Files
dune-dashboard/templates/server.html
T
Reditus 65a1948fd1 feat: add backup/restore with encryption, scheduling, and node resource charts
- Full backup: game DB, K8s manifests, RMQ config, dashboard schema
- AES-256-GCM encryption with PBKDF2 key derivation
- Restore wizard with SSH-based deployment to new VM
- Dashboard schema backup (bans, audit, chat, player_ips, settings)
- Scheduled backups: interval mode (days/hours/mins) or specific days + multiple times
- Retention policy (auto-delete oldest backups beyond keep limit)
- Password protection with sidecar metadata for preview without unlock
- Verify with optional password for encrypted archives
- Node resource charts (CPU/memory) with 5-min history on server page
- csrfFetch moved to head for correct script execution order
2026-06-14 10:12:27 +01:00

789 lines
40 KiB
HTML

{% extends "base.html" %}
{% block title %}Server - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Server Status &amp; Control</h1>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div class="stats-grid">
<div class="stat-card">
<div class="label">Online Players</div>
<div class="value online">{{ online_count }}</div>
</div>
<div class="stat-card">
<div class="label">Overmap Players</div>
<div class="value">{{ overmap_count }}</div>
</div>
<div class="stat-card">
<div class="label">Active Servers</div>
<div class="value">{{ active_servers|length }}</div>
</div>
<div class="stat-card">
<div class="label">World Partitions</div>
<div class="value">{{ partitions|length }}</div>
</div>
{% if node_metrics.cpu %}
<div class="stat-card">
<div class="label">Node CPU</div>
<div class="value" id="node-cpu">{{ node_metrics.cpu }}</div>
</div>
<div class="stat-card">
<div class="label">Node Memory</div>
<div class="value" id="node-mem">{{ node_metrics.memory }}</div>
</div>
{% endif %}
</div>
<div class="card chart-panel">
<div class="card-header">Node Resources <span class="chart-hint">5-minute history, updated every 5s</span></div>
<div class="card-body chart-panel-body">
<div class="chart-box">
<canvas id="chart-cpu" height="120"></canvas>
</div>
<div class="chart-box">
<canvas id="chart-mem" height="120"></canvas>
</div>
</div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
<div class="card">
<div class="card-header">Players Per Map</div>
<div class="card-body">
{% if per_map %}
{% for m in per_map %}
<div class="faction-bar">
<span class="bar-label" style="font-weight:600;">{{ m.map }}</span>
<div class="bar-bg">
<div class="bar-fill" style="background:var(--primary);width:{{ (m.count / online_count * 100)|round(1) if online_count > 0 else 0 }}%;min-width:2px;"></div>
</div>
<span class="bar-count">{{ m.count }}</span>
</div>
{% endfor %}
{% else %}
<div class="empty">No data</div>
{% endif %}
</div>
</div>
<div class="card">
<div class="card-header">Online Players</div>
<div class="card-body">
{% if online_players %}
<table style="width:100%;">
{% for p in online_players %}
<tr>
<td><a href="/players/{{ p.character_name }}" style="font-weight:500;">{{ p.character_name or 'Unknown' }}</a></td>
<td>{{ p.map or 'N/A' }}</td>
<td><span class="badge badge-{{ p.online_status.lower() }}">{{ p.online_status }}</span></td>
</tr>
{% endfor %}
</table>
{% else %}
<div class="empty">No players online</div>
{% endif %}
</div>
</div>
</div>
<div class="card">
<div class="card-header">Active Server IDs</div>
<div class="card-body">
{% if active_servers %}
<div class="table-wrap">
<table>
<thead><tr><th>Server ID</th><th>Map</th><th>Actions</th></tr></thead>
<tbody>
{% for s in active_servers %}
<tr>
<td style="font-family:monospace;font-size:12px;font-weight:600;">{{ s.server_id }}</td>
<td style="color:var(--primary);">{{ s.map or '' }}</td>
<td>
{% if s.deployment %}
<button class="partition-btn" data-deploy="{{ s.deployment }}" data-map="{{ s.server_id }}" title="Restart this server's deployment. Players on this map will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
{% elif not deployments %}
<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>
{% else %}
<span style="color:var(--text-muted);font-size:11px;">No deploy</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="empty">No active servers</div>
{% endif %}
</div>
</div>
</div>
<div class="card">
<div class="card-header">World Partitions</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Partition ID</th><th>Server ID</th><th>Map</th><th>Dimension</th><th>Blocked</th><th>Label</th><th>Actions</th></tr>
</thead>
<tbody>
{% for p in partitions %}
<tr>
<td>{{ p.partition_id }}</td>
<td style="font-family:monospace;font-size:11px;">{{ p.server_id }}</td>
<td>{{ p.map }}</td>
<td>{{ p.dimension_index }}</td>
<td>{{ 'Yes' if p.blocked else 'No' }}</td>
<td>{{ p.label or '' }}</td>
<td>{% if p.deployment %}<div style="display:flex;gap:4px;flex-wrap:wrap;"><button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Restart this partition's deployment. Players on this map will disconnect." style="padding:4px 10px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Restart</button><button class="partition-status-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Show rollout status for this partition's deployment." style="padding:4px 10px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Status</button></div>{% elif not deployments %}<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>{% else %}<span style="color:var(--text-muted);font-size:11px;">No deploy</span>{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="7" class="empty">No partitions found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Kubernetes Deployments</span>
{% if deploys_ok %}
<span style="font-size:12px;color:var(--success);">SSH connected</span>
{% else %}
<span style="font-size:12px;color:var(--danger);">SSH unavailable (key not loaded or VM unreachable)</span>
{% endif %}
</div>
<div class="card-body">
{% if deploys_ok %}
<div style="margin-bottom:10px;padding:10px;background:var(--bg);border-radius:6px;font-size:12px;line-height:1.5;color:var(--text-light);">
<strong>Button Guide:</strong>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e67e22;">Restart</span> — rolling restart of pods</span>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#3498db;">Status</span> — rollout status</span>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e74c3c;">Scale to 0</span> — stop all pods</span>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#27ae60;">Scale to 1</span> — start a pod</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Deployment</th><th>Actions</th></tr></thead>
<tbody>
{% for d in deployments %}
<tr>
<td style="font-family:monospace;font-size:13px;">{{ d.replace('deployment.apps/','') }}</td>
<td>
<button class="btn-action" data-deploy="{{ d }}" data-action="restart" title="Performs a rolling restart of this deployment's pods. Players will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="status" title="Show rollout status: whether the deployment is successfully rolled out, pending, or failed." style="padding:4px 12px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Status</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_0" title="Scale to 0 replicas. Stops all pods for this deployment. Use to shut down a server." style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 0</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" title="Scale to 1 replica. Starts a single pod. Use to bring a stopped server back online." style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p style="color:var(--text-light);font-size:14px;">
To enable server control, ensure the SSH key is available at
<code>$env:TEMP\dune-awakening-server-sshKey</code> and the VM is reachable.
</p>
{% if ssh_error %}
<pre style="background:var(--bg);color:var(--danger);padding:12px;border-radius:6px;font-size:12px;margin-top:8px;">{{ ssh_error }}</pre>
{% endif %}
{% endif %}
<div id="action-output" style="margin-top:16px;display:none;">
<div class="card-header">Command Output</div>
<pre id="action-output-text" style="background:var(--bg);color:var(--text);padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;margin-top:8px;"></pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Battlegroup Control</span>
<span id="bg-status-indicator" style="font-size:12px;color:var(--text-muted);">Click "Refresh Status" to load</span>
</div>
<div class="card-body">
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;">
<button id="bg-btn-start" class="bg-btn" style="padding:8px 20px;background:#27ae60;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Start</button>
<button id="bg-btn-stop" class="bg-btn" style="padding:8px 20px;background:#e74c3c;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Stop</button>
<button id="bg-btn-restart" class="bg-btn" style="padding:8px 20px;background:#e67e22;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Restart</button>
<button id="bg-btn-update" class="bg-btn" style="padding:8px 20px;background:#9b59b6;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Update</button>
<button id="bg-btn-refresh" style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh Status</button>
</div>
<div id="bg-status-output">
<pre id="bg-status-text" style="background:var(--bg);color:var(--text);padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;min-height:100px;">Click "Refresh Status" to load battlegroup status...</pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header">Pod Status</div>
<div class="card-body">
<button id="refresh-pods" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh Pods</button>
<div id="pods-output" style="margin-top:12px;">
<pre id="pods-text" style="background:var(--bg);color:var(--text);padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;">Click refresh to load pod status...</pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header" style="cursor:pointer;" onclick="document.getElementById('debug-section').classList.toggle('hidden');">
<span>🐛 Debug Logging</span>
<span id="debug-status" style="font-size:12px;color:var(--text-muted);">Loading...</span>
</div>
<div class="card-body" id="debug-section">
<div style="margin-bottom:12px;padding:12px;background:var(--bg);border-radius:6px;font-size:13px;line-height:1.6;color:var(--text);">
<strong style="color:var(--primary);">📝 Verbose Logging:</strong> Enable to log detailed information about SSH commands, API requests, database queries, and service connections.
Logs are written to <code>logs/debug.log</code>. Sanitizes sensitive data (passwords, tokens) automatically.
</div>
<div style="display:flex;align-items:center;gap:16px;">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
<input type="checkbox" id="debug-toggle" style="width:18px;height:18px;">
<span style="font-size:14px;">Enable debug logging</span>
</label>
<span id="debug-indicator" style="font-size:12px;color:var(--text-muted);"></span>
</div>
</div>
</div>
<div class="card">
<div class="card-header" style="cursor:pointer;" onclick="document.getElementById('audit-section').classList.toggle('hidden');">
<span>📋 Audit Log Viewer</span>
<span id="audit-stats" style="font-size:12px;color:var(--text-muted);">Loading...</span>
</div>
<div class="card-body" id="audit-section">
<div style="margin-bottom:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
<input type="text" id="audit-search" placeholder="Filter by action..." style="padding:8px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;width:180px;">
<input type="text" id="audit-user" placeholder="Filter by user..." style="padding:8px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;width:140px;">
<select id="audit-severity" style="padding:8px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
<option value="">All Severities</option>
<option value="info">Info</option>
<option value="warning">Warning</option>
<option value="error">Error</option>
</select>
<button onclick="loadAuditLogs()" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Filter</button>
<button onclick="refreshAuditLogs()" style="padding:8px 16px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Refresh</button>
</div>
<div style="margin-bottom:12px;display:flex;gap:16px;font-size:12px;color:var(--text-muted);">
<span>Total: <strong id="audit-total">0</strong></span>
<span>Info: <strong id="audit-info-count" style="color:#3498db;">0</strong></span>
<span>Warning: <strong id="audit-warning-count" style="color:#f39c12;">0</strong></span>
<span>Error: <strong id="audit-error-count" style="color:#e74c3c;">0</strong></span>
</div>
<div id="audit-logs-container" style="max-height:300px;overflow-y:auto;">
<table style="width:100%;border-collapse:collapse;font-size:12px;">
<thead style="position:sticky;top:0;background:var(--table-header);">
<tr style="text-align:left;color:var(--text-muted);">
<th style="padding:8px;border-bottom:1px solid var(--border);">Time</th>
<th style="padding:8px;border-bottom:1px solid var(--border);">Action</th>
<th style="padding:8px;border-bottom:1px solid var(--border);">User</th>
<th style="padding:8px;border-bottom:1px solid var(--border);">Severity</th>
<th style="padding:8px;border-bottom:1px solid var(--border);">Details</th>
</tr>
</thead>
<tbody id="audit-logs-body">
<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--text-muted);">Loading...</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Firewall Security</span>
<span id="fw-status-indicator" style="font-size:12px;color:var(--text-muted);">Loading...</span>
</div>
<div class="card-body">
<div style="margin-bottom:12px;padding:12px;background:var(--bg);border-radius:6px;font-size:13px;line-height:1.6;">
<strong style="color:#e74c3c;">Security Recommendation:</strong> The following services are exposed to the internet without authentication.
Block them so only localhost (the dashboard via SSH tunnel) can reach them.
</div>
<div id="fw-ports-list" style="margin-bottom:16px;"></div>
<button id="fw-btn-refresh" style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh Status</button>
<div id="fw-action-output" style="margin-top:12px;display:none;">
<pre id="fw-action-text" style="background:var(--bg);color:var(--text);padding:12px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;"></pre>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
// ── Node resource charts ──────────────────────────────────────────────
const MAX_POINTS = 720; // 1 hour at 5s intervals
const SPARKLINE_POINTS = 60; // 5 min for sparkline
let metricsHistory = []; // [{cpu_num, memory_gib, memory_pct_num, memory, cpu, ts}]
function parseCSSVar(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
function drawCharts(history) {
const cpuVals = history.map(p => p.cpu_num);
const memVals = history.map(p => p.memory_gib);
const primaryColor = parseCSSVar('--primary') || '#c9a24e';
const successColor = parseCSSVar('--success') || '#27ae60';
const chartCpu = document.getElementById('chart-cpu');
const chartMem = document.getElementById('chart-mem');
if (!chartCpu || !window.Chart) return;
if (!window._cpuChart) {
const textColor = parseCSSVar('--text-muted') || '#9a8a7a';
const gridColor = parseCSSVar('--border') || '#e0d5c7';
const commonOpts = {
responsive: true, maintainAspectRatio: false,
animation: { duration: 300 },
plugins: { legend: { display: false } },
scales: {
x: { display: true, grid: { color: gridColor }, ticks: { color: textColor, font: { size: 10 }, maxTicksLimit: 8 } },
y: { display: true, grid: { color: gridColor }, ticks: { color: textColor, font: { size: 10 } } }
}
};
window._cpuChart = new Chart(chartCpu, {
type: 'line',
data: { labels: [], datasets: [{ label: 'CPU %', data: [], borderColor: primaryColor, backgroundColor: primaryColor + '20', fill: true, pointRadius: 0, borderWidth: 2, tension: 0.3 }] },
options: { ...commonOpts, scales: { ...commonOpts.scales, y: { ...commonOpts.scales.y, min: 0, max: 100, title: { display: true, text: 'CPU %', color: textColor, font: { size: 11 } } } } }
});
const memMax = window._totalMemGib ? Math.ceil(window._totalMemGib) : undefined;
window._memChart = new Chart(chartMem, {
type: 'line',
data: { labels: [], datasets: [{ label: 'Memory GiB', data: [], borderColor: successColor, backgroundColor: successColor + '20', fill: true, pointRadius: 0, borderWidth: 2, tension: 0.3 }] },
options: { ...commonOpts, scales: { ...commonOpts.scales, y: { ...commonOpts.scales.y, beginAtZero: true, max: memMax, title: { display: true, text: 'GiB', color: textColor, font: { size: 11 } } } } }
});
}
const labels = history.map(p => p.ts);
window._cpuChart.data.labels = labels;
window._cpuChart.data.datasets[0].data = cpuVals;
window._cpuChart.data.datasets[0].borderColor = primaryColor;
window._cpuChart.data.datasets[0].backgroundColor = primaryColor + '20';
window._cpuChart.update('none');
window._memChart.data.labels = labels;
window._memChart.data.datasets[0].data = memVals;
window._memChart.data.datasets[0].borderColor = successColor;
window._memChart.data.datasets[0].backgroundColor = successColor + '20';
if (window._totalMemGib) {
window._memChart.options.scales.y.max = Math.ceil(window._totalMemGib);
}
window._memChart.update('none');
}
async function fetchMetrics() {
try {
const resp = await fetch('/server/metrics');
const data = await resp.json();
if (data.cpu) {
document.getElementById('node-cpu').textContent = data.cpu;
const memPctNum = data.memory_pct_num || 0;
const memGib = data.memory_gib || 0;
if (!window._totalMemGib && memPctNum > 0) {
window._totalMemGib = memGib / (memPctNum / 100);
}
document.getElementById('node-mem').textContent = data.memory;
const now = new Date();
const ts = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0') + ':' + now.getSeconds().toString().padStart(2, '0');
const point = { cpu_num: data.cpu_num || 0, memory_gib: memGib, memory_pct_num: memPctNum, memory: data.memory, cpu: data.cpu, ts: ts };
metricsHistory.push(point);
if (metricsHistory.length > MAX_POINTS) metricsHistory.shift();
drawCharts(metricsHistory);
}
} catch (e) {}
}
function loadChartJS(src) {
return new Promise((resolve, reject) => {
if (window.Chart) { resolve(); return; }
const s = document.createElement('script');
s.src = src; s.onload = resolve; s.onerror = reject;
document.head.appendChild(s);
});
}
loadChartJS('https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js').then(() => {
fetchMetrics();
setInterval(fetchMetrics, 5000);
}).catch(() => {
// Chart.js failed to load, still update text values
setInterval(fetchMetrics, 5000);
});
document.querySelectorAll('.btn-action').forEach(btn => {
btn.addEventListener('click', async function() {
const deploy = this.dataset.deploy;
const action = this.dataset.action;
const label = this.textContent.trim();
if (action === 'restart' || action === 'scale_0') {
const confirmMsg = action === 'restart'
? `Restart deployment "${deploy}"?`
: `Scale deployment "${deploy}" to 0 replicas (shutdown)?`;
if (!confirm(confirmMsg)) return;
if (!confirm('Are you sure? This will affect live players.')) return;
}
this.disabled = true;
this.textContent = 'Working...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
outputText.textContent = `Running ${action} on ${deploy}...`;
try {
const form = new FormData();
form.append('deployment', deploy);
form.append('action', action);
const resp = await csrfFetch('/server/action', { method: 'POST', body: form });
const data = await resp.json();
outputText.textContent = data.output || (data.success ? 'Done' : 'Failed');
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = label;
});
});
document.querySelectorAll('.partition-btn').forEach(btn => {
btn.addEventListener('click', async function() {
const deploy = this.dataset.deploy;
const map = this.dataset.map;
const label = this.textContent.trim();
if (!confirm(`Restart "${map}" partition (${deploy})?`)) return;
if (!confirm('Are you sure? Players on this map will be disconnected.')) return;
this.disabled = true;
this.textContent = 'Working...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
outputText.textContent = `Restarting ${deploy}...`;
try {
const form = new FormData();
form.append('deployment', deploy);
form.append('action', 'restart');
const resp = await csrfFetch('/server/action', { method: 'POST', body: form });
const data = await resp.json();
outputText.textContent = data.output || (data.success ? 'Restart initiated' : 'Failed');
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = label;
});
});
document.querySelectorAll('.partition-status-btn').forEach(btn => {
btn.addEventListener('click', async function() {
const deploy = this.dataset.deploy;
const map = this.dataset.map;
const label = this.textContent.trim();
this.disabled = true;
this.textContent = 'Loading...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
outputText.textContent = `Fetching status for ${deploy}...`;
try {
const form = new FormData();
form.append('deployment', deploy);
form.append('action', 'status');
const resp = await csrfFetch('/server/action', { method: 'POST', body: form });
const data = await resp.json();
outputText.textContent = data.output || (data.success ? 'No status output' : 'Failed');
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = label;
});
});
async function refreshPods() {
const btn = document.getElementById('refresh-pods');
const pre = document.getElementById('pods-text');
if (btn) { btn.disabled = true; btn.textContent = 'Loading...'; }
pre.textContent = 'Fetching pod list...';
try {
const resp = await fetch('/server/pods');
const data = await resp.json();
pre.textContent = data.output || (data.success ? 'No pods found' : 'Failed: ' + data.output);
} catch (e) {
pre.textContent = 'Error: ' + e.message;
}
if (btn) { btn.disabled = false; btn.textContent = 'Refresh Pods'; }
}
document.getElementById('refresh-pods')?.addEventListener('click', refreshPods);
async function bgAction(action, btn) {
const confirmMsgs = {
'stop': 'Stop the battlegroup? This will disconnect all players.',
'restart': 'Restart the battlegroup? This will disconnect all players.',
'update': 'Update the battlegroup? This will download new images and restart. This may take several minutes.'
};
if (confirmMsgs[action] && !confirm(confirmMsgs[action])) return;
if ((action === 'stop' || action === 'restart') && !confirm('Are you sure? This will affect live players.')) return;
btn.disabled = true;
const originalText = btn.textContent;
btn.textContent = action === 'update' ? 'Updating (may take several minutes)...' : 'Working...';
const pre = document.getElementById('bg-status-text');
pre.textContent = `Running ${action}...`;
try {
const url = action === 'update' ? '/server/battlegroup/update' : '/server/battlegroup/action';
const form = new FormData();
form.append('action', action);
const resp = await csrfFetch(url, { method: 'POST', body: form });
const data = await resp.json();
pre.textContent = data.output || (data.success ? `${action} completed successfully` : `Failed: ${data.output}`);
} catch (e) {
pre.textContent = 'Error: ' + e.message;
}
btn.disabled = false;
btn.textContent = originalText;
}
async function bgRefreshStatus() {
const btn = document.getElementById('bg-btn-refresh');
const pre = document.getElementById('bg-status-text');
const indicator = document.getElementById('bg-status-indicator');
btn.disabled = true;
btn.textContent = 'Loading...';
pre.textContent = 'Fetching battlegroup status...';
try {
const resp = await fetch('/server/battlegroup/status');
const data = await resp.json();
pre.textContent = data.output || (data.success ? 'No status available' : 'Failed: ' + data.output);
indicator.textContent = data.success ? 'Status loaded' : 'Failed to load';
indicator.style.color = data.success ? 'var(--success)' : 'var(--danger)';
} catch (e) {
pre.textContent = 'Error: ' + e.message;
indicator.textContent = 'Error';
indicator.style.color = 'var(--danger)';
}
btn.disabled = false;
btn.textContent = 'Refresh Status';
}
document.getElementById('bg-btn-start')?.addEventListener('click', function() { bgAction('start', this); });
document.getElementById('bg-btn-stop')?.addEventListener('click', function() { bgAction('stop', this); });
document.getElementById('bg-btn-restart')?.addEventListener('click', function() { bgAction('restart', this); });
document.getElementById('bg-btn-update')?.addEventListener('click', function() { bgAction('update', this); });
document.getElementById('bg-btn-refresh')?.addEventListener('click', bgRefreshStatus);
// Firewall Security
async function loadFwStatus() {
const indicator = document.getElementById('fw-status-indicator');
const list = document.getElementById('fw-ports-list');
const btn = document.getElementById('fw-btn-refresh');
btn.disabled = true;
btn.textContent = 'Loading...';
indicator.textContent = 'Checking...';
try {
const resp = await fetch('/server/firewall');
const data = await resp.json();
if (!data.success) {
indicator.textContent = 'SSH unavailable';
indicator.style.color = 'var(--danger)';
list.innerHTML = '<p style="color:var(--text-light);font-size:14px;">SSH tunnel is required for firewall control.</p>';
btn.disabled = false;
btn.textContent = 'Refresh Status';
return;
}
const allPorts = [...(data.blocked || []), ...(data.available || [])];
let html = '<table style="width:100%;font-size:13px;"><thead><tr><th>Service</th><th>Port</th><th>Status</th><th>Action</th></tr></thead><tbody>';
for (const p of allPorts) {
const portDisplay = p.port !== null && p.port !== undefined ? p.port : 'N/A';
const hasPort = p.port !== null && p.port !== undefined;
const isBlocked = hasPort && (data.blocked || []).some(b => b.port === p.port);
const rules = hasPort ? Object.values(data.iptables_rules || {}).filter(r => r.includes('dpt:' + p.port)) : [];
const statusText = !hasPort ? '<span style="color:var(--text-muted);font-style:italic;">Not running</span>' : (isBlocked ? '<span style="color:#4ade80;font-weight:600;">Blocked</span>' : '<span style="color:#e74c3c;font-weight:600;">Open</span>');
const actionBtn = !hasPort
? '<span style="color:var(--text-muted);font-size:11px;">Start battlegroup to enable</span>'
: (isBlocked
? `<button class="fw-btn" data-port="${p.port}" data-action="unblock" style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Unblock</button>`
: `<button class="fw-btn" data-port="${p.port}" data-action="block" style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Block</button>`);
html += `<tr><td style="padding:6px 0;">${p.name}</td><td style="font-family:monospace;">${portDisplay}</td><td>${statusText}</td><td>${actionBtn}</td></tr>`;
}
html += '</tbody></table>';
list.innerHTML = html;
indicator.textContent = 'Status loaded';
indicator.style.color = 'var(--success)';
document.querySelectorAll('.fw-btn').forEach(btn => {
btn.addEventListener('click', async function() {
const port = this.dataset.port;
const action = this.dataset.action;
if (!confirm((action === 'block' ? 'Block' : 'Unblock') + ' port ' + port + ' from external access?')) return;
this.disabled = true;
this.textContent = 'Working...';
const output = document.getElementById('fw-action-output');
const outputText = document.getElementById('fw-action-text');
output.style.display = 'block';
outputText.textContent = (action === 'block' ? 'Blocking' : 'Unblocking') + ' port ' + port + '...';
try {
const form = new FormData();
form.append('port', port);
const resp = await csrfFetch('/server/firewall/' + action, { method: 'POST', body: form });
const result = await resp.json();
outputText.textContent = result.output || (result.success ? 'Done' : 'Failed');
await loadFwStatus();
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
});
});
} catch (e) {
indicator.textContent = 'Error loading status';
indicator.style.color = 'var(--danger)';
list.innerHTML = '<p style="color:var(--danger);">Error: ' + e.message + '</p>';
}
btn.disabled = false;
btn.textContent = 'Refresh Status';
}
document.getElementById('fw-btn-refresh')?.addEventListener('click', loadFwStatus);
loadFwStatus();
// Audit Log Viewer
async function loadAuditLogs(action = '', user = '', severity = '', limit = 100, offset = 0) {
const tbody = document.getElementById('audit-logs-body');
const actionFilter = document.getElementById('audit-search').value;
const userFilter = document.getElementById('audit-user').value;
const severityFilter = document.getElementById('audit-severity').value;
try {
let url = '/api/audit/logs?limit=' + limit + '&offset=' + offset;
if (actionFilter) url += '&action=' + encodeURIComponent(actionFilter);
if (userFilter) url += '&user=' + encodeURIComponent(userFilter);
const resp = await fetch(url);
const data = await resp.json();
if (!data.success) {
tbody.innerHTML = '<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--danger);">Error: ' + data.error + '</td></tr>';
return;
}
const logs = data.logs || [];
if (logs.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--text-muted);">No audit logs found</td></tr>';
document.getElementById('audit-total').textContent = '0';
return;
}
// Update stats
const infoCount = logs.filter(l => l.severity === 'info').length;
const warningCount = logs.filter(l => l.severity === 'warning').length;
const errorCount = logs.filter(l => l.severity === 'error').length;
document.getElementById('audit-total').textContent = logs.length;
document.getElementById('audit-info-count').textContent = infoCount;
document.getElementById('audit-warning-count').textContent = warningCount;
document.getElementById('audit-error-count').textContent = errorCount;
// Render table
tbody.innerHTML = logs.map(log => {
const details = log.details ? JSON.stringify(log.details) : '-';
const severityColor = log.severity === 'error' ? 'color:#e74c3c;' : (log.severity === 'warning' ? 'color:#f39c12;' : 'color:#3498db;');
const timestamp = log.timestamp ? log.timestamp.replace('T', ' ').substring(0, 19) : '-';
return '<tr style="border-bottom:1px solid var(--border);">' +
'<td style="padding:8px;color:var(--text-muted);">' + timestamp + '</td>' +
'<td style="padding:8px;font-weight:600;">' + (log.action || '-') + '</td>' +
'<td style="padding:8px;">' + (log.user || '-') + '</td>' +
'<td style="padding:8px;' + severityColor + '">' + (log.severity || 'info') + '</td>' +
'<td style="padding:8px;color:var(--text-muted);font-size:11px;max-width:200px;overflow:hidden;text-overflow:ellipsis;">' + details + '</td>' +
'</tr>';
}).join('');
} catch (e) {
tbody.innerHTML = '<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--danger);">Error: ' + e.message + '</td></tr>';
}
}
function refreshAuditLogs() {
loadAuditLogs();
}
// Load audit stats on page load
loadAuditLogs();
// Debug Logging
const debugToggle = document.getElementById('debug-toggle');
const debugStatus = document.getElementById('debug-status');
const debugIndicator = document.getElementById('debug-indicator');
async function loadDebugStatus() {
try {
const resp = await csrfFetch('/api/settings');
const data = await resp.json();
if (data.success) {
const debugEnabled = data.settings.logging.debug_enabled;
debugToggle.checked = debugEnabled;
if (debugEnabled) {
debugStatus.innerHTML = '<span style="color:var(--success);">✓ Enabled</span>';
debugIndicator.textContent = 'Debug logs writing to logs/debug.log';
} else {
debugStatus.innerHTML = '<span style="color:var(--text-muted);">○ Disabled</span>';
debugIndicator.textContent = '';
}
}
} catch (e) {
console.error('Failed to load debug status:', e);
}
}
debugToggle.addEventListener('change', async function() {
const enabled = this.checked;
try {
const resp = await csrfFetch('/api/settings/debug', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: enabled })
});
const data = await resp.json();
if (data.success) {
if (enabled) {
debugStatus.innerHTML = '<span style="color:var(--success);">✓ Enabled</span>';
debugIndicator.textContent = 'Debug logs writing to logs/debug.log';
alert('Debug logging enabled! Logs will be written to logs/debug.log');
} else {
debugStatus.innerHTML = '<span style="color:var(--text-muted);">○ Disabled</span>';
debugIndicator.textContent = '';
alert('Debug logging disabled.');
}
} else {
alert('Failed to toggle debug: ' + (data.error || 'Unknown error'));
this.checked = !enabled;
}
} catch (e) {
alert('Error toggling debug: ' + e.message);
this.checked = !enabled;
}
});
// Load debug status on page load
loadDebugStatus();
// Auto-load battlegroup and pods once on page load, then require manual refresh
bgRefreshStatus();
refreshPods();
</script>
{% endblock %}