Compare commits

...
4 Commits
Author SHA1 Message Date
Reditus 306ebcc871 feat: vertical/horizontal nav layout toggle with grouped dropdowns, mobile auto-sidebar 2026-06-14 22:54:55 +01:00
Reditus 3486f3b2cb feat: pod management UI (logs, describe, delete, list) with csrfFetch fix 2026-06-14 12:01:27 +01:00
Reditus 42eec81081 fix: SSH keepalive, director fallback, Ctrl+C handler, namespace ordering
- SSH transport keepalive (15s) + stale client cleanup for reliable reconnection
- Ctrl+C signal handler (os._exit) to bypass stuck daemon threads
- Director API fallback: SSH + wget to BGD service cluster IP (no tunnel needed)
- Namespace auto-detection moved before DirectorService creation
- Director host defaults to 127.0.0.1 (configurable via director.host)
- Connection monitor: 60s -> 30s interval
- Backup scheduler: skip if SSH unreachable instead of blocking 300s
2026-06-14 11:09:31 +01:00
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
17 changed files with 2542 additions and 41 deletions

No files matched your search

+4
View File
@@ -29,6 +29,8 @@ chmod +x start.sh
- **Chat Logs** with channel filtering and auto-refresh - **Chat Logs** with channel filtering and auto-refresh
- **Director Tools** (battlegroups, world state, transfers) - **Director Tools** (battlegroups, world state, transfers)
- **SSH File Browser** + **in-browser shell** - **SSH File Browser** + **in-browser shell**
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
- **Nav Layout** — switch between horizontal and vertical sidebar; persists preference; auto-enables sidebar on mobile
- **Firewall Hardening** via iptables - **Firewall Hardening** via iptables
- **Auto‑Update** with safe file replacement - **Auto‑Update** with safe file replacement
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt) - **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
@@ -36,6 +38,8 @@ chmod +x start.sh
- **Organized Logging** with automatic cleanup and redaction - **Organized Logging** with automatic cleanup and redaction
- **Debug Mode** with full SSH/K8s tracing - **Debug Mode** with full SSH/K8s tracing
- **SSH Key Rotation** — scan all key locations and sync the newest key - **SSH Key Rotation** — scan all key locations and sync the newest key
- **Backup & Restore** — full server snapshots (game DB, K8s resources, RMQ config, dashboard schema) with optional AES-256 encryption and password protection
- **Scheduled Backups** — configurable interval or day/time-based scheduling with automatic retention cleanup
--- ---
+1
View File
@@ -46,6 +46,7 @@ DEFAULTS = {
'battlegroup_script': '/home/dune/.dune/bin/battlegroup', 'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
}, },
'director': { 'director': {
'host': '',
'port': 32479, 'port': 32479,
}, },
'filebrowser': { 'filebrowser': {
+52 -10
View File
@@ -6,6 +6,7 @@ import time
import logging import logging
import logging.handlers import logging.handlers
import threading import threading
from datetime import datetime
from flask import Flask, request, g from flask import Flask, request, g
from flask_login import current_user from flask_login import current_user
from flask_socketio import SocketIO from flask_socketio import SocketIO
@@ -25,6 +26,7 @@ from app.services.admin import AdminService
from app.services.updater import UpdateService from app.services.updater import UpdateService
from app.services.director import DirectorService from app.services.director import DirectorService
from app.services.rmq import RmqService from app.services.rmq import RmqService
from app.services.backup import BackupService
from app.utils.cache import MultiCache from app.utils.cache import MultiCache
from app.routes.main import register_routes from app.routes.main import register_routes
from app.routes.api import register_api_routes from app.routes.api import register_api_routes
@@ -236,6 +238,16 @@ def create_app(settings_path=None):
) )
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}") logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
# Auto-detect namespace if not set in config — must run before
# services that consume the namespace (director, backup, etc.).
if settings['kubernetes']['namespace'] == '':
try:
k8s_service.auto_detect_namespace()
if k8s_service.namespace:
settings['kubernetes']['namespace'] = k8s_service.namespace
except Exception as e:
logging.warning(f"Could not auto-detect K8s namespace: {e}")
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl']) static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
player_svc = PlayerService(db_service, dash_db=dash_db_service) player_svc = PlayerService(db_service, dash_db=dash_db_service)
@@ -247,7 +259,7 @@ def create_app(settings_path=None):
updater_svc = UpdateService(base_dir) updater_svc = UpdateService(base_dir)
logging.debug("UpdateService initialized") logging.debug("UpdateService initialized")
director_svc = DirectorService( director_svc = DirectorService(
host='127.0.0.1', host=settings.get('director', {}).get('host') or '127.0.0.1',
node_port=settings.get('director', {}).get('port', 32479), node_port=settings.get('director', {}).get('port', 32479),
k8s_service=k8s_service, k8s_service=k8s_service,
ssh_service=ssh_service, ssh_service=ssh_service,
@@ -262,6 +274,9 @@ def create_app(settings_path=None):
) )
logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}") logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}")
backup_svc = BackupService(ssh_service, k8s_service, rmq_svc, settings)
logging.debug("BackupService initialized")
services = { services = {
'db': db_service, 'db': db_service,
'dash_db': dash_db_service, 'dash_db': dash_db_service,
@@ -275,6 +290,7 @@ def create_app(settings_path=None):
'updater': updater_svc, 'updater': updater_svc,
'director': director_svc, 'director': director_svc,
'rmq': rmq_svc, 'rmq': rmq_svc,
'backup': backup_svc,
} }
logging.debug(f"All services registered: {list(services.keys())}") logging.debug(f"All services registered: {list(services.keys())}")
@@ -313,14 +329,6 @@ def create_app(settings_path=None):
def cleanup_db(exc): def cleanup_db(exc):
pass pass
if settings['kubernetes']['namespace'] == '':
try:
k8s_service.auto_detect_namespace()
if k8s_service.namespace:
settings['kubernetes']['namespace'] = k8s_service.namespace
except Exception as e:
logging.warning(f"Could not auto-detect K8s namespace: {e}")
# Check SSL certificate expiry and start background monitor # Check SSL certificate expiry and start background monitor
if ssl_enabled: if ssl_enabled:
try: try:
@@ -422,7 +430,7 @@ def create_app(settings_path=None):
def _connection_monitor(): def _connection_monitor():
"""Background thread that monitors and auto-reconnects services.""" """Background thread that monitors and auto-reconnects services."""
import time import time
check_interval = 60 # Check every 60 seconds check_interval = 30 # Check every 30 seconds
consecutive_failures = 0 consecutive_failures = 0
max_consecutive_failures = 5 max_consecutive_failures = 5
last_ssh_ok = True # Track SSH state to detect reconnection last_ssh_ok = True # Track SSH state to detect reconnection
@@ -496,6 +504,40 @@ def create_app(settings_path=None):
except Exception as e: except Exception as e:
logging.debug(f"Could not initialize connection monitor: {e}") logging.debug(f"Could not initialize connection monitor: {e}")
# ── Backup Scheduler ──────────────────────────────────────────────────
try:
backup_svc = services.get('backup')
if backup_svc:
def _backup_scheduler():
while True:
time.sleep(60)
try:
cfg = backup_svc.load_schedule()
if not cfg.get('enabled'):
continue
next_str = cfg.get('next_run', '')
if not next_str:
continue
try:
next_ts = datetime.fromisoformat(next_str).timestamp()
except Exception:
continue
if time.time() >= next_ts:
ssh_svc = services.get('ssh')
if ssh_svc and not ssh_svc.check_connection():
logging.warning('Backup scheduler: SSH unavailable, skipping backup')
continue
logging.info('Backup scheduler: Triggering scheduled backup')
backup_svc.run_scheduled_backup()
except Exception as e:
logging.error(f'Backup scheduler: {e}')
sched_thread = threading.Thread(target=_backup_scheduler, daemon=True)
sched_thread.start()
logging.info('Backup scheduler: Background thread started')
except Exception as e:
logging.debug(f'Could not start backup scheduler: {e}')
app.dune_settings = settings app.dune_settings = settings
app.dune_services = services app.dune_services = services
+179
View File
@@ -38,6 +38,7 @@ def register_api_routes(app, services, settings):
chat_svc = services['chat'] chat_svc = services['chat']
admin_svc = services['admin'] admin_svc = services['admin']
vehicle_svc = services['vehicle'] vehicle_svc = services['vehicle']
backup_svc = services.get('backup')
audit_svc = services.get('audit') audit_svc = services.get('audit')
# Get or create rate limiter - use existing one from factory if available # Get or create rate limiter - use existing one from factory if available
@@ -1114,6 +1115,79 @@ def register_api_routes(app, services, settings):
except Exception as e: except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
# Pod actions (list, logs, delete, describe)
@app.route('/api/pods')
@auth_req
def api_pods_list():
try:
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(
f'sudo kubectl get pods -n {ns} -o custom-columns=NAME:.metadata.name,ROLE:.metadata.labels.role,STATUS:.status.phase')
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list pods'})
pods = []
for line in (out or '').strip().split('\n')[1:]:
parts = line.split(None, 2)
if len(parts) >= 3:
pods.append({
'name': parts[0],
'role': parts[1] if parts[1] != '<none>' else '',
'status': parts[2],
})
return jsonify({'success': True, 'pods': pods})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pod/logs', methods=['POST'])
@auth_req
def api_pod_logs():
try:
data = request.get_json(force=True) or {}
pod = data.get('pod', '').strip()
if not pod:
return jsonify({'success': False, 'error': 'pod name required'})
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(
f'sudo kubectl logs -n {ns} {pod} --tail=300 2>/dev/null || echo "NO_LOGS"', timeout=15)
if rc != 0 and 'NO_LOGS' not in (out or ''):
return jsonify({'success': False, 'error': err or 'Failed to get logs'})
logs = (out or '').replace('NO_LOGS\n', '').replace('NO_LOGS', '')
return jsonify({'success': True, 'logs': logs, 'pod': pod})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pod/delete', methods=['POST'])
@auth_req
def api_pod_delete():
try:
data = request.get_json(force=True) or {}
pod = data.get('pod', '').strip()
if not pod:
return jsonify({'success': False, 'error': 'pod name required'})
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(f'sudo kubectl delete pod -n {ns} {pod} --wait=false', timeout=30)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to delete pod'})
return jsonify({'success': True, 'message': f'Pod {pod} deleted (will be recreated by its controller)'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pod/describe', methods=['POST'])
@auth_req
def api_pod_describe():
try:
data = request.get_json(force=True) or {}
pod = data.get('pod', '').strip()
if not pod:
return jsonify({'success': False, 'error': 'pod name required'})
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(f'sudo kubectl describe pod -n {ns} {pod}', timeout=30)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to describe pod'})
return jsonify({'success': True, 'describe': out or '', 'pod': pod})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
# Update management # Update management
@app.route('/api/update/status') @app.route('/api/update/status')
@auth_req @auth_req
@@ -1981,3 +2055,108 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'SQL prefix not allowed'}) return jsonify({'success': False, 'error': 'SQL prefix not allowed'})
success, result = admin_svc.admin_db_execute(sql) success, result = admin_svc.admin_db_execute(sql)
return jsonify({'success': success, 'result': result if success else str(result)}) return jsonify({'success': success, 'result': result if success else str(result)})
# ── Backup Endpoints ──────────────────────────────────────────────
if backup_svc:
@app.route('/api/backup/list')
@auth_req
def api_backup_list():
return jsonify({'success': True, 'backups': backup_svc.list_backups()})
@app.route('/api/backup/create', methods=['POST'])
@auth_req
def api_backup_create():
data = request.get_json() or {}
password = data.get('password', '')
result = backup_svc.create_backup(password=password)
return jsonify(result)
@app.route('/api/backup/info', methods=['POST'])
@auth_req
def api_backup_info():
data = request.get_json() or {}
name = data.get('name', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
'backups', f'{name}.tar.gz')
info = backup_svc.get_backup_info(path)
return jsonify({'success': True, 'info': info})
@app.route('/api/backup/delete', methods=['POST'])
@auth_req
def api_backup_delete():
data = request.get_json() or {}
name = data.get('name', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
deleted = backup_svc.delete_backup(name)
return jsonify({'success': deleted})
@app.route('/api/backup/verify', methods=['POST'])
@auth_req
def api_backup_verify():
data = request.get_json() or {}
name = data.get('name', '')
password = data.get('password', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
result = backup_svc.verify_backup(name, password=password)
return jsonify(result)
@app.route('/api/backup/restore/preview', methods=['POST'])
@auth_req
def api_backup_restore_preview():
data = request.get_json() or {}
name = data.get('name', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
result = backup_svc.restore_preview(name)
return jsonify(result)
@app.route('/api/backup/restore/test-connection', methods=['POST'])
@auth_req
def api_backup_test_connection():
result = backup_svc.test_connection()
return jsonify(result)
@app.route('/api/backup/restore/start', methods=['POST'])
@auth_req
def api_backup_restore_start():
data = request.get_json() or {}
name = data.get('name', '')
options = data.get('options', {})
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
result = backup_svc.start_restore(name, options)
return jsonify(result)
@app.route('/api/backup/restore/status', methods=['POST'])
@auth_req
def api_backup_restore_status():
data = request.get_json() or {}
restore_id = data.get('restore_id', '')
if not restore_id:
return jsonify({'success': False, 'error': 'Restore ID required'})
result = backup_svc.get_restore_status(restore_id)
return jsonify(result)
@app.route('/api/backup/schedule', methods=['GET'])
@auth_req
def api_backup_schedule_get():
return jsonify({'success': True, 'schedule': backup_svc.get_schedule()})
@app.route('/api/backup/schedule', methods=['POST'])
@auth_req
def api_backup_schedule_set():
data = request.get_json() or {}
result = backup_svc.update_schedule(data)
return jsonify({'success': True, 'schedule': result})
@app.route('/api/backup/run-scheduled', methods=['POST'])
@auth_req
def api_backup_run_scheduled():
result = backup_svc.run_scheduled_backup()
return jsonify(result)
+8 -1
View File
@@ -4,7 +4,7 @@ import json
import logging import logging
from flask import Blueprint, render_template, request, jsonify from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required, current_user from flask_login import login_required, current_user
from app.utils.constants import NAV_PAGES, GUILD_ROLES from app.utils.constants import NAV_PAGES, NAV_GROUPS, GUILD_ROLES
from app.utils.debug_logging import sanitize_for_log from app.utils.debug_logging import sanitize_for_log
from app.services.player import LIKE_PC from app.services.player import LIKE_PC
@@ -49,6 +49,7 @@ def register_routes(app, services, settings):
) )
return dict( return dict(
nav_pages=NAV_PAGES, nav_pages=NAV_PAGES,
nav_groups=NAV_GROUPS,
current_path=request.path if request else '/', current_path=request.path if request else '/',
fmt_role=fmt_role, fmt_role=fmt_role,
conn_ok=conn_ok, conn_ok=conn_ok,
@@ -535,6 +536,12 @@ def register_routes(app, services, settings):
def admin_experimental(): def admin_experimental():
return render_template('admin_experimental.html') return render_template('admin_experimental.html')
# Backup / Restore
@app.route('/backup')
@login_required
def backup_page():
return render_template('backup.html')
# Map - shows locations of players, vehicles, buildings # Map - shows locations of players, vehicles, buildings
@app.route('/map') @app.route('/map')
@login_required @login_required
+809
View File
@@ -0,0 +1,809 @@
"""Backup service - backup creation, restore orchestration, backup management"""
import base64
import json
import logging
import os
import shlex
import shutil
import subprocess
import tarfile
import threading
import time
from datetime import datetime, timedelta
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
logger = logging.getLogger(__name__)
class BackupError(Exception):
pass
class BackupService:
BACKUP_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
def __init__(self, ssh_service, k8s_service, rmq_service, settings):
self.ssh = ssh_service
self.k8s = k8s_service
self.rmq = rmq_service
self.settings = settings
self._restore_state = {}
os.makedirs(self.BACKUP_DIR, exist_ok=True)
def _backup_path(self, name):
return os.path.join(self.BACKUP_DIR, name)
def _timestamp(self):
return datetime.now().strftime('%d-%m-%Y_%H%M%S')
def _fmt_date(self, ts):
if not ts:
return 'unknown'
try:
dt = datetime.strptime(ts, '%d-%m-%Y_%H%M%S')
return dt.strftime('%d-%m-%Y %H:%M:%S')
except (ValueError, TypeError):
return ts
# ── Backup Creation ───────────────────────────────────────────────
def create_backup(self, password=''):
ts = self._timestamp()
backup_name = f'backup-{ts}'
work_dir = self._backup_path(backup_name)
os.makedirs(work_dir, exist_ok=True)
components = []
try:
# 1. Battleground backup via VM tool
logger.info('Backup: Running battlegroup backup on VM...')
stdout, stderr, rc = self.ssh.run(
'/home/dune/.dune/bin/battlegroup backup', timeout=300)
if rc != 0:
raise BackupError(f'battlegroup backup failed: {stderr}')
bg_path = None
for line in stdout.splitlines():
line = line.strip()
if line.endswith('.tar.gz') or 'backup' in line.lower():
bg_path = line
if not bg_path:
raise BackupError('Could not locate battlegroup backup file on VM')
bg_local = os.path.join(work_dir, 'battlegroup-backup.tar.gz')
logger.info(f'Backup: Downloading {bg_path}...')
self._download_file(bg_path, bg_local)
components.append({
'name': 'battlegroup-backup.tar.gz',
'source': 'VM battlegroup tool',
'size': os.path.getsize(bg_local),
})
# 2. K8s manifests
logger.info('Backup: Exporting K8s resources...')
k8s_dir = os.path.join(work_dir, 'k8s-manifests')
os.makedirs(k8s_dir, exist_ok=True)
ns = self.k8s.namespace
resources = [('battlegroup', 'battlegroup-crd.yaml'),
('deploy', 'deployments.yaml'),
('sts', 'statefulsets.yaml'),
('svc', 'services.yaml'),
('cm', 'configmaps.yaml'),
('secret', 'secrets.yaml')]
for res, fname in resources:
stdout, stderr, rc = self.ssh.run(
f'sudo kubectl get {res} -n {ns} -o yaml', timeout=60)
if rc == 0 and stdout.strip():
with open(os.path.join(k8s_dir, fname), 'w') as f:
f.write(stdout)
components.append({
'name': f'k8s-manifests/{fname}',
'source': f'kubectl get {res}',
'size': len(stdout),
})
# 3. RMQ definitions
logger.info('Backup: Exporting RMQ definitions...')
rmq_dir = os.path.join(work_dir, 'rmq')
os.makedirs(rmq_dir, exist_ok=True)
for label, fetch_fn in [('admin-overview', self.rmq.overview),
('game-overview', self.rmq.game_overview)]:
try:
data = fetch_fn()
if data:
with open(os.path.join(rmq_dir, f'{label}.json'), 'w') as f:
json.dump(data, f, indent=2)
components.append({
'name': f'rmq/{label}.json',
'source': f'RMQ {label}',
'size': len(json.dumps(data)),
})
except Exception as e:
logger.warning(f'Backup: Could not export RMQ {label}: {e}')
# 4. Dashboard database schema (bans, audit_log, chat_history, player_ips, player_actions, settings)
logger.info('Backup: Dumping dashboard schema...')
db_dump = None
ns = self.k8s.namespace
dbpod_cmd = (
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
f'sudo kubectl exec -n {ns} $dbpod -- pg_dump -U postgres -d dune '
f'--schema=dashboard --no-owner --no-acl 2>/dev/null'
)
stdout, stderr, rc = self.ssh.run(dbpod_cmd, timeout=120)
if rc == 0 and stdout.strip():
db_dump = os.path.join(work_dir, 'dashboard-db.sql')
with open(db_dump, 'w') as f:
f.write(stdout)
components.append({
'name': 'dashboard-db.sql',
'source': 'pg_dump dashboard schema',
'size': len(stdout),
})
logger.info(f'Backup: Dashboard schema dumped ({len(stdout)} bytes)')
else:
logger.warning(f'Backup: Could not dump dashboard schema: {stderr}')
# 5. Dashboard settings.yaml
settings_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'settings.yaml')
if os.path.exists(settings_path):
shutil.copy2(settings_path, os.path.join(work_dir, 'settings.yaml'))
components.append({
'name': 'settings.yaml',
'source': 'local',
'size': os.path.getsize(settings_path),
})
# 6. Write manifest
manifest = {
'name': backup_name,
'created': ts,
'dashboard_version': 'v0.5.0',
'components': components,
}
with open(os.path.join(work_dir, 'metadata.json'), 'w') as f:
json.dump(manifest, f, indent=2)
# 7. Package into tarball
archive_path = self._backup_path(f'{backup_name}.tar.gz')
with tarfile.open(archive_path, 'w:gz') as tar:
tar.add(work_dir, arcname=backup_name)
shutil.rmtree(work_dir)
# 8. Encrypt with password if provided
encrypted = False
if password:
logger.info('Backup: Encrypting with password...')
self._encrypt_file(archive_path, password)
encrypted = True
# Write sidecar metadata so list/preview work without password
meta_path = self._backup_path(f'{backup_name}.meta')
with open(meta_path, 'w') as f:
json.dump({'name': backup_name, 'created': ts, 'components': components}, f)
total_size = os.path.getsize(archive_path)
logger.info(f'Backup created: {archive_path} ({total_size} bytes)')
return {
'success': True,
'backup': backup_name,
'path': archive_path,
'size': total_size,
'components': components,
'encrypted': encrypted,
}
except Exception as e:
if os.path.exists(work_dir):
shutil.rmtree(work_dir)
logger.error(f'Backup failed: {e}')
return {'success': False, 'error': str(e)}
def _download_file(self, remote_path, local_path):
stdout, stderr, rc = self.ssh.run(
f'cat {shlex.quote(remote_path)} | base64', timeout=120)
if rc != 0:
raise BackupError(f'Failed to read remote file: {stderr}')
raw = base64.b64decode(stdout)
with open(local_path, 'wb') as f:
f.write(raw)
def _encrypt_file(self, filepath, password):
salt = os.urandom(16)
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=600000)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
f = Fernet(key)
with open(filepath, 'rb') as fh:
data = fh.read()
encrypted = salt + f.encrypt(data)
with open(filepath, 'wb') as fh:
fh.write(encrypted)
def _decrypt_file(self, filepath, password):
with open(filepath, 'rb') as fh:
data = fh.read()
salt = data[:16]
ciphertext = data[16:]
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=600000)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
f = Fernet(key)
return f.decrypt(ciphertext)
def _backup_is_encrypted(self, name):
path = self._backup_path(f'{name}.tar.gz')
if not os.path.exists(path):
return False
try:
with tarfile.open(path, 'r:gz') as tar:
tar.getmembers()
return False
except Exception:
return True
def _schedule_path(self):
return os.path.join(self.BACKUP_DIR, 'schedule.json')
def load_schedule(self):
path = self._schedule_path()
if not os.path.exists(path):
return {'enabled': False, 'mode': 'interval', 'interval_minutes': 1440,
'schedule_days': [], 'schedule_times': ['05:00'],
'keep': 5, 'password': '', 'next_run': ''}
try:
with open(path) as f:
return json.load(f)
except Exception:
return {'enabled': False, 'mode': 'interval', 'interval_minutes': 1440,
'schedule_days': [], 'schedule_times': ['05:00'],
'keep': 5, 'password': '', 'next_run': ''}
def save_schedule(self, cfg):
with open(self._schedule_path(), 'w') as f:
json.dump(cfg, f, indent=2)
def get_schedule(self):
return self.load_schedule()
def _next_run_from_schedule(self, cfg):
now = datetime.now()
days_set = set(cfg.get('schedule_days', []))
times = cfg.get('schedule_times', [])
if not days_set or not times:
return ''
best = None
for offset in range(8):
base = datetime(now.year, now.month, now.day) + timedelta(days=offset)
wd = base.weekday()
if wd not in days_set:
continue
for t in times:
try:
h, m = (int(x) for x in t.split(':'))
except Exception:
continue
candidate = base.replace(hour=h, minute=m, second=0, microsecond=0)
if candidate <= now:
continue
if best is None or candidate < best:
best = candidate
return best.isoformat() if best else ''
def _next_run_from_interval(self, cfg):
return datetime.fromtimestamp(time.time() + cfg['interval_minutes'] * 60).isoformat()
def update_schedule(self, data):
cfg = self.load_schedule()
cfg['enabled'] = bool(data.get('enabled', cfg['enabled']))
if 'mode' in data:
cfg['mode'] = data['mode']
if 'interval_minutes' in data:
cfg['interval_minutes'] = int(data['interval_minutes'])
if 'schedule_days' in data:
cfg['schedule_days'] = data['schedule_days']
if 'schedule_times' in data:
cfg['schedule_times'] = data['schedule_times']
cfg['keep'] = int(data.get('keep', cfg['keep']))
if 'password' in data:
cfg['password'] = data['password']
if cfg.get('mode') == 'schedule':
cfg['next_run'] = self._next_run_from_schedule(cfg)
else:
cfg['next_run'] = self._next_run_from_interval(cfg)
self.save_schedule(cfg)
return cfg
def run_scheduled_backup(self):
cfg = self.load_schedule()
if not cfg.get('enabled'):
return {'success': False, 'error': 'Scheduled backups are disabled'}
pw = cfg.get('password', '') or None
result = self.create_backup(password=pw or '')
if result.get('success'):
keep = cfg.get('keep', 5)
if keep > 0:
self._enforce_retention(keep)
if cfg.get('mode') == 'schedule':
cfg['next_run'] = self._next_run_from_schedule(cfg)
else:
cfg['next_run'] = self._next_run_from_interval(cfg)
self.save_schedule(cfg)
return result
def _enforce_retention(self, keep):
backups = []
for fname in sorted(os.listdir(self.BACKUP_DIR), reverse=True):
if fname.endswith('.tar.gz'):
backups.append(fname.replace('.tar.gz', ''))
backups.sort(reverse=True)
for old in backups[keep:]:
self.delete_backup(old)
# ── Backup Listing ────────────────────────────────────────────────
def list_backups(self):
backups = []
if not os.path.isdir(self.BACKUP_DIR):
return backups
for fname in sorted(os.listdir(self.BACKUP_DIR), reverse=True):
if fname.endswith('.tar.gz'):
fpath = os.path.join(self.BACKUP_DIR, fname)
info = self.get_backup_info(fpath)
name = fname.replace('.tar.gz', '')
backups.append({
'name': name,
'path': fpath,
'size': os.path.getsize(fpath),
'created': self._fmt_date(info.get('created', '')),
'components': info.get('components', []),
'password_protected': self._backup_is_encrypted(name),
})
return backups
def get_backup_info(self, path):
if path.endswith('.tar.gz'):
meta_path = path.replace('.tar.gz', '.meta')
if os.path.exists(meta_path):
try:
with open(meta_path) as f:
return json.load(f)
except Exception as e:
logger.warning(f'Could not read sidecar meta from {meta_path}: {e}')
try:
with tarfile.open(path, 'r:gz') as tar:
for m in tar.getmembers():
if m.name.endswith('metadata.json'):
with tar.extractfile(m) as f:
return json.loads(f.read().decode('utf-8'))
except Exception as e:
logger.warning(f'Could not read metadata from {path}: {e}')
return {}
def delete_backup(self, name):
path = self._backup_path(f'{name}.tar.gz')
if os.path.exists(path):
os.remove(path)
meta_path = self._backup_path(f'{name}.meta')
if os.path.exists(meta_path):
os.remove(meta_path)
return True
def verify_backup(self, name, password=''):
path = self._backup_path(f'{name}.tar.gz')
if not os.path.exists(path):
return {'success': False, 'error': 'Backup not found'}
is_encrypted = self._backup_is_encrypted(name)
meta = self.get_backup_info(path)
if is_encrypted and not password:
return {
'success': True,
'valid': True,
'encrypted': True,
'files': 0,
'size': os.path.getsize(path),
'components': meta.get('components', []),
'note': 'Enter password to verify contents',
}
try:
if is_encrypted:
decrypted = self._decrypt_file(path, password)
import tempfile
tmp = tempfile.NamedTemporaryFile(suffix='.tar.gz', delete=False)
tmp.write(decrypted)
tmp_path = tmp.name
tmp.close()
try:
with tarfile.open(tmp_path, 'r:gz') as tar:
members = tar.getmembers()
finally:
os.unlink(tmp_path)
else:
with tarfile.open(path, 'r:gz') as tar:
members = tar.getmembers()
return {
'success': True,
'valid': True,
'encrypted': is_encrypted,
'files': len(members),
'size': os.path.getsize(path),
'components': meta.get('components', []),
}
except Exception as e:
return {'success': False, 'valid': False, 'error': str(e)}
# ── Restore Orchestration ─────────────────────────────────────────
def restore_preview(self, name):
path = self._backup_path(f'{name}.tar.gz')
if not os.path.exists(path):
return {'success': False, 'error': 'Backup not found'}
info = self.get_backup_info(path)
comps = info.get('components', [])
return {
'success': True,
'backup': name,
'created': self._fmt_date(info.get('created', '')),
'components': comps,
'has_db': any('battlegroup-backup' in c.get('name', '') for c in comps),
'has_dash_db': any('dashboard-db.sql' in c.get('name', '') for c in comps),
'has_k8s': any('k8s-manifests' in c.get('name', '') for c in comps),
'has_settings': any('settings.yaml' in c.get('name', '') for c in comps),
'has_rmq': any(c.get('name', '').startswith('rmq/') for c in comps),
'password_protected': self._backup_is_encrypted(name),
}
def test_connection(self):
ssh_user = self.settings.get('server', {}).get('user', 'dune')
ssh_key = self.settings.get('server', {}).get('ssh_key', '')
vm_ip = self.settings.get('server', {}).get('host', '')
if not ssh_key:
return {'success': False, 'error': 'No SSH key configured in dashboard settings'}
if not vm_ip:
return {'success': False, 'error': 'No server host configured in dashboard settings'}
try:
result = subprocess.run(
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=10',
'-o', 'LogLevel=QUIET', '-i', ssh_key,
f'{ssh_user}@{vm_ip}',
'hostname && sudo kubectl get nodes --no-headers 2>/dev/null | head -1'],
capture_output=True, text=True, timeout=30)
if result.returncode != 0:
return {'success': False, 'error': result.stderr.strip() or 'Connection failed'}
lines = [l for l in result.stdout.splitlines() if l.strip()]
return {
'success': True,
'hostname': lines[0] if lines else 'unknown',
'k8s_ok': len(lines) > 1,
}
except subprocess.TimeoutExpired:
return {'success': False, 'error': 'Connection timed out'}
except FileNotFoundError:
return {'success': False, 'error': 'SSH client not found on dashboard machine'}
except Exception as e:
return {'success': False, 'error': str(e)}
def start_restore(self, backup_name, options):
ssh_user = self.settings.get('server', {}).get('user', 'dune')
ssh_key = self.settings.get('server', {}).get('ssh_key', '')
vm_ip = self.settings.get('server', {}).get('host', '')
if not ssh_key:
return {'success': False, 'error': 'No SSH key configured in dashboard settings'}
if not vm_ip:
return {'success': False, 'error': 'No server host configured in dashboard settings'}
state_key = backup_name
self._restore_state[state_key] = {
'status': 'preparing',
'progress': 0,
'steps': [],
'current_step': 0,
'backup_name': backup_name,
'vm_ip': vm_ip,
'ssh_user': ssh_user,
'ssh_key_path': ssh_key,
'options': options,
'errors': [],
'completed_steps': [],
'started': time.time(),
}
t = threading.Thread(target=self._run_restore, args=(state_key,), daemon=True)
t.start()
return {'success': True, 'restore_id': state_key}
def get_restore_status(self, restore_id):
state = self._restore_state.get(restore_id)
if not state:
return {'success': False, 'error': 'Restore not found'}
return {
'success': True,
'status': state['status'],
'progress': state['progress'],
'steps': state['steps'],
'current_step': state['current_step'],
'completed_steps': state['completed_steps'],
'errors': state['errors'],
}
def _run_restore(self, state_key):
state = self._restore_state[state_key]
opts = state['options']
vm_ip = state['vm_ip']
ssh_user = state['ssh_user']
ssh_key = state['ssh_key_path']
backup_name = state['backup_name']
ns = self.k8s.namespace
def ssh_cmd(cmd, timeout=120):
return subprocess.run(
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'LogLevel=QUIET',
'-i', ssh_key, f'{ssh_user}@{vm_ip}', cmd],
capture_output=True, text=True, timeout=timeout)
def add_step(label):
state['steps'].append(label)
def complete_step(label, success, detail=''):
state['completed_steps'].append({
'label': label, 'success': success, 'detail': detail,
})
if not success:
state['errors'].append(detail or f'{label} failed')
state['current_step'] += 1
total = max(len(state['steps']), 1)
state['progress'] = min(int(state['current_step'] / total * 100), 99)
archive_path = self._backup_path(f'{backup_name}.tar.gz')
pw = opts.get('password', '')
# Step 0: Decrypt backup if password provided
if self._backup_is_encrypted(backup_name):
add_step('Decrypting backup archive')
try:
if not pw:
raise BackupError('Backup is encrypted but no password provided')
decrypted = self._decrypt_file(archive_path, pw)
import tempfile
tmp = tempfile.NamedTemporaryFile(suffix='.tar.gz', delete=False)
tmp.write(decrypted)
upload_path = tmp.name
tmp.close()
complete_step('Decrypting backup archive', True)
except Exception as e:
complete_step('Decrypting backup archive', False, str(e))
state['status'] = 'failed'
return
else:
upload_path = archive_path
# Step 1: Upload backup archive to new VM
add_step('Uploading backup archive to new VM')
try:
with open(upload_path, 'rb') as f:
b64_data = base64.b64encode(f.read()).decode()
r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > /tmp/restore-{backup_name}.tar.gz', timeout=300)
if r.returncode != 0:
raise BackupError(f'Upload failed: {r.stderr}')
complete_step('Uploading backup archive to new VM', True)
except Exception as e:
complete_step('Uploading backup archive to new VM', False, str(e))
state['status'] = 'failed'
return
finally:
if upload_path != archive_path:
try:
os.unlink(upload_path)
except Exception:
pass
# Step 2: Extract archive on VM
add_step('Extracting backup archive on VM')
try:
r = ssh_cmd(
f'mkdir -p /tmp/restore-{backup_name} && '
f'cd /tmp/restore-{backup_name} && '
f'tar xzf /tmp/restore-{backup_name}.tar.gz --strip-components=1',
timeout=60)
if r.returncode != 0:
raise BackupError(f'Extract failed: {r.stderr}')
complete_step('Extracting backup archive on VM', True)
except Exception as e:
complete_step('Extracting backup archive on VM', False, str(e))
# Step 3: Restore K8s secrets and configmaps
if opts.get('restore_k8s', True):
add_step('Restoring K8s secrets and configmaps')
try:
d = f'/tmp/restore-{backup_name}'
for fname in ['secrets.yaml', 'configmaps.yaml']:
r = ssh_cmd(
f'sudo kubectl apply -n {ns} -f {d}/k8s-manifests/{fname} 2>/dev/null || true',
timeout=30)
if r.returncode != 0:
logger.warning(f'Could not apply {fname}: {r.stderr}')
complete_step('Restoring K8s secrets and configmaps', True)
except Exception as e:
complete_step('Restoring K8s secrets and configmaps', False, str(e))
# Step 4: Restore battlegroup CRD and wait for pods
if opts.get('restore_battlegroup', True):
add_step('Applying battlegroup CRD')
try:
d = f'/tmp/restore-{backup_name}'
r = ssh_cmd(
f'sudo kubectl apply -f {d}/k8s-manifests/battlegroup-crd.yaml', timeout=60)
if r.returncode != 0:
raise BackupError(r.stderr)
complete_step('Applying battlegroup CRD', True)
except Exception as e:
complete_step('Applying battlegroup CRD', False, str(e))
add_step('Waiting for pods to provision (up to 5 min)')
try:
for i in range(30):
r = ssh_cmd(
f'sudo kubectl get pods -n {ns} --no-headers 2>/dev/null | '
f'grep -c -E "(dbdepl|mq-.*-sts)" || true', timeout=15)
if r.returncode == 0 and r.stdout.strip():
count = int(r.stdout.strip())
if count >= 2:
complete_step('Waiting for pods to provision', True)
break
time.sleep(10)
else:
complete_step('Waiting for pods to provision', False, 'Timed out')
except Exception as e:
complete_step('Waiting for pods to provision', False, str(e))
add_step('Waiting for DB pod to be Running')
try:
for i in range(30):
r = ssh_cmd(
f'sudo kubectl get pods -n {ns} -l role=db --no-headers '
f'-o custom-columns=STATUS:.status.phase 2>/dev/null | head -1',
timeout=15)
if 'Running' in r.stdout:
complete_step('Waiting for DB pod to be Running', True)
break
time.sleep(10)
else:
complete_step('Waiting for DB pod to be Running', False, 'DB pod did not start')
except Exception as e:
complete_step('Waiting for DB pod to be Running', False, str(e))
# Step 5: Import game database
if opts.get('restore_db', True):
add_step('Importing game database')
try:
r = ssh_cmd(
f'cd /tmp/restore-{backup_name} && '
f'/home/dune/.dune/bin/battlegroup import',
timeout=600)
if r.returncode != 0:
raise BackupError(r.stderr)
complete_step('Importing game database', True)
except Exception as e:
complete_step('Importing game database', False, str(e))
# Step 6: Restore dashboard database schema
if opts.get('restore_dash_db', True):
add_step('Restoring dashboard schema (bans, chat, audit, settings)')
try:
dash_sql_path = self._backup_path(f'{backup_name}.tar.gz')
dash_sql_content = None
with tarfile.open(dash_sql_path, 'r:gz') as tar:
for m in tar.getmembers():
if m.name.endswith('dashboard-db.sql'):
with tar.extractfile(m) as f:
dash_sql_content = f.read()
break
if dash_sql_content:
b64_sql = base64.b64encode(dash_sql_content).decode()
r = ssh_cmd(
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
f'echo {shlex.quote(b64_sql)} | base64 -d | '
f'sudo kubectl exec -n {ns} -i $dbpod -- psql -U postgres -d dune',
timeout=120)
if r.returncode != 0:
logger.warning(f'Dashboard DB restore warning: {r.stderr}')
complete_step('Restoring dashboard schema (bans, chat, audit, settings)', True)
else:
complete_step('Restoring dashboard schema (bans, chat, audit, settings)', True)
except Exception as e:
complete_step('Restoring dashboard schema (bans, chat, audit, settings)', False, str(e))
if opts.get('restore_db', True) or opts.get('restore_dash_db', True):
add_step('Re-applying dashboard schema ownership')
try:
sql = ("ALTER SCHEMA dashboard OWNER TO dune;"
"GRANT ALL PRIVILEGES ON SCHEMA dashboard TO dune;"
"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA dashboard TO dune;"
"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA dashboard TO dune;")
r = ssh_cmd(
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
f'sudo kubectl exec -n {ns} $dbpod -- psql -U postgres -d dune '
f'-c {shlex.quote(sql)}', timeout=30)
if r.returncode != 0:
logger.warning(f'Dashboard schema ownership warning: {r.stderr}')
complete_step('Re-applying dashboard schema ownership', True)
except Exception as e:
complete_step('Re-applying dashboard schema ownership', False, str(e))
# Step 7: Apply ping fix if new IP provided
if opts.get('restore_ping_fix', True) and opts.get('new_ip'):
add_step('Applying HOST_DATACENTER ping fix')
try:
r = ssh_cmd('hostname', timeout=10)
hostname = r.stdout.strip()
new_ip = opts['new_ip']
for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']:
full_name = f'{ns}-{deploy_suffix}'
ssh_cmd(
f'sudo kubectl set env deploy/{full_name} -n {ns} '
f'HOST_DATACENTER_ID={hostname} '
f'HOST_DATACENTER_IP_ADDRESS={new_ip}',
timeout=30)
complete_step('Applying HOST_DATACENTER ping fix', True)
except Exception as e:
complete_step('Applying HOST_DATACENTER ping fix', False, str(e))
# Step 8: Re-create RMQ dashboard_admin user
if opts.get('restore_rmq', True):
add_step('Re-creating RMQ dashboard_admin user on both instances')
try:
pw = self.settings.get('rabbitmq', {}).get('password', '')
for side in ['admin', 'game']:
pod_r = ssh_cmd(
f'sudo kubectl get pods -n {ns} -o name | grep mq-{side}-sts | head -1',
timeout=15)
if pod_r.returncode != 0 or not pod_r.stdout.strip():
logger.warning(f'No mq-{side} pod found')
continue
pod = pod_r.stdout.strip()
for cmd in [
f'rabbitmqctl add_user dashboard_admin {pw}',
f'rabbitmqctl set_user_tags dashboard_admin administrator',
f'rabbitmqctl set_permissions -p / dashboard_admin ".*" ".*" ".*"',
f'rabbitmqctl eval '
f'\'application:set_env(rabbit, auth_backends, '
f'[rabbit_auth_backend_cache, rabbit_auth_backend_internal]).\'',
]:
ssh_cmd(f'sudo kubectl exec -n {ns} {pod} -- {cmd}', timeout=15)
complete_step('Re-creating RMQ dashboard_admin user on both instances', True)
except Exception as e:
complete_step('Re-creating RMQ dashboard_admin user on both instances', False, str(e))
# Step 9: Restore settings.yaml locally
if opts.get('restore_settings', True):
add_step('Restoring dashboard settings.yaml locally')
try:
d = f'/tmp/restore-{backup_name}'
r = ssh_cmd(f'cat {d}/settings.yaml', timeout=15)
if r.returncode == 0 and r.stdout.strip():
local_settings = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
'settings.yaml')
with open(local_settings, 'w') as f:
f.write(r.stdout)
complete_step('Restoring dashboard settings.yaml locally', True)
else:
complete_step('Restoring dashboard settings.yaml locally', True)
except Exception as e:
complete_step('Restoring dashboard settings.yaml locally', False, str(e))
# Step 10: Cleanup
add_step('Cleaning up temporary files on VM')
try:
ssh_cmd(f'rm -rf /tmp/restore-{backup_name} /tmp/restore-{backup_name}.tar.gz',
timeout=15)
complete_step('Cleaning up temporary files on VM', True)
except Exception as e:
complete_step('Cleaning up temporary files on VM', False, str(e))
state['status'] = 'completed' if not state['errors'] else 'completed_with_errors'
state['progress'] = 100
state['completed_at'] = time.time()
+66 -3
View File
@@ -2,6 +2,7 @@
import json import json
import logging import logging
import urllib.error
import urllib.request import urllib.request
import configparser import configparser
import io import io
@@ -10,6 +11,9 @@ from typing import Any, Dict, Optional
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Internal port the BGD container listens on (used with service cluster IP)
_BGD_CONTAINER_PORT = 11717
class DirectorService: class DirectorService:
"""Service for interacting with the game server's battlegroup director. """Service for interacting with the game server's battlegroup director.
@@ -27,6 +31,7 @@ class DirectorService:
self.k8s = k8s_service self.k8s = k8s_service
self.ssh = ssh_service self.ssh = ssh_service
self.namespace = namespace self.namespace = namespace
self._bgd_svc_url = None # cached cluster URL for SSH fallback
resource_prefix = namespace resource_prefix = namespace
for prefix in ['funcom-seabass-']: for prefix in ['funcom-seabass-']:
if resource_prefix.startswith(prefix): if resource_prefix.startswith(prefix):
@@ -35,9 +40,31 @@ class DirectorService:
self.resource_prefix = resource_prefix self.resource_prefix = resource_prefix
self.cm_name = f"{resource_prefix}-bgd-conf-cm" self.cm_name = f"{resource_prefix}-bgd-conf-cm"
def _resolve_bgd_svc_url(self):
"""Find the BGD Service cluster IP via kubectl (stable across pod restarts)."""
out, err, rc = self.k8s.run('get svc -o name', timeout=10)
if rc != 0:
return None
for line in (out or '').split('\n'):
line = line.strip()
if 'bgd-svc' in line:
svc_name = line.split('/')[-1]
ip_out, ip_err, ip_rc = self.k8s.run(
f'get svc {svc_name} -o jsonpath={{.spec.clusterIP}}', timeout=10)
if ip_rc == 0 and ip_out:
ip = ip_out.strip()
logger.info("Director: resolved BGD svc cluster IP %s", ip)
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
return None
def _request(self, path: str, method: str = 'GET', data: Any = None, def _request(self, path: str, method: str = 'GET', data: Any = None,
timeout: int = 15, raw_data: bool = False) -> str: timeout: int = 15, raw_data: bool = False) -> str:
"""Execute HTTP request to director service via NodePort. """Execute HTTP request to director service.
Tries local HTTP first (SSH tunnel + kubectl port-forward).
Falls back to SSH + wget directly to the BGD service cluster IP,
which survives server restarts without needing a port-forward.
Args: Args:
path: URL path (e.g., '/v0/battlegroup'). path: URL path (e.g., '/v0/battlegroup').
@@ -67,8 +94,44 @@ class DirectorService:
method=method method=method
) )
with urllib.request.urlopen(req, timeout=timeout) as resp: # Try local HTTP first (SSH tunnel + kubectl port-forward on VM)
return resp.read().decode() try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode()
except (urllib.error.URLError, ConnectionError, OSError) as e:
logger.debug("Director local HTTP failed, trying SSH fallback: %s", e)
# Fallback: SSH to BGD service cluster IP (always works, no tunnel needed)
if not self._bgd_svc_url:
self._bgd_svc_url = self._resolve_bgd_svc_url()
if self._bgd_svc_url:
svc_url = f"{self._bgd_svc_url}{path}"
logger.debug("Director SSH fallback: %s %s", method, svc_url)
if method == 'GET':
out, err, rc = self.ssh.run(f'wget -qO- {svc_url}', timeout=timeout)
else:
body_bytes = None
if raw_data and isinstance(data, str):
body_bytes = data.encode()
elif data is not None:
body_bytes = json.dumps(data).encode()
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
self.ssh.run(f'echo {body_b64} | base64 -d > {tmp}', timeout=5)
try:
out, err, rc = self.ssh.run(
f'wget -qO- --post-file={tmp} '
f'--header="Content-Type: application/json" {svc_url}',
timeout=timeout)
finally:
self.ssh.run(f'rm -f {tmp}', timeout=5)
if rc == 0 and out:
return out
logger.warning("Director SSH fallback failed (rc=%d): %s",
rc, err[:100] if err else 'none')
self._bgd_svc_url = None # stale cache, re-resolve next time
raise ConnectionError("Connection refused: Director unreachable via local HTTP or SSH fallback")
# ── Director API methods ────────────────────────────────────────── # ── Director API methods ──────────────────────────────────────────
+27 -3
View File
@@ -60,6 +60,23 @@ class K8sService:
return [] return []
return [d.strip() for d in (out or '').strip().split('\n') if d.strip()] return [d.strip() for d in (out or '').strip().split('\n') if d.strip()]
def _parse_memory_gib(self, raw):
raw = raw.strip().upper()
if raw.endswith('KI'):
return round(int(raw[:-2]) / (1024 ** 3), 1)
if raw.endswith('MI'):
return round(int(raw[:-2]) / 1024, 1)
if raw.endswith('GI'):
return round(int(raw[:-2]), 1)
if raw.endswith('TI'):
return round(int(raw[:-2]) * 1024, 1)
if raw.endswith('PI'):
return round(int(raw[:-2]) * 1024 ** 2, 1)
try:
return round(int(raw) / (1024 ** 3), 1)
except ValueError:
return 0.0
def get_node_metrics(self): def get_node_metrics(self):
out, err, rc = self.run('top nodes') out, err, rc = self.run('top nodes')
if rc == 0 and out.strip(): if rc == 0 and out.strip():
@@ -67,10 +84,17 @@ class K8sService:
if len(lines) >= 2: if len(lines) >= 2:
parts = lines[1].split() parts = lines[1].split()
if len(parts) >= 4: if len(parts) >= 4:
cpu_pct_str = parts[2]
mem_str = parts[3]
mem_pct_str = parts[4] if len(parts) >= 5 else ''
return { return {
'cpu': parts[2], 'cpu': cpu_pct_str,
'memory': parts[3], 'memory': mem_str,
'cpu_pct': parts[1] 'cpu_pct': parts[1],
'cpu_num': float(cpu_pct_str.rstrip('%')),
'memory_gib': self._parse_memory_gib(mem_str),
'memory_pct': mem_pct_str,
'memory_pct_num': float(mem_pct_str.rstrip('%')) if mem_pct_str else 0.0,
} }
return {} return {}
+10
View File
@@ -7,6 +7,8 @@ import paramiko
from app.utils.ssh_key import resolve_ssh_key from app.utils.ssh_key import resolve_ssh_key
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
KEEPALIVE_INTERVAL = 15
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -37,6 +39,11 @@ class SSHService:
transport = self._client.get_transport() transport = self._client.get_transport()
if transport and transport.is_active(): if transport and transport.is_active():
return self._client return self._client
logger.debug("SSH: closing stale client before reconnect")
try:
self._client.close()
except Exception:
pass
self._client = None self._client = None
client = paramiko.SSHClient() client = paramiko.SSHClient()
@@ -56,6 +63,9 @@ class SSHService:
try: try:
client.connect(**connect_kwargs) client.connect(**connect_kwargs)
logger.debug("SSH connection established to %s@%s", self.user, self.host) logger.debug("SSH connection established to %s@%s", self.user, self.host)
transport = client.get_transport()
if transport:
transport.set_keepalive(KEEPALIVE_INTERVAL)
except paramiko.AuthenticationException: except paramiko.AuthenticationException:
logger.error("SSH authentication failed for %s@%s", self.user, self.host) logger.error("SSH authentication failed for %s@%s", self.user, self.host)
raise raise
+26
View File
@@ -82,4 +82,30 @@ NAV_PAGES = [
('/buildings', 'Buildings'), ('/buildings', 'Buildings'),
('/map', 'Map'), ('/map', 'Map'),
('/admin-experimental', 'Experimental'), ('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]
NAV_GROUPS = [
('/', 'Overview'),
('Server', [
('/server', 'Server'),
('/director', 'Director'),
('/shell', 'Shell'),
('/files', 'Files'),
]),
('Players', [
('/players', 'Players'),
('/vehicles', 'Vehicles'),
('/guilds', 'Guilds'),
('/buildings', 'Buildings'),
]),
('World', [
('/events', 'Events'),
('/chat', 'Chat'),
('/map', 'Map'),
]),
('System', [
('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]),
] ]
+6
View File
@@ -67,6 +67,12 @@ if __name__ == '__main__':
print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.") print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.")
print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n") print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n")
import signal
def _shutdown(sig, frame):
logging.getLogger(__name__).info("Shutdown signal received, exiting...")
os._exit(0)
signal.signal(signal.SIGINT, _shutdown)
# Start optional HTTP -> HTTPS redirect server when SSL is enabled. # Start optional HTTP -> HTTPS redirect server when SSL is enabled.
# This is convenience only; the dashboard works without port 80 if users visit https://host:port. # This is convenience only; the dashboard works without port 80 if users visit https://host:port.
if ssl_context and settings['dashboard'].get('http_redirect', False): if ssl_context and settings['dashboard'].get('http_redirect', False):
+197
View File
@@ -71,6 +71,50 @@ nav a.active {
nav .spacer { flex: 1; } nav .spacer { flex: 1; }
/* Horizontal vs vertical nav link visibility */
.nav-links-h { display: flex; align-items: center; gap: 2px; }
.nav-links-v { display: none; }
body[data-nav-layout="vertical"] .nav-links-h { display: none; }
body[data-nav-layout="vertical"] .nav-links-v { display: flex; flex-direction: column; width: 100%; flex: 1; overflow-y: auto; }
/* Horizontal nav dropdowns */
.nav-dropdown {
position: relative;
display: inline-block;
}
.nav-dropdown-toggle {
cursor: default;
padding: 0 10px;
}
.nav-dropdown-content {
display: none;
position: absolute;
top: 100%;
left: 0;
background: var(--nav-bg);
min-width: 140px;
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
border-radius: 6px;
z-index: 1000;
padding: 4px 0;
border: 1px solid rgba(255,255,255,0.1);
}
.nav-dropdown-content a {
color: var(--nav-text);
padding: 8px 16px;
height: auto;
border-bottom: none;
font-size: 12px;
display: block;
}
.nav-dropdown-content a:hover { color: #fff; background: rgba(255,255,255,0.06); }
.nav-dropdown-content a.active {
color: var(--nav-active);
border-left: 3px solid var(--nav-active);
}
.nav-dropdown:hover .nav-dropdown-content { display: block; }
.conn-dot { .conn-dot {
width: 8px; width: 8px;
height: 8px; height: 8px;
@@ -939,6 +983,32 @@ td a:hover { text-decoration: underline; }
border-radius: 3px; border-radius: 3px;
} }
/* Resource charts */
.chart-panel .chart-hint {
font-size: 11px;
color: var(--text-muted);
font-weight: 400;
}
.chart-panel-body {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.chart-box {
position: relative;
height: 140px;
}
.chart-box canvas {
width: 100% !important;
height: 100% !important;
}
@media (max-width: 600px) {
.chart-panel-body {
grid-template-columns: 1fr;
}
.chart-box { height: 120px; }
}
/* Empty state */ /* Empty state */
.empty { .empty {
text-align: center; text-align: center;
@@ -1144,3 +1214,130 @@ td a:hover { text-decoration: underline; }
font-family: monospace; font-family: monospace;
white-space: nowrap; white-space: nowrap;
} }
/* Nav Layout Toggle */
.nav-toggle {
position: fixed;
top: 56px;
left: 6px;
z-index: 101;
background: var(--nav-bg);
color: var(--nav-text);
border: 1px solid rgba(255,255,255,0.15);
border-radius: 4px;
padding: 3px 7px;
font-size: 15px;
cursor: pointer;
line-height: 1;
opacity: 0.5;
transition: opacity 0.15s;
}
.nav-toggle:hover { opacity: 1; color: #fff; }
/* Vertical sidebar layout */
body[data-nav-layout="vertical"] {
padding-left: 216px;
}
body[data-nav-layout="vertical"] .nav-toggle {
left: 204px;
top: 6px;
}
body[data-nav-layout="vertical"] nav {
position: fixed;
left: 0;
top: 0;
bottom: 0;
width: 200px;
flex-direction: column;
height: 100vh;
padding: 0;
align-items: stretch;
box-shadow: 1px 0 4px rgba(0,0,0,0.2);
}
body[data-nav-layout="vertical"] nav .brand {
padding: 20px 16px 12px;
margin-right: 0;
font-size: 13px;
text-align: center;
border-bottom: 1px solid rgba(255,255,255,0.08);
}
body[data-nav-layout="vertical"] nav a {
padding: 10px 16px;
height: auto;
border-bottom: none;
border-left: 3px solid transparent;
font-size: 12px;
}
body[data-nav-layout="vertical"] nav a:hover {
background: rgba(255,255,255,0.05);
}
body[data-nav-layout="vertical"] nav a.active {
border-bottom-color: transparent;
border-left-color: var(--nav-active);
}
body[data-nav-layout="vertical"] nav .spacer {
display: none;
}
body[data-nav-layout="vertical"] nav .theme-dropdown {
padding: 8px 16px;
border-top: 1px solid rgba(255,255,255,0.08);
}
body[data-nav-layout="vertical"] nav .theme-dropdown .theme-dropdown-content {
bottom: 100%;
top: auto;
left: 0;
right: auto;
margin-bottom: 4px;
}
body[data-nav-layout="vertical"] nav .theme-dropdown .theme-btn {
width: 100%;
justify-content: center;
}
body[data-nav-layout="vertical"] nav .nav-conn,
body[data-nav-layout="vertical"] nav .nav-logout {
padding: 10px 16px;
justify-content: center;
border-top: 1px solid rgba(255,255,255,0.08);
}
body[data-nav-layout="vertical"] .container {
max-width: none;
padding: 24px;
}
body[data-nav-layout="vertical"] .site-footer {
margin-left: 216px;
}
@media (max-width: 768px) {
body[data-nav-layout="vertical"] {
padding-left: 0;
}
body[data-nav-layout="vertical"] .nav-toggle {
top: 8px;
left: 8px;
}
body[data-nav-layout="vertical"] nav {
display: none;
}
body[data-nav-layout="vertical"] nav.nav-open {
display: flex;
}
body[data-nav-layout="vertical"] .container {
padding: 24px;
}
body[data-nav-layout="vertical"] .site-footer {
margin-left: 0;
}
}
+2 -2
View File
@@ -367,7 +367,7 @@
display: none; display: none;
position: absolute; position: absolute;
right: 0; right: 0;
background: #252530; background: var(--nav-bg);
min-width: 290px; min-width: 290px;
max-height: 80vh; max-height: 80vh;
overflow-y: auto; overflow-y: auto;
@@ -375,7 +375,7 @@
border-radius: 8px; border-radius: 8px;
z-index: 1000; z-index: 1000;
padding: 12px; padding: 12px;
border: 1px solid #404050; border: 1px solid rgba(255,255,255,0.1);
} }
.theme-grid { .theme-grid {
+722
View File
@@ -0,0 +1,722 @@
{% extends "base.html" %}
{% block title %}Backup - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Backup &amp; Restore</h1>
<p>Create full server backups and restore to a new VM</p>
</div>
<div id="backup-status" class="error-banner" style="display:none;"></div>
<div style="background:rgba(220,38,38,0.12);border:2px solid rgba(220,38,38,0.6);border-left:6px solid #dc2626;border-radius:8px;padding:16px 20px;margin-bottom:20px;">
<div style="font-size:14px;font-weight:700;color:#ef4444;margin-bottom:8px;">&#9888; SECURITY WARNING</div>
<div style="font-size:13px;color:var(--text);line-height:1.6;">
Backups contain <strong>sensitive information</strong> including database contents, K8s secrets, and server configuration.
Store backup files in a <strong>secure, offline location</strong>. Use a password to encrypt backups containing private data.
Do not share backup files or expose them in insecure storage.
<strong style="color:#ef4444;display:block;margin-top:8px;">&#9888; If you set a password, never forget it — lost passwords cannot be recovered and the backup will be permanently unrecoverable.</strong>
</div>
</div>
<div class="card" style="margin-bottom:20px;">
<div class="card-header">
<span>Backups</span>
<button onclick="createBackup()" id="create-btn" style="padding:6px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Create Backup</button>
</div>
<div class="card-body">
<p style="color:var(--text-muted);font-size:13px;margin-bottom:12px;">
Creates a full snapshot: game database, K8s resources, RMQ definitions, and dashboard settings.
Backups are stored locally in <code>./backups/</code>.
</p>
<div id="backup-list">
<p style="color:var(--text-muted);font-size:13px;">Loading backups...</p>
</div>
</div>
</div>
<div class="card" style="margin-bottom:20px;">
<div class="card-header">
<span>Scheduled Backups</span>
<button onclick="runScheduledNow()" id="run-sched-btn" style="padding:6px 16px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:13px;">Run Now</button>
<button onclick="saveSchedule()" id="save-sched-btn" style="padding:6px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Save</button>
</div>
<div class="card-body">
<p style="color:var(--text-muted);font-size:13px;margin-bottom:12px;">
Automatically create backups on a schedule. Old backups beyond the keep limit are deleted.
</p>
<div id="schedule-status" style="font-size:13px;margin-bottom:10px;color:var(--text-muted);">Loading schedule...</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
<div>
<label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;margin-bottom:8px;">
<input type="checkbox" id="sched-enabled"> <span>Enable scheduled backups</span>
</label>
<div style="margin-bottom:8px;">
<div style="display:flex;gap:8px;margin-bottom:8px;">
<label style="display:flex;align-items:center;gap:4px;font-size:13px;cursor:pointer;">
<input type="radio" name="sched-mode" value="interval" checked onchange="toggleSchedMode()">
Interval
</label>
<label style="display:flex;align-items:center;gap:4px;font-size:13px;cursor:pointer;">
<input type="radio" name="sched-mode" value="schedule" onchange="toggleSchedMode()">
Specific days &amp; time
</label>
</div>
<div id="sched-interval-fields" style="display:flex;gap:6px;align-items:center;">
<input type="number" id="sched-days" value="1" min="0" max="365"
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
<span style="font-size:12px;color:var(--text-muted);">days</span>
<input type="number" id="sched-hours" value="0" min="0" max="23"
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
<span style="font-size:12px;color:var(--text-muted);">hours</span>
<input type="number" id="sched-mins" value="0" min="0" max="59"
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
<span style="font-size:12px;color:var(--text-muted);">mins</span>
</div>
<div id="sched-schedule-fields" style="display:none;">
<div style="display:flex;gap:6px;margin-bottom:6px;flex-wrap:wrap;">
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="0"> Mon
</label>
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="1"> Tue
</label>
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="2"> Wed
</label>
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="3"> Thu
</label>
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="4"> Fri
</label>
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="5"> Sat
</label>
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
<input type="checkbox" class="sched-day" value="6"> Sun
</label>
</div>
<div>
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:4px;">Times</label>
<div id="sched-times-list">
<div style="display:flex;gap:6px;margin-bottom:4px;">
<input type="time" class="sched-time" value="05:00"
style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">&times;</button>
</div>
</div>
<button onclick="addSchedTime()" style="margin-top:4px;padding:4px 12px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:12px;">+ Add time</button>
</div>
</div>
</div>
</div>
<div>
<div style="margin-bottom:8px;">
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Keep last N backups (0 = unlimited)</label>
<input type="number" id="sched-keep" value="5" min="0" max="100"
style="width:100%;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
</div>
<div style="margin-bottom:8px;">
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Encryption password (leave blank for no encryption)</label>
<input type="password" id="sched-password" placeholder="All scheduled backups use this password"
style="width:100%;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
</div>
</div>
</div>
<div id="sched-next-run" style="font-size:12px;color:var(--text-muted);margin-top:8px;"></div>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Restore to Configured VM</span>
</div>
<div class="card-body">
<p style="color:var(--text-muted);font-size:13px;margin-bottom:16px;">
Restore a backup onto a <strong>freshly provisioned VM</strong> (Alpine Linux + K3s already installed).
The dashboard will guide you through each step.
</p>
<div id="restore-steps">
<div class="restore-step" data-step="1">
<div class="step-number">1</div>
<div class="step-content">
<div class="step-title">Select Backup</div>
<div class="step-body">
<select id="restore-backup-select" style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;margin-bottom:8px;">
<option value="">-- Select a backup --</option>
</select>
<div id="restore-preview" style="display:none;font-size:13px;color:var(--text-muted);"></div>
</div>
</div>
</div>
<div class="restore-step" data-step="2">
<div class="step-number">2</div>
<div class="step-content">
<div class="step-title">Verify Connection</div>
<div class="step-body">
<p style="font-size:12px;color:var(--text-muted);margin-bottom:8px;">
Uses the SSH key and host configured in <code>settings.yaml</code>.
Ensure the dashboard is already set up to manage the target VM before restoring.
</p>
<button onclick="testConnection()" id="test-conn-btn" style="padding:8px 20px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Test Connection</button>
<div id="conn-result" style="margin-top:8px;font-size:13px;"></div>
</div>
</div>
</div>
<div class="restore-step" data-step="3">
<div class="step-number">3</div>
<div class="step-content">
<div class="step-title">Restore Options</div>
<div class="step-body">
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-db" checked> <span>Game database (from battlegroup backup)</span>
</label>
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-dash-db" checked> <span>Dashboard database (bans, audit log, chat history, player IPs, settings)</span>
</label>
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-k8s" checked> <span>K8s secrets &amp; configmaps</span>
</label>
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-battlegroup" checked> <span>Battlegroup CRD (triggers pod provisioning)</span>
</label>
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-rmq" checked> <span>Re-create RMQ dashboard_admin user</span>
</label>
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-ping-fix" checked> <span>Apply HOST_DATACENTER ping fix</span>
</label>
<div id="new-ip-group" style="margin:8px 0 0 24px;display:none;">
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">New public IP for ping fix</label>
<input type="text" id="restore-new-ip" placeholder="Same as VM IP if unchanged"
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
</div>
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
<input type="checkbox" id="opt-settings" checked> <span>Restore dashboard settings.yaml</span>
</label>
<div style="margin:12px 0 0 0;padding:10px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:4px;">
<div style="font-size:12px;color:var(--text-muted);margin-bottom:4px;">Backup password (if encrypted)</div>
<input type="password" id="restore-password" placeholder="Leave blank if not password-protected"
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
</div>
</div>
</div>
</div>
<div class="restore-step" data-step="4">
<div class="step-number">4</div>
<div class="step-content">
<div class="step-title">Execute Restore</div>
<div class="step-body">
<p style="font-size:13px;color:var(--text-muted);margin-bottom:12px;">
This will <strong>overwrite all data</strong> on the target VM. Ensure you have selected the correct backup and VM.
</p>
<button onclick="startRestore()" id="restore-btn" style="padding:10px 24px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:14px;font-weight:bold;">
Start Restore
</button>
<div id="restore-progress" style="display:none;margin-top:16px;">
<div style="background:var(--border);border-radius:4px;height:20px;overflow:hidden;margin-bottom:12px;">
<div id="progress-bar" style="height:100%;background:var(--accent);border-radius:4px;width:0%;transition:width 0.5s;"></div>
</div>
<div id="progress-steps" style="font-size:13px;"></div>
<div id="restore-complete" style="display:none;margin-top:12px;padding:12px;background:var(--bg-card);border:1px solid var(--border);border-radius:4px;font-size:13px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<style>
.restore-step {
display:flex;gap:16px;padding:16px 0;
border-bottom:1px solid var(--border);
}
.restore-step:last-child { border-bottom:none; }
.step-number {
width:32px;height:32px;border-radius:50%;
background:var(--accent);color:#fff;
display:flex;align-items:center;justify-content:center;
font-weight:bold;font-size:14px;flex-shrink:0;
}
.step-content { flex:1; }
.step-title { font-weight:bold;font-size:14px;margin-bottom:8px;color:var(--text); }
.step-body { padding-left:0; }
#restore-steps .restore-step.disabled { opacity:0.4;pointer-events:none; }
.backup-row {
display:flex;align-items:center;padding:8px 12px;
border-bottom:1px solid var(--border);font-size:13px;
}
.backup-row:last-child { border-bottom:none; }
.backup-row:hover { background:var(--bg-hover); }
.backup-name { flex:1;font-weight:bold; }
.backup-size { width:80px;text-align:right;color:var(--text-muted); }
.backup-date { width:160px;color:var(--text-muted); }
.backup-actions { width:120px;text-align:right; }
.backup-actions button {
padding:4px 10px;font-size:12px;border:none;border-radius:3px;
cursor:pointer;margin-left:4px;
}
</style>
<script>
let restorePollInterval = null;
function showStatus(msg, type) {
const el = document.getElementById('backup-status');
el.textContent = msg;
el.className = 'error-banner ' + (type || 'info');
el.style.display = 'block';
}
function hideStatus() {
document.getElementById('backup-status').style.display = 'none';
}
function bytesStr(bytes) {
if (!bytes) return '0 B';
const u = ['B', 'KB', 'MB', 'GB'];
let i = 0;
let v = bytes;
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
return v.toFixed(1) + ' ' + u[i];
}
function esc(s) {
if (!s) return '';
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
// ── Backup Management ──────────────────────────────────────────────
async function loadBackups() {
try {
const r = await csrfFetch('/api/backup/list');
const d = await r.json();
const container = document.getElementById('backup-list');
if (!d.success || !d.backups || d.backups.length === 0) {
container.innerHTML = '<p style="color:var(--text-muted);font-size:13px;">No backups found. Click "Create Backup" to create one.</p>';
return;
}
let html = '<div style="background:var(--bg-card);border:1px solid var(--border);border-radius:4px;">';
html += '<div class="backup-row" style="font-weight:bold;color:var(--text-muted);font-size:12px;">';
html += '<div class="backup-name">Name</div><div class="backup-date">Created</div><div class="backup-size">Size</div><div class="backup-actions">Actions</div></div>';
for (const b of d.backups) {
html += '<div class="backup-row">';
const lock = b.password_protected ? ' &#128274;' : '';
html += '<div class="backup-name">' + esc(b.name) + lock + '</div>';
html += '<div class="backup-date">' + esc(b.created) + '</div>';
html += '<div class="backup-size">' + bytesStr(b.size) + '</div>';
html += '<div class="backup-actions">';
html += '<button onclick="verifyBackup(\'' + esc(b.name) + '\')" title="Verify">&#10003;</button>';
html += '<button onclick="deleteBackup(\'' + esc(b.name) + '\')" title="Delete" style="background:#c0392b;color:#fff;">&#10005;</button>';
html += '</div></div>';
}
html += '</div>';
container.innerHTML = html;
populateRestoreSelect(d.backups);
} catch (e) {
document.getElementById('backup-list').innerHTML = '<p style="color:red;font-size:13px;">Failed to load backups: ' + esc(e.message) + '</p>';
}
}
function populateRestoreSelect(backups) {
const sel = document.getElementById('restore-backup-select');
sel.innerHTML = '<option value="">-- Select a backup --</option>';
for (const b of backups) {
sel.innerHTML += '<option value="' + esc(b.name) + '">' + esc(b.name) + ' (' + bytesStr(b.size) + ')</option>';
}
}
async function createBackup() {
const pw = prompt('Optional: Enter a password to encrypt this backup (leave blank for no encryption):', '');
const btn = document.getElementById('create-btn');
btn.disabled = true;
btn.textContent = 'Creating...';
showStatus('Creating backup... this may take several minutes.', 'info');
try {
const r = await csrfFetch('/api/backup/create', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({password: pw || ''})
});
const d = await r.json();
if (d.success) {
const note = pw ? ' (password protected)' : '';
showStatus('Backup created successfully (' + bytesStr(d.size) + ')' + note, 'success');
} else {
showStatus('Backup failed: ' + esc(d.error), 'error');
}
} catch (e) {
showStatus('Error: ' + esc(e.message), 'error');
}
btn.disabled = false;
btn.textContent = 'Create Backup';
loadBackups();
}
async function verifyBackup(name) {
const pw = prompt('Enter backup password (leave blank if not encrypted):', '');
showStatus('Verifying ' + name + '...', 'info');
try {
const r = await csrfFetch('/api/backup/verify', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({name, password: pw || ''})
});
const d = await r.json();
if (d.success && d.valid) {
if (d.encrypted && d.files === 0) {
showStatus(name + ' is encrypted. ' + esc(d.note || 'Enter password to verify contents.'), 'info');
} else {
showStatus(name + ' verified: ' + d.files + ' files, ' + bytesStr(d.size), 'success');
}
} else {
showStatus('Verification failed: ' + esc(d.error || 'Corrupt backup'), 'error');
}
} catch (e) {
showStatus('Error: ' + esc(e.message), 'error');
}
}
async function deleteBackup(name) {
if (!confirm('Delete backup "' + name + '"? This cannot be undone.')) return;
try {
const r = await csrfFetch('/api/backup/delete', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({name})
});
const d = await r.json();
if (d.success) {
showStatus('Backup deleted.', 'info');
loadBackups();
} else {
showStatus('Delete failed.', 'error');
}
} catch (e) {
showStatus('Error: ' + esc(e.message), 'error');
}
}
// ── Schedule ─────────────────────────────────────────────────────
function toggleSchedMode() {
const isInterval = document.querySelector('input[name="sched-mode"]:checked').value === 'interval';
document.getElementById('sched-interval-fields').style.display = isInterval ? 'flex' : 'none';
document.getElementById('sched-schedule-fields').style.display = isInterval ? 'none' : 'block';
}
function schedDaysArray() {
const days = [];
document.querySelectorAll('.sched-day:checked').forEach(cb => days.push(parseInt(cb.value)));
return days;
}
function schedTimesArray() {
const times = [];
document.querySelectorAll('.sched-time').forEach(inp => { if (inp.value) times.push(inp.value); });
return times;
}
function addSchedTime() {
const list = document.getElementById('sched-times-list');
const div = document.createElement('div');
div.style.cssText = 'display:flex;gap:6px;margin-bottom:4px;';
div.innerHTML = '<input type="time" class="sched-time" value="05:00" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
+ '<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">&times;</button>';
list.appendChild(div);
}
function removeSchedTime(btn) {
const list = document.getElementById('sched-times-list');
if (list.children.length > 1) {
btn.parentElement.remove();
}
}
async function loadSchedule() {
try {
const r = await csrfFetch('/api/backup/schedule');
const d = await r.json();
if (!d.success) return;
const s = d.schedule;
document.getElementById('sched-enabled').checked = s.enabled;
const mode = s.mode || 'interval';
const radio = document.querySelector('input[name="sched-mode"][value="' + mode + '"]');
if (radio) radio.checked = true;
toggleSchedMode();
if (s.interval_minutes) {
const total = s.interval_minutes;
document.getElementById('sched-days').value = Math.floor(total / 1440);
document.getElementById('sched-hours').value = Math.floor((total % 1440) / 60);
document.getElementById('sched-mins').value = total % 60;
}
(s.schedule_days || []).forEach(v => {
const cb = document.querySelector('.sched-day[value="' + v + '"]');
if (cb) cb.checked = true;
});
const times = s.schedule_times || ['05:00'];
const list = document.getElementById('sched-times-list');
list.innerHTML = '';
times.forEach(t => {
const div = document.createElement('div');
div.style.cssText = 'display:flex;gap:6px;margin-bottom:4px;';
div.innerHTML = '<input type="time" class="sched-time" value="' + t + '" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
+ '<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">&times;</button>';
list.appendChild(div);
});
document.getElementById('sched-keep').value = s.keep;
document.getElementById('sched-password').value = s.password || '';
const status = document.getElementById('schedule-status');
status.innerHTML = s.enabled
? '<span style="color:#27ae60;">&#9679; Active</span>'
: '<span style="color:var(--text-muted);">&#9679; Disabled</span>';
const nextEl = document.getElementById('sched-next-run');
if (s.enabled && s.next_run) {
const dt = new Date(s.next_run);
const pad = n => String(n).padStart(2,'0');
const fmt = pad(dt.getDate())+'-'+pad(dt.getMonth()+1)+'-'+dt.getFullYear()+' '+pad(dt.getHours())+':'+pad(dt.getMinutes());
nextEl.textContent = 'Next run: ' + fmt;
} else {
nextEl.textContent = '';
}
} catch (e) {
document.getElementById('schedule-status').textContent = 'Failed to load schedule';
}
}
async function saveSchedule() {
const btn = document.getElementById('save-sched-btn');
btn.disabled = true;
btn.textContent = 'Saving...';
const mode = document.querySelector('input[name="sched-mode"]:checked').value;
const body = {
enabled: document.getElementById('sched-enabled').checked,
mode: mode,
keep: parseInt(document.getElementById('sched-keep').value),
password: document.getElementById('sched-password').value,
};
if (mode === 'interval') {
body.interval_minutes = parseInt(document.getElementById('sched-days').value) * 1440
+ parseInt(document.getElementById('sched-hours').value) * 60
+ parseInt(document.getElementById('sched-mins').value);
} else {
body.schedule_days = schedDaysArray();
body.schedule_times = schedTimesArray();
}
try {
const r = await csrfFetch('/api/backup/schedule', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify(body)
});
const d = await r.json();
if (d.success) {
showStatus('Schedule saved.', 'success');
loadSchedule();
} else {
showStatus('Failed to save schedule.', 'error');
}
} catch (e) {
showStatus('Error: ' + esc(e.message), 'error');
}
btn.disabled = false;
btn.textContent = 'Save';
}
async function runScheduledNow() {
if (!confirm('Run a scheduled backup now? This will also apply retention.')) return;
const btn = document.getElementById('run-sched-btn');
btn.disabled = true;
btn.textContent = 'Running...';
showStatus('Running scheduled backup...', 'info');
try {
const r = await csrfFetch('/api/backup/run-scheduled', {method:'POST'});
const d = await r.json();
if (d.success) {
showStatus('Scheduled backup completed (' + bytesStr(d.size) + ')', 'success');
loadBackups();
loadSchedule();
} else {
showStatus('Scheduled backup failed: ' + esc(d.error), 'error');
}
} catch (e) {
showStatus('Error: ' + esc(e.message), 'error');
}
btn.disabled = false;
btn.textContent = 'Run Now';
}
// ── Restore Wizard ─────────────────────────────────────────────────
document.getElementById('restore-backup-select').addEventListener('change', async function() {
const name = this.value;
const preview = document.getElementById('restore-preview');
if (!name) { preview.style.display = 'none'; return; }
try {
const r = await csrfFetch('/api/backup/restore/preview', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({name})
});
const d = await r.json();
if (d.success) {
preview.style.display = 'block';
let html = '<div style="margin-top:8px;padding:8px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:4px;">';
html += '<strong>Backup contents:</strong><br>';
html += 'Created: ' + esc(d.created) + '<br>';
const comps = d.components || [];
if (comps.length > 0) {
html += '<ul style="margin:4px 0 0 16px;padding:0;">';
for (const c of comps) {
html += '<li>' + esc(c.name) + ' (' + bytesStr(c.size) + ')</li>';
}
html += '</ul>';
}
html += '</div>';
preview.innerHTML = html;
}
} catch(e) { preview.innerHTML = '<span style="color:red;">Error loading preview</span>'; }
});
document.getElementById('opt-ping-fix').addEventListener('change', function() {
document.getElementById('new-ip-group').style.display = this.checked ? 'block' : 'none';
});
async function testConnection() {
const resultDiv = document.getElementById('conn-result');
const btn = document.getElementById('test-conn-btn');
btn.disabled = true;
btn.textContent = 'Testing...';
resultDiv.innerHTML = 'Testing connection...';
try {
const r = await csrfFetch('/api/backup/restore/test-connection', {
method:'POST', headers:{'Content-Type':'application/json'}
});
const d = await r.json();
if (d.success) {
let html = '<span style="color:#27ae60;">&#10003; Connected to ' + esc(d.hostname) + '</span>';
if (d.k8s_ok) html += '<br><span style="color:#27ae60;">&#10003; kubectl accessible</span>';
else html += '<br><span style="color:#f39c12;">&#9888; kubectl not detected (is K3s installed?)</span>';
resultDiv.innerHTML = html;
} else {
resultDiv.innerHTML = '<span style="color:red;">&#10005; ' + esc(d.error) + '</span>';
}
} catch(e) {
resultDiv.innerHTML = '<span style="color:red;">Error: ' + esc(e.message) + '</span>';
}
btn.disabled = false;
btn.textContent = 'Test Connection';
}
async function startRestore() {
const name = document.getElementById('restore-backup-select').value;
if (!name) {
showStatus('Please select a backup.', 'error');
return;
}
if (!confirm('This will OVERWRITE ALL DATA on the configured server. Are you sure?')) return;
if (!confirm('Last chance — are you absolutely sure you want to restore "' + name + '"?')) return;
const password = document.getElementById('restore-password').value;
const options = {
restore_db: document.getElementById('opt-db').checked,
restore_dash_db: document.getElementById('opt-dash-db').checked,
restore_k8s: document.getElementById('opt-k8s').checked,
restore_battlegroup: document.getElementById('opt-battlegroup').checked,
restore_rmq: document.getElementById('opt-rmq').checked,
restore_ping_fix: document.getElementById('opt-ping-fix').checked,
restore_settings: document.getElementById('opt-settings').checked,
new_ip: document.getElementById('restore-new-ip').value.trim() || '',
password: password || '',
};
const btn = document.getElementById('restore-btn');
btn.disabled = true;
btn.textContent = 'Restoring...';
document.getElementById('restore-progress').style.display = 'block';
document.getElementById('progress-bar').style.width = '0%';
document.getElementById('progress-steps').innerHTML = '';
document.getElementById('restore-complete').style.display = 'none';
try {
const r = await csrfFetch('/api/backup/restore/start', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({name, vm_ip: vmIp, options})
});
const d = await r.json();
if (!d.success) {
showStatus('Restore failed to start: ' + esc(d.error), 'error');
btn.disabled = false;
btn.textContent = 'Start Restore';
return;
}
restorePollInterval = setInterval(() => pollRestore(d.restore_id), 2000);
} catch(e) {
showStatus('Error: ' + esc(e.message), 'error');
btn.disabled = false;
btn.textContent = 'Start Restore';
}
}
async function pollRestore(restoreId) {
try {
const r = await csrfFetch('/api/backup/restore/status', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({restore_id: restoreId})
});
const d = await r.json();
if (!d.success) {
clearInterval(restorePollInterval);
return;
}
document.getElementById('progress-bar').style.width = d.progress + '%';
let html = '';
for (let i = 0; i < d.steps.length; i++) {
const step = d.steps[i];
const completed = d.completed_steps.find(s => s.label === step);
if (completed) {
const icon = completed.success ? '&#10003;' : '&#10005;';
const color = completed.success ? '#27ae60' : '#c0392b';
html += '<div style="padding:4px 0;"><span style="color:' + color + ';">' + icon + '</span> ' + esc(step) + '</div>';
} else if (i < d.current_step) {
html += '<div style="padding:4px 0;color:var(--text-muted);">&#9679; ' + esc(step) + '</div>';
} else if (i === d.current_step) {
html += '<div style="padding:4px 0;color:var(--accent);font-weight:bold;">&#9654; ' + esc(step) + '</div>';
} else {
html += '<div style="padding:4px 0;color:var(--text-muted);opacity:0.5;">' + esc(step) + '</div>';
}
}
document.getElementById('progress-steps').innerHTML = html;
if (d.status === 'completed' || d.status === 'completed_with_errors') {
clearInterval(restorePollInterval);
const completeDiv = document.getElementById('restore-complete');
completeDiv.style.display = 'block';
if (d.errors && d.errors.length > 0) {
completeDiv.innerHTML = '<strong style="color:#f39c12;">Restore completed with warnings:</strong><br>' +
d.errors.map(e => '<div style="color:#c0392b;font-size:12px;">&#9888; ' + esc(e) + '</div>').join('');
} else {
completeDiv.innerHTML = '<strong style="color:#27ae60;">&#10003; Restore completed successfully!</strong>';
}
document.getElementById('restore-btn').disabled = false;
document.getElementById('restore-btn').textContent = 'Start Restore';
}
} catch(e) {
clearInterval(restorePollInterval);
}
}
loadBackups();
loadSchedule();
</script>
{% endblock %}
+70 -13
View File
@@ -7,14 +7,45 @@
<meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
<script>
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
async function csrfFetch(url, options = {}) {
options.headers = options.headers || {};
options.headers['X-CSRFToken'] = csrfToken;
return fetch(url, options);
}
</script>
{% block head_extra %}{% endblock %} {% block head_extra %}{% endblock %}
</head> </head>
<body> <body>
<button class="nav-toggle" id="navToggle" title="Toggle nav layout" onclick="toggleNavLayout()">☰</button>
<nav> <nav>
<div class="brand">DUNE DASHBOARD</div> <div class="brand">DUNE DASHBOARD</div>
{% for href, label in nav_pages %} <!-- Horizontal: use grouped nav -->
<a href="{{ href }}" class="{% if current_path == href %}active{% endif %}">{{ label }}</a> <div class="nav-links-h">
{% endfor %} {% for item in nav_groups %}
{% if item|length == 2 and item[1] is string %}
{# Simple link #}
<a href="{{ item[0] }}" class="{% if current_path == item[0] %}active{% endif %}">{{ item[1] }}</a>
{% else %}
{# Dropdown group: item[0] is label, item[1] is list of (href, label) #}
<div class="nav-dropdown">
<a class="nav-dropdown-toggle {% for ih, il in item[1] %}{% if current_path == ih %}active{% endif %}{% endfor %}">{{ item[0] }} ▾</a>
<div class="nav-dropdown-content">
{% for ih, il in item[1] %}
<a href="{{ ih }}" class="{% if current_path == ih %}active{% endif %}">{{ il }}</a>
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
<!-- Vertical nav links (flat list) -->
<div class="nav-links-v">
{% for href, label in nav_pages %}
<a href="{{ href }}" class="{% if current_path == href %}active{% endif %}">{{ label }}</a>
{% endfor %}
</div>
<div class="spacer"></div> <div class="spacer"></div>
<div class="theme-dropdown"> <div class="theme-dropdown">
<button class="theme-btn" title="Theme">🎨</button> <button class="theme-btn" title="Theme">🎨</button>
@@ -93,12 +124,12 @@
</div> </div>
</div> </div>
</div> </div>
<span style="font-size:12px;color:var(--nav-text);display:flex;align-items:center;"> <span class="nav-conn">
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span> <span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
{{ 'Connected' if conn_ok else 'Disconnected' }} {{ 'Connected' if conn_ok else 'Disconnected' }}
</span> </span>
{% if current_user and current_user.is_authenticated %} {% if current_user and current_user.is_authenticated %}
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a> <a href="/logout" class="nav-logout">Logout</a>
{% endif %} {% endif %}
</nav> </nav>
<main class="container"> <main class="container">
@@ -108,14 +139,6 @@
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span> <span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
</footer> </footer>
<script> <script>
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
async function csrfFetch(url, options = {}) {
options.headers = options.headers || {};
options.headers['X-CSRFToken'] = csrfToken;
return fetch(url, options);
}
// Theme System // Theme System
function setTheme(themeName) { function setTheme(themeName) {
document.documentElement.setAttribute('data-theme', themeName); document.documentElement.setAttribute('data-theme', themeName);
@@ -135,7 +158,41 @@
updateThemeUI(savedTheme); updateThemeUI(savedTheme);
} }
// Nav Layout System (experimental vertical toggle)
function toggleNavLayout() {
const body = document.body;
const isMobile = window.innerWidth <= 768;
if (isMobile) {
document.querySelector('nav').classList.toggle('nav-open');
return;
}
const current = body.getAttribute('data-nav-layout') || 'horizontal';
const next = current === 'horizontal' ? 'vertical' : 'horizontal';
body.setAttribute('data-nav-layout', next);
localStorage.setItem('dune-nav-layout', next);
}
function initNavLayout() {
const isMobile = window.innerWidth <= 768;
if (isMobile) {
document.body.setAttribute('data-nav-layout', 'vertical');
localStorage.removeItem('dune-nav-layout');
} else {
const saved = localStorage.getItem('dune-nav-layout') || 'horizontal';
document.body.setAttribute('data-nav-layout', saved);
}
}
window.addEventListener('resize', function() {
const isMobile = window.innerWidth <= 768;
const current = document.body.getAttribute('data-nav-layout');
if (isMobile && current !== 'vertical') {
document.body.setAttribute('data-nav-layout', 'vertical');
}
});
initTheme(); initTheme();
initNavLayout();
</script> </script>
{% block scripts %}{% endblock %} {% block scripts %}{% endblock %}
<style> <style>
+106 -3
View File
@@ -41,6 +41,18 @@
{% endif %} {% endif %}
</div> </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 style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
<div class="card"> <div class="card">
<div class="card-header">Players Per Map</div> <div class="card-header">Players Per Map</div>
@@ -307,17 +319,108 @@
{% block scripts %} {% block scripts %}
<script> <script>
// Auto-refresh node metrics every 5 seconds // ── Node resource charts ──────────────────────────────────────────────
setInterval(async function() { 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 { try {
const resp = await fetch('/server/metrics'); const resp = await fetch('/server/metrics');
const data = await resp.json(); const data = await resp.json();
if (data.cpu) { if (data.cpu) {
document.getElementById('node-cpu').textContent = 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; 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) {} } catch (e) {}
}, 5000); }
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 => { document.querySelectorAll('.btn-action').forEach(btn => {
btn.addEventListener('click', async function() { btn.addEventListener('click', async function() {
+257 -6
View File
@@ -35,27 +35,79 @@
</div> </div>
<div class="card"> <div class="card">
<div class="card-header">Pods ({{ pods|length }})</div> <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
<span>Pods (<span id="pod-count">{{ pods|length }}</span>)</span>
<button onclick="refreshPodList()" style="padding:4px 12px;background:var(--primary);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">↻ Refresh</button>
</div>
<div class="table-wrap"> <div class="table-wrap">
<table> <table id="pods-table">
<thead> <thead>
<tr><th>Name</th><th>Role</th><th>Status</th></tr> <tr><th>Name</th><th>Role</th><th>Status</th><th>Actions</th></tr>
</thead> </thead>
<tbody> <tbody>
{% for pod in pods %} {% for pod in pods %}
<tr> <tr data-pod="{{ pod.name }}" data-role="{{ pod.role }}">
<td style="font-family:monospace;font-size:12px;">{{ pod.name }}</td> <td style="font-family:monospace;font-size:12px;">{{ pod.name }}</td>
<td><span class="badge badge-{{ pod.role.lower() if pod.role else 'default' }}">{{ pod.role or 'default' }}</span></td> <td><span class="badge badge-{{ (pod.role or 'default').lower() }}">{{ pod.role or 'default' }}</span></td>
<td><span class="badge badge-{{ pod.status.lower() }}">{{ pod.status }}</span></td> <td><span class="badge badge-{{ pod.status.lower() }}">{{ pod.status }}</span></td>
<td style="white-space:nowrap;">
<button class="pod-btn shell-btn" onclick="shellPod('{{ pod.name }}')" title="Open shell">[>_]</button>
<button class="pod-btn logs-btn" onclick="fetchPodLogs('{{ pod.name }}')" title="View logs">[&#128196;]</button>
<button class="pod-btn desc-btn" onclick="fetchPodDescribe('{{ pod.name }}')" title="Describe pod">[i]</button>
{% if pod.role == 'igw-database-operation' %}
<button class="pod-btn del-btn-safe" onclick="promptDeletePod('{{ pod.name }}', true)" title="Delete DB backup pod">[&#128465; DB backup]</button>
{% else %}
<button class="pod-btn del-btn" onclick="promptDeletePod('{{ pod.name }}', false)" title="Delete pod">[&#128465;]</button>
{% endif %}
</td>
</tr> </tr>
{% else %} {% else %}
<tr><td colspan="3" class="empty">No pods found</td></tr> <tr><td colspan="4" class="empty">No pods found</td></tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
<!-- Pod Logs Modal -->
<div id="logs-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('logs-modal')">
<div class="modal" style="max-width:900px;">
<div class="modal-header"><h3>Pod Logs — <span id="logs-pod-name"></span></h3></div>
<div id="logs-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading logs...</div>
<pre id="logs-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
<button onclick="closeModal('logs-modal')" class="btn-cancel">Close</button>
</div>
</div>
</div>
<!-- Pod Describe Modal -->
<div id="describe-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('describe-modal')">
<div class="modal" style="max-width:900px;">
<div class="modal-header"><h3>Describe Pod — <span id="describe-pod-name"></span></h3></div>
<div id="describe-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading...</div>
<pre id="describe-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
<button onclick="closeModal('describe-modal')" class="btn-cancel">Close</button>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div id="delete-modal" class="modal-overlay" style="display:none;">
<div class="modal" style="max-width:450px;">
<div class="modal-header"><h3 id="delete-modal-title">Delete Pod</h3></div>
<div class="modal-body" style="padding:20px;">
<p id="delete-modal-message">Are you sure you want to delete this pod?</p>
<p style="font-family:monospace;font-size:14px;padding:8px 12px;background:var(--bg-card);border-radius:4px;margin:12px 0 0;" id="delete-pod-name-display"></p>
</div>
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
<button onclick="closeModal('delete-modal')" class="btn-cancel">Cancel</button>
<button id="delete-confirm-btn" onclick="confirmDeletePod()" class="btn-danger" style="margin-left:8px;">Delete Pod</button>
</div>
</div>
</div>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
@@ -178,9 +230,208 @@ function setupTerminalInput(term, type) {
socket.emit('shell_input', {data: data, type: type}); socket.emit('shell_input', {data: data, type: type});
}); });
} }
// ── Pod action functions ──────────────────────────────────────────
let _pendingDeletePod = null;
function openModal(id) {
document.getElementById(id).style.display = '';
}
function closeModal(id) {
document.getElementById(id).style.display = 'none';
}
function shellPod(name) {
const sel = document.getElementById('pod-select');
for (let i = 0; i < sel.options.length; i++) {
if (sel.options[i].value === name) {
sel.selectedIndex = i;
break;
}
}
if (!connectedPod) {
toggleShell('pod');
}
}
function fetchPodLogs(name) {
document.getElementById('logs-pod-name').textContent = name;
document.getElementById('logs-content').style.display = 'none';
document.getElementById('logs-loading').style.display = '';
document.getElementById('logs-content').textContent = '';
openModal('logs-modal');
csrfFetch('/api/pod/logs', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({pod: name}),
})
.then(r => r.json())
.then(data => {
document.getElementById('logs-loading').style.display = 'none';
if (data.success) {
const el = document.getElementById('logs-content');
el.textContent = data.logs || '(empty logs)';
el.style.display = '';
} else {
document.getElementById('logs-content').textContent = 'Error: ' + (data.error || 'Unknown');
document.getElementById('logs-content').style.display = '';
}
})
.catch(err => {
document.getElementById('logs-loading').style.display = 'none';
document.getElementById('logs-content').textContent = 'Request failed: ' + err;
document.getElementById('logs-content').style.display = '';
});
}
function fetchPodDescribe(name) {
document.getElementById('describe-pod-name').textContent = name;
document.getElementById('describe-content').style.display = 'none';
document.getElementById('describe-loading').style.display = '';
document.getElementById('describe-content').textContent = '';
openModal('describe-modal');
csrfFetch('/api/pod/describe', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({pod: name}),
})
.then(r => r.json())
.then(data => {
document.getElementById('describe-loading').style.display = 'none';
if (data.success) {
const el = document.getElementById('describe-content');
el.textContent = data.describe || '(empty)';
el.style.display = '';
} else {
document.getElementById('describe-content').textContent = 'Error: ' + (data.error || 'Unknown');
document.getElementById('describe-content').style.display = '';
}
})
.catch(err => {
document.getElementById('describe-loading').style.display = 'none';
document.getElementById('describe-content').textContent = 'Request failed: ' + err;
document.getElementById('describe-content').style.display = '';
});
}
function promptDeletePod(name, safe) {
_pendingDeletePod = name;
document.getElementById('delete-pod-name-display').textContent = name;
const title = document.getElementById('delete-modal-title');
const msg = document.getElementById('delete-modal-message');
const btn = document.getElementById('delete-confirm-btn');
if (safe) {
title.textContent = 'Delete DB Backup Pod';
msg.innerHTML = 'This pod stores database backups. It is <strong>safe to delete</strong> — Kubernetes will recreate it automatically. Continue?';
btn.className = 'btn-edit';
btn.textContent = 'Delete Backup Pod';
} else {
title.textContent = 'Delete Pod?';
msg.innerHTML = 'Deleting a pod will restart it. Depending on the pod role, this may cause a brief service interruption. Proceed?';
btn.className = 'btn-danger';
btn.textContent = 'Delete Pod';
}
openModal('delete-modal');
}
function confirmDeletePod() {
const name = _pendingDeletePod;
if (!name) return;
closeModal('delete-modal');
const btn = document.querySelector(`[data-pod="${name}"] .del-btn, [data-pod="${name}"] .del-btn-safe`);
if (btn) { btn.textContent = '...'; btn.disabled = true; }
csrfFetch('/api/pod/delete', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({pod: name}),
})
.then(r => r.json())
.then(data => {
if (data.success) {
setTimeout(refreshPodList, 3000);
} else {
alert('Delete failed: ' + (data.error || 'Unknown'));
}
})
.catch(err => {
alert('Delete request failed: ' + err);
})
.finally(() => {
_pendingDeletePod = null;
});
}
function refreshPodList() {
csrfFetch('/api/pods')
.then(r => r.json())
.then(data => {
if (!data.success) return;
const tbody = document.querySelector('#pods-table tbody');
const countEl = document.getElementById('pod-count');
if (!tbody) return;
tbody.innerHTML = '';
if (!data.pods || data.pods.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" class="empty">No pods found</td></tr>';
if (countEl) countEl.textContent = '0';
// Also update pod select
const sel = document.getElementById('pod-select');
sel.innerHTML = '';
return;
}
if (countEl) countEl.textContent = data.pods.length;
// Rebuild pod select
const sel = document.getElementById('pod-select');
sel.innerHTML = '';
data.pods.forEach(p => {
const opt = document.createElement('option');
opt.value = p.name;
opt.textContent = p.name;
sel.appendChild(opt);
// Build table row
const tr = document.createElement('tr');
tr.dataset.pod = p.name;
tr.dataset.role = p.role || '';
const role = p.role || 'default';
const roleLower = role.toLowerCase();
tr.innerHTML = `
<td style="font-family:monospace;font-size:12px;">${p.name}</td>
<td><span class="badge badge-${roleLower}">${role}</span></td>
<td><span class="badge badge-${p.status.toLowerCase()}">${p.status}</span></td>
<td style="white-space:nowrap;">
<button class="pod-btn shell-btn" onclick="shellPod('${p.name}')" title="Open shell">[>_]</button>
<button class="pod-btn logs-btn" onclick="fetchPodLogs('${p.name}')" title="View logs">[📄]</button>
<button class="pod-btn desc-btn" onclick="fetchPodDescribe('${p.name}')" title="Describe pod">[i]</button>
${p.role === 'igw-database-operation'
? `<button class="pod-btn del-btn-safe" onclick="promptDeletePod('${p.name}', true)" title="Delete DB backup pod">[🗑 DB backup]</button>`
: `<button class="pod-btn del-btn" onclick="promptDeletePod('${p.name}', false)" title="Delete pod">[🗑]</button>`
}
</td>`;
tbody.appendChild(tr);
});
})
.catch(() => {});
}
</script> </script>
<style> <style>
.xterm { height: 100%; } .xterm { height: 100%; }
.xterm-viewport { overflow-y: auto !important; } .xterm-viewport { overflow-y: auto !important; }
.pod-btn {
padding: 2px 6px; border: none; border-radius: 3px;
cursor: pointer; font-size: 11px; font-family: monospace;
margin: 0 2px; line-height: 1.6;
}
.shell-btn { background: var(--primary); color: #fff; }
.shell-btn:hover { opacity: .85; }
.logs-btn { background: #5a6c7d; color: #fff; }
.logs-btn:hover { opacity: .85; }
.desc-btn { background: #6c5a7d; color: #fff; }
.desc-btn:hover { opacity: .85; }
.del-btn { background: #c0392b; color: #fff; }
.del-btn:hover { opacity: .85; }
.del-btn-safe { background: #27ae60; color: #fff; padding: 2px 8px; }
.del-btn-safe:hover { opacity: .85; }
.pod-btn:disabled { opacity: .5; cursor: not-allowed; }
</style> </style>
{% endblock %} {% endblock %}