Compare commits

..
Author SHA1 Message Date
Reditus 4a94bf68ce fix: director ConfigMap name, CSRF, ServerSetScale replicas + error handling
- Fix ConfigMap name derivation (strip funcom-seabass- prefix from namespace)
- Fix CSRF token missing on all 6 director POST handlers (fetch -> csrfFetch)
- Add ServerSetScale replicas management to director map cards
- Merge webOverrideCfg into cfg so UI shows active runtime overrides
- Auto-refresh after Apply and reset button state on all handlers
- Surface JSON error bodies in error banner instead of silent fail
- Fix SSL SAN handling for IP vs DNS common name
- Fix Let's Encrypt certbot paths to use project-root certbot/ dir
- Fix deploys_ok to reflect actual K8s availability
- Add active server deployment matching with restart buttons
2026-05-29 11:55:57 +01:00
Reditus 0f173dc107 feat: separate dashboard database + launcher repair/cleanup options
- Move dashboard tables (bans, player_ips, audit_log, chat_history,
  settings, player_actions) to a dedicated 'dashboard' database to
  prevent pg_dump conflicts during game updates
- Add DashboardDatabaseService (legacy + backend) with auto-migration
  from old dashboard schema on first startup
- Add launcher option 9: Repair Game Database (fixes schema ownership)
- Add launcher option 10: Clean up Old Dashboard Schema (drops old schema)
- Update PlayerService to fetch IPs from dashboard DB separately
- Update all routes and services to use dash_db for dashboard tables
- Add dashboard_database_name config option to settings.yaml.example
- Update README with new menu options
2026-05-27 01:02:39 +01:00
22 changed files with 1158 additions and 220 deletions

No files matched your search

+3
View File
@@ -38,6 +38,9 @@ internal-scripts/ssh/sshKey
# SSL Certificates
ssl/
# Let's Encrypt certbot runtime data
certbot/
# Temporary settings scripts (generated by launcher)
read_settings*.py
hash_pw*.py
+2
View File
@@ -82,6 +82,8 @@ This project is **Source Available** under the [Dune Dashboard Source License (D
- **[6] Start Dashboard (Debug Mode)** — Launch with full debug logging enabled
- **[7] Start New Dashboard (React + ChakraUI)** — Launch the modern React dashboard with auto-installed dependencies
- **[8] Reset to Factory Defaults** — Wipe all data (settings, logs, certs, cache, node_modules) and return to a clean state
- **[9] Repair Game Database** — Fix dashboard schema ownership so game updates won't break servers
- **[10] Clean up Old Dashboard Schema** — Drop the old `dashboard` schema from the game database (after migration)
- **[Q] Quit** — Exit the launcher
3. **First-time Setup** (option 2)
+1
View File
@@ -39,6 +39,7 @@ DEFAULTS = {
'max_connections': 10,
'owner': 'dune',
'dashboard_schema': 'dashboard',
'dashboard_database_name': 'dashboard',
},
'kubernetes': {
'namespace': '',
+22 -8
View File
@@ -15,7 +15,7 @@ from flask_limiter.util import get_remote_address
from app.config import load_settings
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
from app.services.database import DatabaseService
from app.services.database import DatabaseService, DashboardDatabaseService
from app.services.ssh import SSHService
from app.services.k8s import K8sService
from app.services.player import PlayerService
@@ -188,19 +188,32 @@ def create_app(settings_path=None):
'database': settings['database']['name'],
}
dash_db_config = {
'host': db_host,
'port': settings['database']['port'],
'user': settings['database']['user'],
'password': settings['database']['password'],
'database': settings['database'].get('dashboard_database_name', 'dashboard'),
}
db_service = DatabaseService(
db_config,
min_conn=settings['database']['min_connections'],
max_conn=settings['database']['max_connections'],
dashboard_schema=settings['database'].get('dashboard_schema', 'dashboard')
)
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
db_service.ensure_tables()
logging.debug("Database tables ensured")
dash_db_service = DashboardDatabaseService(
dash_db_config,
min_conn=settings['database']['min_connections'],
max_conn=settings['database']['max_connections'],
owner=settings['database'].get('owner', 'dune'),
)
dash_db_service.ensure_tables(game_db=db_service)
# Create performance indexes if they don't exist
try:
admin_svc_for_indexes = AdminService(db_service, None)
admin_svc_for_indexes = AdminService(db_service, None, dash_db=dash_db_service)
success, created, error = admin_svc_for_indexes.create_indexes()
if success and created:
logging.info(f"Created {len(created)} database indexes")
@@ -223,11 +236,11 @@ def create_app(settings_path=None):
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
player_svc = PlayerService(db_service)
player_svc = PlayerService(db_service, dash_db=dash_db_service)
vehicle_svc = VehicleService(db_service)
chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache)
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service, static_cache)
logging.debug("ChatService initialized")
admin_svc = AdminService(db_service, ssh_service)
admin_svc = AdminService(db_service, ssh_service, dash_db=dash_db_service)
logging.debug("AdminService initialized")
updater_svc = UpdateService(base_dir)
logging.debug("UpdateService initialized")
@@ -242,6 +255,7 @@ def create_app(settings_path=None):
services = {
'db': db_service,
'dash_db': dash_db_service,
'ssh': ssh_service,
'k8s': k8s_service,
'player': player_svc,
+37 -1
View File
@@ -922,7 +922,8 @@ def register_api_routes(app, services, settings):
if map_name:
kv = director_svc.extract_server_config_kv(config)
if kv:
director_svc.update_ini_section(map_name, kv)
if not director_svc.update_ini_section(map_name, kv):
logger.warning("ConfigMap update failed for map %s (director API call succeeded)", map_name)
return result, 200, {'Content-Type': 'application/json'}
except Exception as e:
@@ -992,6 +993,41 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/server_set_scale/<map_name>')
@auth_req
def director_server_set_scale_get(map_name):
try:
if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 503
scale = director_svc.get_server_set_scale(map_name)
if scale is None:
return jsonify({'replicas': 0, 'partitions': []})
spec = scale.get('spec', {})
return jsonify({
'replicas': spec.get('replicas', 0),
'partitions': [p for p in spec.get('partitions', []) if p is not None],
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/server_set_scale/<map_name>', methods=['POST'])
@auth_req
def director_server_set_scale_patch(map_name):
try:
if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 503
config = request.get_json()
replicas = int(config.get('replicas', 1))
partitions_raw = config.get('partitions', [])
partitions = [int(p) for p in partitions_raw if p is not None]
if replicas > len(partitions):
return jsonify({'success': False, 'error': 'replicas cannot exceed partition count'}), 400
if not director_svc.patch_server_set_scale(map_name, replicas, partitions):
return jsonify({'success': False, 'error': 'Failed to patch ServerSetScale'}), 500
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
# Update management
@app.route('/api/update/status')
@auth_req
+30 -2
View File
@@ -426,7 +426,7 @@ def register_routes(app, services, settings):
def server_status():
logger.debug(f"Page access: /server by user={current_user.id}")
try:
active_servers = db.query("""
active_servers_raw = db.query("""
SELECT server_id, map
FROM dune.world_partition
WHERE server_id IS NOT NULL
@@ -448,6 +448,34 @@ def register_routes(app, services, settings):
deployments = k8s.get_deployments()
node_metrics = k8s.get_node_metrics()
active_servers = []
for s in active_servers_raw:
sid = (s.get('server_id') or '').lower().replace('_', '-')
s['deployment'] = ''
mp = (s.get('map') or '').lower().replace('_', '-')
for d in deployments:
short = d.replace('deployment.apps/', '')
if sid and sid in short.lower():
s['deployment'] = d
break
if mp and mp in short.lower():
s['deployment'] = d
break
if not s['deployment']:
mid = '-sg-' + sid
for d in deployments:
short = d.replace('deployment.apps/', '')
if mid in short.lower():
s['deployment'] = d
break
if not s['deployment'] and mp:
for d in deployments:
short = d.replace('deployment.apps/', '')
if mp in short.lower() and 'pod' in short.lower():
s['deployment'] = d
break
active_servers.append(s)
for p in partitions:
sid = (p.get('server_id') or '').lower().replace('_', '-')
p['deployment'] = ''
@@ -482,7 +510,7 @@ def register_routes(app, services, settings):
online_players=online_players, partitions=partitions,
overmap_count=overmap_count.get('c') if overmap_count else 0,
online_count=online_count.get('c') if online_count else 0,
deployments=deployments, deploys_ok=True, ssh_error='',
deployments=deployments, deploys_ok=len(deployments) > 0, ssh_error='',
node_metrics=node_metrics)
except Exception as e:
logger.exception("Error in server_status route")
+66 -81
View File
@@ -26,9 +26,10 @@ def _validate_ip(ip):
class AdminService:
_iptables_lock = threading.Lock()
def __init__(self, db_service, ssh_service):
def __init__(self, db_service, ssh_service, dash_db=None):
self.db = db_service
self.ssh = ssh_service
self.dash_db = dash_db or db_service
def ban_player(self, player_id, duration=0, reason='', note=''):
try:
@@ -44,17 +45,11 @@ class AdminService:
account_id = player_row.get('account_id') if player_row else None
player_name = player_row.get('character_name', 'Unknown') if player_row else 'Unknown'
conn = self.db.get_connection()
if not conn:
return False, "Database connection failed"
cur = None
try:
cur = conn.cursor()
if account_id:
if duration_int == 0:
cur.execute("""
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
@@ -62,8 +57,8 @@ class AdminService:
banned_at = NOW(), expires_at = NULL, active = TRUE
""", [player_id, account_id, reason, note, duration_int])
else:
cur.execute("""
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
@@ -72,8 +67,8 @@ class AdminService:
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
else:
if duration_int == 0:
cur.execute("""
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
reason = EXCLUDED.reason, note = EXCLUDED.note,
@@ -81,8 +76,8 @@ class AdminService:
expires_at = NULL, active = TRUE
""", [player_id, reason, note, duration_int])
else:
cur.execute("""
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
reason = EXCLUDED.reason, note = EXCLUDED.note,
@@ -90,47 +85,47 @@ class AdminService:
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
""", [player_id, reason, note, duration_int, duration_int, duration_int])
conn.commit()
audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}")
return True, f"Player {player_name} banned for {duration_int} minutes"
except Exception as e:
logger.error(f"Failed to ban player {player_id}: {e}")
if conn:
conn.rollback()
return False, str(e)
finally:
if cur:
cur.close()
self.db.return_connection(conn)
def unban_player(self, player_id):
conn = self.db.get_connection()
if not conn:
return False, "Database connection failed"
cur = None
try:
cur = conn.cursor()
cur.execute("DELETE FROM dashboard.bans WHERE player_id = %s", [player_id])
conn.commit()
# Delete from dashboard bans
self.dash_db.execute("DELETE FROM bans WHERE player_id = %s", [player_id])
cur.execute("SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s", [player_id])
account_row = cur.fetchone()
account_id = account_row[0] if account_row and isinstance(account_row, (tuple, list)) else (account_row.get('account_id') if account_row else None)
# Look up account info from game database
account_row = self.db.query(
"SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s",
[player_id], one=True
)
account_id = account_row.get('account_id') if account_row else None
ips_to_unblock = []
if account_id:
all_ips = self.db.query("""
SELECT ip_address FROM dashboard.player_ips
WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s)
""", [account_id]) or []
ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')]
game_account_players = self.db.query(
"SELECT player_controller_id FROM dune.player_state WHERE account_id = %s",
[account_id]
) or []
account_player_ids = [r['player_controller_id'] for r in game_account_players]
if account_player_ids:
placeholders = ','.join(['%s'] * len(account_player_ids))
ips_rows = self.dash_db.query(
f"SELECT ip_address FROM player_ips WHERE player_id IN ({placeholders})",
account_player_ids
) or []
ips_to_unblock = [r.get('ip_address') for r in ips_rows if r.get('ip_address')]
else:
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
if ip_row and ip_row.get('ip_address'):
ips_to_unblock.append(ip_row.get('ip_address'))
cur.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id])
conn.commit()
self.dash_db.execute(
"INSERT INTO player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)",
[player_id]
)
with self._iptables_lock:
for ip in ips_to_unblock:
@@ -144,13 +139,7 @@ class AdminService:
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
except Exception as e:
logger.error(f"Failed to unban player {player_id}: {e}")
if conn:
conn.rollback()
return False, str(e)
finally:
if cur:
cur.close()
self.db.return_connection(conn)
def kick_player(self, player_id):
player = self.db.query("""
@@ -163,7 +152,7 @@ class AdminService:
return False, "Player not found"
player_name = player.get('character_name', 'Unknown')
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
player_ip = ip_row.get('ip_address') if ip_row else None
if not player_ip:
@@ -184,7 +173,7 @@ class AdminService:
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
thread.start()
self.db.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
self.dash_db.execute("INSERT INTO player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}")
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
@@ -262,14 +251,8 @@ class AdminService:
if not game_pods:
return False, "No game server pods found"
conn = self.db.get_connection()
if not conn:
return False, "Database connection failed"
cur = None
updated = 0
try:
cur = conn.cursor()
for pod_name, map_name in game_pods:
cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- find /home/dune -name "*.log" -path "*/Logs/*" 2>/dev/null | head -5'
out_logs, err_logs, rc_logs = self.ssh.run(cmd)
@@ -302,26 +285,25 @@ class AdminService:
if ip_to_player:
for ip, name in ip_to_player.items():
cur.execute("""
player_row = self.db.query("""
SELECT ps.player_controller_id, ps.account_id
FROM dune.player_state ps
JOIN dune.accounts a ON ps.account_id = a.id
WHERE a.funcom_id = %s OR ps.character_name = %s
LIMIT 1
""", [name, name])
row = cur.fetchone()
if row:
pid = row[0] if isinstance(row, (tuple, list)) else row.get('funcom_id')
account_id = row[1] if isinstance(row, (tuple, list)) else row.get('account_id')
cur.execute("""
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
""", [name, name], one=True)
if player_row:
pid = player_row.get('player_controller_id')
account_id = player_row.get('account_id')
self.dash_db.execute("""
INSERT INTO player_ips (player_id, ip_address, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
""", [pid, ip])
updated += 1
ban_check = self.db.query("""
SELECT player_id FROM dashboard.bans
ban_check = self.dash_db.query("""
SELECT player_id FROM bans
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
LIMIT 1
""", [pid, account_id], one=True)
@@ -334,21 +316,14 @@ class AdminService:
else:
logger.warning(f"Skipping invalid IP for ban block: {ip}")
conn.commit()
return True, f"Updated {updated} player IPs from game logs"
except Exception as e:
logger.error(f"Failed to detect player IPs: {e}")
if conn:
conn.rollback()
return False, str(e)
finally:
if cur:
cur.close()
self.db.return_connection(conn)
def set_player_ip(self, player_id, ip_address):
return self.db.execute("""
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
return self.dash_db.execute("""
INSERT INTO player_ips (player_id, ip_address, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
""", [player_id, ip_address])
@@ -363,21 +338,31 @@ class AdminService:
return True, f"Unblocked {ip}"
def get_bans(self, limit=50):
return self.db.query("""
SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name
FROM dashboard.bans b
LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id
ORDER BY b.banned_at DESC
bans = self.dash_db.query("""
SELECT id, player_id, reason, active, banned_at, expires_at
FROM bans
ORDER BY banned_at DESC
LIMIT %s
""", [limit]) or []
for ban in bans:
pid = ban.get('player_id')
if pid:
player = self.db.query(
"SELECT character_name FROM dune.player_state WHERE player_controller_id = %s",
[pid], one=True
)
ban['character_name'] = player.get('character_name', '') if player else ''
else:
ban['character_name'] = ''
return bans
def get_player_ban(self, player_id):
return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dashboard.bans WHERE player_id = %s", [player_id], one=True)
return self.dash_db.query("SELECT reason, note, duration, banned_at, expires_at FROM bans WHERE player_id = %s", [player_id], one=True)
def get_player_history(self, player_id, limit=20):
return self.db.query("""
return self.dash_db.query("""
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
FROM dashboard.player_actions
FROM player_actions
WHERE player_id = %s
ORDER BY created_at DESC
LIMIT %s
+6 -6
View File
@@ -9,7 +9,7 @@ logger = logging.getLogger(__name__)
class ChatService:
def __init__(self, db_service, k8s_service, ssh_service, cache):
self.db = db_service
self.db = db_service # DashboardDatabaseService
self.k8s = k8s_service
self.ssh = ssh_service
self.cache = cache
@@ -20,7 +20,7 @@ class ChatService:
return True
try:
self.db.execute("""
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
CREATE TABLE IF NOT EXISTS chat_history (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP DEFAULT NOW(),
channel VARCHAR(50),
@@ -33,7 +33,7 @@ class ChatService:
is_admin BOOLEAN DEFAULT FALSE
)
""")
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)")
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC)")
self.ensured_table = True
logger.info("Chat history table ready")
return True
@@ -46,7 +46,7 @@ class ChatService:
loc_y = location.get('Y', 0) if location else 0
loc_z = location.get('Z', 0) if location else 0
return self.db.execute("""
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""", [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin])
@@ -61,7 +61,7 @@ class ChatService:
cur = conn.cursor()
for msg in messages:
cur.execute("""
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""", [
msg['channel'], msg['sender'], msg['message'],
@@ -87,7 +87,7 @@ class ChatService:
return self.db.query("""
SELECT id, timestamp, channel, sender, message, target,
location_x, location_y, location_z, is_admin
FROM dashboard.chat_history
FROM chat_history
ORDER BY timestamp DESC
LIMIT %s
""", [limit])
+248 -12
View File
@@ -10,11 +10,10 @@ logger = logging.getLogger(__name__)
class DatabaseService:
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema='dashboard'):
def __init__(self, db_config, min_conn=2, max_conn=10):
self.db_config = db_config
self.min_conn = min_conn
self.max_conn = max_conn
self.dashboard_schema = dashboard_schema
self.pool = None
def init_pool(self):
@@ -138,23 +137,186 @@ class DatabaseService:
return False
def ensure_tables(self):
"""No-op: dashboard tables now live in a separate database."""
pass
class DashboardDatabaseService:
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
def __init__(self, db_config, min_conn=2, max_conn=10, owner='dune'):
self.db_config = db_config
self.min_conn = min_conn
self.max_conn = max_conn
self.owner = owner
self.pool = None
self._migrated = False
def init_pool(self):
if self.pool is not None:
return self.pool
for attempt in range(10):
try:
self.pool = psycopg2.pool.ThreadedConnectionPool(
minconn=self.min_conn,
maxconn=self.max_conn,
**self.db_config
)
logger.info("Dashboard database pool initialized")
return self.pool
except psycopg2.OperationalError as e:
if 'does not exist' in str(e) and attempt == 0:
logger.info("Dashboard database does not exist, creating...")
self._ensure_database()
continue
if attempt < 9:
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
self.pool = None
except Exception as e:
if attempt < 9:
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
self.pool = None
return self.pool
def _ensure_database(self):
try:
admin_config = dict(self.db_config)
admin_config['database'] = 'postgres'
conn = psycopg2.connect(**admin_config)
conn.autocommit = True
cur = conn.cursor()
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", [self.db_config['database']])
if not cur.fetchone():
cur.execute(f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}")
logger.info("Created dashboard database '%s'", self.db_config['database'])
cur.close()
conn.close()
except Exception as e:
logger.error("Failed to create dashboard database: %s", e)
raise
def _migrate_old_schema(self, game_db):
if self._migrated:
return
tables = ['settings', 'bans', 'player_ips', 'player_actions', 'audit_log', 'chat_history']
migrated = False
for table in tables:
try:
rows = game_db.query(f"SELECT count(*) as cnt FROM dashboard.{table}", one=True)
if rows and rows.get('cnt', 0) > 0:
logger.info("Migrating %d rows from dashboard.%s", rows['cnt'], table)
old_rows = game_db.query(f"SELECT * FROM dashboard.{table}")
if old_rows:
cols = list(old_rows[0].keys())
placeholders = ','.join(['%s'] * len(cols))
col_names = ','.join(cols)
for row in old_rows:
vals = [row[c] for c in cols]
self.execute(
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
vals,
)
migrated = True
logger.info("Migrated dashboard.%s -> %s (%d rows)", table, table, rows['cnt'])
except Exception as e:
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
if migrated:
logger.info("Data migration from old dashboard schema complete")
self._migrated = True
def get_connection(self):
try:
pool = self.init_pool()
if pool:
return pool.getconn()
return psycopg2.connect(**self.db_config)
except Exception as e:
logger.error("Failed to get dashboard connection: %s", e)
return None
def return_connection(self, conn):
if conn and self.pool and hasattr(conn, 'poll'):
try:
self.pool.putconn(conn)
except Exception:
try:
conn.close()
except Exception:
pass
def close_all(self):
if self.pool:
try:
self.pool.closeall()
except Exception as e:
logger.error("Error closing dashboard pool: %s", e)
self.pool = None
def query(self, sql, params=None, one=False):
conn = self.get_connection()
if not conn:
return {} if one else []
cur = None
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute(sql, params)
rows = cur.fetchall()
if one and rows:
return rows[0]
if one:
return {}
return rows
except Exception as e:
logger.error("Dashboard query error: %s", e)
raise
finally:
if cur:
cur.close()
self.return_connection(conn)
def execute(self, sql, params=None, commit=True):
conn = self.get_connection()
if not conn:
return False
cur = None
try:
cur = conn.cursor()
cur.execute(sql, params)
if commit:
conn.commit()
return True
except Exception as e:
logger.error("Dashboard execute error: %s", e)
if conn:
conn.rollback()
return False
finally:
if cur:
cur.close()
self.return_connection(conn)
def ensure_tables(self, game_db=None):
conn = self.get_connection()
if not conn:
return
cur = None
schema = self.dashboard_schema
try:
cur = conn.cursor()
cur.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
cur.execute(f"""
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
cur.execute("""
CREATE TABLE IF NOT EXISTS player_ips (
player_id BIGINT PRIMARY KEY,
ip_address INET NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
)
""")
cur.execute(f"""
CREATE TABLE IF NOT EXISTS {schema}.bans (
cur.execute("""
CREATE TABLE IF NOT EXISTS bans (
id SERIAL PRIMARY KEY,
player_id BIGINT UNIQUE,
account_id BIGINT,
@@ -166,8 +328,8 @@ class DatabaseService:
active BOOLEAN DEFAULT TRUE
)
""")
cur.execute(f"""
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
cur.execute("""
CREATE TABLE IF NOT EXISTS player_actions (
id SERIAL PRIMARY KEY,
player_id BIGINT NOT NULL,
action_type VARCHAR(50) NOT NULL,
@@ -178,13 +340,87 @@ class DatabaseService:
created_at TIMESTAMP NOT NULL DEFAULT NOW()
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS audit_log (
id BIGSERIAL PRIMARY KEY,
action_type VARCHAR(50) NOT NULL,
user_name VARCHAR(100) NOT NULL,
target_player_id BIGINT,
details JSONB DEFAULT '{}',
source_ip INET,
severity VARCHAR(20) DEFAULT 'info',
created_at TIMESTAMP NOT NULL DEFAULT NOW()
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS chat_history (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP DEFAULT NOW(),
channel VARCHAR(50),
sender VARCHAR(255),
message TEXT,
target VARCHAR(255),
location_x FLOAT,
location_y FLOAT,
location_z FLOAT,
is_admin BOOLEAN DEFAULT FALSE
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS settings (
key VARCHAR(255) PRIMARY KEY,
value TEXT DEFAULT '',
updated_at TIMESTAMP DEFAULT NOW()
)
""")
owner = self.owner
cur.execute(f"""
DO $$DECLARE r RECORD;
BEGIN
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
LOOP
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
END LOOP;
END$$;
""")
cur.execute(f"""
DO $$DECLARE r RECORD;
BEGIN
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
LOOP
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
END LOOP;
END$$;
""")
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
conn.commit()
logger.info(f"Dashboard tables ensured in schema '{schema}' (player_ips, bans, player_actions)")
logger.info("Legacy dashboard tables ensured, owner=%s", owner)
except Exception as e:
logger.warning(f"Failed to ensure dashboard tables: {e}")
logger.warning("Failed to ensure legacy dashboard tables: %s", e)
if conn:
conn.rollback()
finally:
if cur:
cur.close()
self.return_connection(conn)
if game_db is not None:
self._migrate_old_schema(game_db)
def check_health(self):
try:
conn = self.get_connection()
if not conn:
return False
cur = conn.cursor()
cur.execute('SELECT 1')
cur.fetchone()
cur.close()
self.return_connection(conn)
return True
except Exception as e:
logger.warning("Dashboard health check FAILED: %s", e)
return False
+42 -2
View File
@@ -27,7 +27,13 @@ class DirectorService:
self.k8s = k8s_service
self.ssh = ssh_service
self.namespace = namespace
self.cm_name = f"{namespace}-bgd-conf-cm"
resource_prefix = namespace
for prefix in ['funcom-seabass-']:
if resource_prefix.startswith(prefix):
resource_prefix = resource_prefix[len(prefix):]
break
self.resource_prefix = resource_prefix
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
def _request(self, path: str, method: str = 'GET', data: Any = None,
timeout: int = 15, raw_data: bool = False) -> str:
@@ -141,8 +147,9 @@ class DirectorService:
Returns:
True if the update succeeded, False otherwise.
"""
cm_out, _, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
cm_out, cm_err, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
if cm_rc != 0 or not cm_out:
logger.warning("update_ini_section: could not get ConfigMap %s: %s", self.cm_name, cm_err)
return False
cm = json.loads(cm_out)
@@ -165,6 +172,39 @@ class DirectorService:
cfg.write(buf)
return self.patch_configmap(buf.getvalue())
# ── ServerSetScale management ────────────────────────────────────
def _map_to_scale_name(self, map_name: str) -> str:
safe = map_name.lower().replace('_', '-')
return f"{self.resource_prefix}-{safe}"
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
name = self._map_to_scale_name(map_name)
cm_out, cm_err, cm_rc = self.k8s.run(
f'get serversetscale {name} -o json')
if cm_rc != 0 or not cm_out:
return None
return json.loads(cm_out)
def patch_server_set_scale(self, map_name: str, replicas: int,
partitions: list) -> bool:
name = self._map_to_scale_name(map_name)
patch = json.dumps({
'spec': {
'partitions': partitions,
'replicas': replicas,
}
})
patch_b64 = base64.b64encode(patch.encode()).decode()
cmd = (f'echo {patch_b64} | base64 -d | '
f'sudo kubectl patch serversetscale {name} -n {self.namespace} '
f'--type merge --patch-file /dev/stdin')
out, err, rc = self.ssh.run(cmd, timeout=15)
if rc != 0:
logger.warning("ServerSetScale patch failed for %s: %s", map_name, err)
return False
return True
# ── Helper: extract config values for INI update ─────────────────
@staticmethod
+19 -4
View File
@@ -41,8 +41,9 @@ def _build_player_filters(search='', faction_id='', guild_id='', map_filter='',
class PlayerService:
def __init__(self, db_service):
def __init__(self, db_service, dash_db=None):
self.db = db_service
self.dash_db = dash_db
def is_online(self, player_controller_id):
result = self.db.query(
@@ -131,8 +132,7 @@ class PlayerService:
ea.id as account_id, ea.user as account_email,
acc.funcom_id,
ps.player_controller_id,
f.name as faction_name, g.guild_name,
pi.ip_address
f.name as faction_name, g.guild_name
FROM dune.actors a
JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id
LEFT JOIN dune.accounts acc ON ea.id = acc.id
@@ -141,7 +141,6 @@ class PlayerService:
LEFT JOIN dune.factions f ON pf.faction_id = f.id
LEFT JOIN dune.guild_members gm ON ps.player_controller_id = gm.player_id
LEFT JOIN dune.guilds g ON gm.guild_id = g.guild_id
LEFT JOIN dashboard.player_ips pi ON ps.player_controller_id = pi.player_id
WHERE {where_clause}
ORDER BY player_name
LIMIT %s OFFSET %s
@@ -151,6 +150,22 @@ class PlayerService:
return []
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
# Fetch IPs from the dashboard database separately and merge
ip_map = {}
if self.dash_db and player_ids:
placeholders = ','.join(['%s'] * len(player_ids))
ip_rows = self.dash_db.query(
f"SELECT player_id, ip_address FROM player_ips WHERE player_id IN ({placeholders})",
player_ids
) or []
ip_map = {r['player_id']: r['ip_address'] for r in ip_rows if r.get('player_id')}
for p in players:
pid = p.get('player_controller_id')
if pid and pid in ip_map:
p['ip_address'] = ip_map[pid]
else:
p['ip_address'] = None
actor_ids = [p.get('id') for p in players if p.get('id')]
vehicle_counts = {}
+6 -1
View File
@@ -108,7 +108,12 @@ def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None,
])
# Build SAN entries
san_entries = [x509.DNSName(common_name)]
san_entries = []
# Add common_name as the appropriate SAN type
try:
san_entries.append(x509.IPAddress(ipaddress.ip_address(common_name)))
except ValueError:
san_entries.append(x509.DNSName(common_name))
if san_ips:
for ip in san_ips:
try:
+1
View File
@@ -39,6 +39,7 @@ DEFAULTS = {
"max_connections": 10,
"owner": "dune",
"dashboard_schema": "dashboard",
"dashboard_database_name": "dashboard",
},
"kubernetes": {
"namespace": "",
+20 -5
View File
@@ -24,7 +24,7 @@ from app.routes.debug import debug_bp
from app.routes.chat import chat_bp
from app.websocket.shell import register_websocket_handlers
from app.services.database import DatabaseService
from app.services.database import DatabaseService, DashboardDatabaseService
from app.services.ssh import SSHService
from app.services.k8s import K8sService
from app.services.bg_director import BgDirectorService
@@ -156,13 +156,27 @@ def create_app(settings_path=None):
"database": settings["database"]["name"],
}
dash_db_config = {
"host": settings["database"]["host"],
"port": settings["database"]["port"],
"user": settings["database"]["user"],
"password": settings["database"]["password"],
"database": settings["database"].get("dashboard_database_name", "dashboard"),
}
db_service = DatabaseService(
db_config,
min_conn=settings["database"]["min_connections"],
max_conn=settings["database"]["max_connections"],
dashboard_schema=settings["database"].get("dashboard_schema", "dashboard"),
)
db_service.ensure_tables()
dash_db_service = DashboardDatabaseService(
dash_db_config,
min_conn=settings["database"]["min_connections"],
max_conn=settings["database"]["max_connections"],
owner=settings["database"].get("owner", "dune"),
)
dash_db_service.ensure_tables(game_db=db_service)
ssh_service = SSHService(
host=settings["server"]["host"],
@@ -200,14 +214,15 @@ def create_app(settings_path=None):
world_svc = WorldService(db_service)
progression_svc = ProgressionService(db_service)
character_svc = CharacterService(db_service)
audit_svc = AuditService(db_service)
chat_svc = ChatService(db_service, k8s_service, ssh_service)
audit_svc = AuditService(dash_db_service)
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service)
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
realtime_svc.start()
_services = {
"db": db_service,
"dash_db": dash_db_service,
"ssh": ssh_service,
"k8s": k8s_service,
"bg_director": bg_director,
+18 -17
View File
@@ -875,8 +875,9 @@ def get_audit_stats():
@login_required
def get_settings():
from app.factory import get_services
settings = get_services()["db"].execute_readonly(
"SELECT key, value, updated_at FROM dashboard.settings ORDER BY key"
dash_db = get_services()["dash_db"]
settings = dash_db.execute_readonly(
"SELECT key, value, updated_at FROM settings ORDER BY key"
)
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
@@ -891,10 +892,10 @@ def update_settings():
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
).model_dump()), 400
from app.factory import get_services
db = get_services()["db"]
dash_db = get_services()["dash_db"]
for key, value in data.items():
db.execute_mutation(
"""INSERT INTO dashboard.settings (key, value, updated_at)
dash_db.execute_mutation(
"""INSERT INTO settings (key, value, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
[key, str(value)],
@@ -912,9 +913,9 @@ def ban_player(player_id):
reason = data.get("reason", "admin")
duration = data.get("duration_hours", 0)
from app.factory import get_services
db = get_services()["db"]
db.execute_mutation(
"""INSERT INTO dashboard.bans (player_id, reason, duration, banned_at, expires_at, active)
dash_db = get_services()["dash_db"]
dash_db.execute_mutation(
"""INSERT INTO bans (player_id, reason, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
[player_id, reason, duration, duration, duration],
@@ -927,9 +928,9 @@ def ban_player(player_id):
@login_required
def unban_player(player_id):
from app.factory import get_services
db = get_services()["db"]
db.execute_mutation(
"UPDATE dashboard.bans SET active = FALSE WHERE player_id = %s",
dash_db = get_services()["dash_db"]
dash_db.execute_mutation(
"UPDATE bans SET active = FALSE WHERE player_id = %s",
[player_id],
)
_audit("player_unban", {"player_id": player_id})
@@ -940,9 +941,9 @@ def unban_player(player_id):
@login_required
def get_player_ban(player_id):
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"SELECT * FROM dashboard.bans WHERE player_id = %s AND active = TRUE",
dash_db = get_services()["dash_db"]
rows = dash_db.execute_readonly(
"SELECT * FROM bans WHERE player_id = %s AND active = TRUE",
[player_id],
)
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
@@ -961,9 +962,9 @@ def kick_player(player_id):
@login_required
def get_player_history(player_id):
from app.factory import get_services
db = get_services()["db"]
logs = db.execute_readonly(
"""SELECT * FROM dashboard.audit_log
dash_db = get_services()["dash_db"]
logs = dash_db.execute_readonly(
"""SELECT * FROM audit_log
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
ORDER BY created_at DESC LIMIT 100""",
[player_id, player_id],
+2 -2
View File
@@ -3,13 +3,13 @@
import logging
from datetime import datetime
from app.services.database import DatabaseService
from app.services.database import DashboardDatabaseService
logger = logging.getLogger(__name__)
class AuditService:
def __init__(self, db: DatabaseService):
def __init__(self, db: DashboardDatabaseService):
self.db = db
def log(self, action: str, user: str, details: dict | None = None,
+2 -2
View File
@@ -4,13 +4,13 @@ import json
import logging
from datetime import datetime
from app.services.database import DatabaseService
from app.services.database import DashboardDatabaseService
logger = logging.getLogger(__name__)
class ChatService:
def __init__(self, db: DatabaseService, k8s_service, ssh_service):
def __init__(self, db: DashboardDatabaseService, k8s_service, ssh_service):
self.db = db
self.k8s = k8s_service
self.ssh = ssh_service
+215 -25
View File
@@ -2,7 +2,7 @@
import logging
import time
from typing import Any, List
from typing import Any, List, Optional
import psycopg
from psycopg.rows import dict_row
@@ -12,11 +12,12 @@ logger = logging.getLogger(__name__)
class DatabaseService:
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema="dashboard"):
"""Service for game database queries (dune schema functions/procedures)."""
def __init__(self, db_config, min_conn=2, max_conn=10):
self.db_config = db_config
self.min_conn = min_conn
self.max_conn = max_conn
self.dashboard_schema = dashboard_schema
self.pool = None
def init_pool(self):
@@ -80,7 +81,7 @@ class DatabaseService:
cur.execute(sql, args)
conn.commit()
def execute_readonly(self, sql: str, params: List[Any] | None = None) -> List[dict]:
def execute_readonly(self, sql: str, params: Optional[List[Any]] = None) -> List[dict]:
"""Execute a read-only SELECT query."""
pool = self.init_pool()
if not pool:
@@ -92,7 +93,7 @@ class DatabaseService:
rows = cur.fetchall()
return rows if rows else []
def execute_mutation(self, sql: str, params: List[Any] | None = None) -> int:
def execute_mutation(self, sql: str, params: Optional[List[Any]] = None) -> int:
"""Execute a direct mutation (UPDATE/INSERT/DELETE) with validation."""
pool = self.init_pool()
if not pool:
@@ -118,38 +119,164 @@ class DatabaseService:
logger.warning(f"Database health check FAILED: {e}")
return False
def ensure_tables(self):
"""Ensure dashboard schema tables exist."""
def close(self):
if self.pool:
try:
self.pool.close()
logger.info("Database pool closed")
except Exception as e:
logger.error(f"Error closing pool: {e}")
self.pool = None
class DashboardDatabaseService:
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
def __init__(self, db_config, min_conn=2, max_conn=10, owner="dune"):
self.db_config = db_config
self.min_conn = min_conn
self.max_conn = max_conn
self.owner = owner
self.pool = None
self._migrated = False
def _conninfo(self, dbname=None):
return (
f"host={self.db_config['host']} "
f"port={self.db_config['port']} "
f"dbname={dbname or self.db_config['database']} "
f"user={self.db_config['user']} "
f"password={self.db_config['password']}"
)
def _temp_connection(self, dbname="postgres"):
"""Get a temporary single connection (for database creation)."""
conn = psycopg.connect(self._conninfo(dbname))
conn.autocommit = True
return conn
def init_pool(self):
if self.pool is not None:
return self.pool
conninfo = self._conninfo()
for attempt in range(10):
try:
self.pool = ConnectionPool(
conninfo=conninfo,
min_size=self.min_conn,
max_size=self.max_conn,
open=False,
)
self.pool.open(wait=True, timeout=20)
logger.info("Dashboard database pool initialized")
return self.pool
except psycopg.errors.OperationalError as e:
if "does not exist" in str(e) and attempt == 0:
logger.info("Dashboard database does not exist, creating...")
self._ensure_database()
continue
if attempt < 9:
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
self.pool = None
except Exception as e:
if attempt < 9:
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
self.pool = None
return self.pool
def _ensure_database(self):
"""Create the dashboard database if it doesn't exist."""
try:
conn = self._temp_connection("postgres")
with conn.cursor() as cur:
cur.execute(
"SELECT 1 FROM pg_database WHERE datname = %s",
[self.db_config["database"]],
)
if not cur.fetchone():
cur.execute(
f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}"
)
logger.info("Created dashboard database '%s'", self.db_config["database"])
else:
logger.debug("Dashboard database already exists")
conn.close()
except Exception as e:
logger.error("Failed to create dashboard database: %s", e)
raise
def _migrate_old_schema(self, game_db):
"""Migrate data from old dashboard schema in the game database."""
if self._migrated:
return
tables = ["settings", "bans", "player_ips", "player_actions", "audit_log", "chat_history"]
migrated = False
for table in tables:
try:
rows = game_db.execute_readonly(
f"SELECT count(*) as cnt FROM dashboard.{table}"
)
if rows and rows[0]["cnt"] > 0:
logger.info("Migrating %d rows from dashboard.%s", rows[0]["cnt"], table)
old_rows = game_db.execute_readonly(f"SELECT * FROM dashboard.{table}")
if old_rows:
cols = list(old_rows[0].keys())
placeholders = ",".join([f"%s"] * len(cols))
col_names = ",".join(cols)
for row in old_rows:
vals = [row[c] for c in cols]
self.execute_mutation(
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
vals,
)
migrated = True
logger.info("Migrated dashboard.%s → %s (%d rows)", table, table, rows[0]["cnt"])
except Exception as e:
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
if migrated:
logger.info("Data migration from old dashboard schema complete")
self._migrated = True
def ensure_tables(self, game_db=None):
"""Ensure tables exist in the dashboard database and migrate if needed."""
pool = self.init_pool()
if not pool:
return
schema = self.dashboard_schema
ddl = f"""
CREATE SCHEMA IF NOT EXISTS {schema};
CREATE TABLE IF NOT EXISTS {schema}.audit_log (
ddl = """
CREATE TABLE IF NOT EXISTS audit_log (
id BIGSERIAL PRIMARY KEY,
action_type VARCHAR(50) NOT NULL,
user_name VARCHAR(100) NOT NULL,
target_player_id BIGINT,
details JSONB DEFAULT '{{}}',
details JSONB DEFAULT '{}',
source_ip INET,
severity VARCHAR(20) DEFAULT 'info',
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON {schema}.audit_log (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_action ON {schema}.audit_log (action_type);
CREATE INDEX IF NOT EXISTS idx_audit_user ON {schema}.audit_log (user_name);
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON audit_log (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_action ON audit_log (action_type);
CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log (user_name);
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
CREATE TABLE IF NOT EXISTS player_ips (
player_id BIGINT PRIMARY KEY,
ip_address INET NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS {schema}.bans (
CREATE TABLE IF NOT EXISTS bans (
id SERIAL PRIMARY KEY,
player_id BIGINT UNIQUE,
account_id BIGINT,
@@ -161,7 +288,7 @@ class DatabaseService:
active BOOLEAN DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
CREATE TABLE IF NOT EXISTS player_actions (
id SERIAL PRIMARY KEY,
player_id BIGINT NOT NULL,
action_type VARCHAR(50) NOT NULL,
@@ -172,7 +299,7 @@ class DatabaseService:
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS {schema}.chat_history (
CREATE TABLE IF NOT EXISTS chat_history (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP DEFAULT NOW(),
channel VARCHAR(50),
@@ -185,9 +312,9 @@ class DatabaseService:
is_admin BOOLEAN DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON {schema}.chat_history (timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC);
CREATE TABLE IF NOT EXISTS {schema}.settings (
CREATE TABLE IF NOT EXISTS settings (
key VARCHAR(255) PRIMARY KEY,
value TEXT DEFAULT '',
updated_at TIMESTAMP DEFAULT NOW()
@@ -197,14 +324,77 @@ class DatabaseService:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(ddl)
owner = self.owner
cur.execute(f"""
DO $$DECLARE r RECORD;
BEGIN
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
LOOP
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
END LOOP;
END$$;
""")
cur.execute(f"""
DO $$DECLARE r RECORD;
BEGIN
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
LOOP
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
END LOOP;
END$$;
""")
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
conn.commit()
logger.info(f"Dashboard tables ensured in schema '{schema}'")
logger.info("Dashboard tables ensured, owner=%s", owner)
if game_db is not None:
self._migrate_old_schema(game_db)
def execute_readonly(self, sql: str, params: Optional[List[Any]] = None) -> List[dict]:
pool = self.init_pool()
if not pool:
raise ConnectionError("Dashboard database pool not available")
with pool.connection() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(sql, params or [])
rows = cur.fetchall()
return rows if rows else []
def execute_mutation(self, sql: str, params: Optional[List[Any]] = None) -> int:
pool = self.init_pool()
if not pool:
raise ConnectionError("Dashboard database pool not available")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(sql, params or [])
conn.commit()
return cur.rowcount
def health_check(self) -> bool:
try:
pool = self.init_pool()
if not pool:
return False
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
return True
except Exception as e:
logger.warning("Dashboard database health check FAILED: %s", e)
return False
def close(self):
if self.pool:
try:
self.pool.close()
logger.info("Database pool closed")
logger.info("Dashboard database pool closed")
except Exception as e:
logger.error(f"Error closing pool: {e}")
logger.error("Error closing dashboard pool: %s", e)
self.pool = None
+233 -12
View File
@@ -302,10 +302,19 @@ function Show-Menu {
Write-Host " [7] Start New Dashboard (React + ChakraUI)" -ForegroundColor Green
Write-Host " Launch the modern React dashboard with ChakraUI and Recharts." -ForegroundColor DarkGray
Write-Host " Auto-installs dependencies. Frontend: http://localhost:5173" -ForegroundColor DarkGray
Write-Host " NOTE: Not complete. Do not report bugs. May not even work." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [8] Reset to Factory Defaults" -ForegroundColor Red
Write-Host " Wipe all data and start fresh. Removes settings, logs, certs, and cache." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [9] Repair Game Database" -ForegroundColor Yellow
Write-Host " Fixes dashboard schema ownership so game updates won't break." -ForegroundColor DarkGray
Write-Host " Run this if game servers fail to start after an update." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [10] Clean up Old Dashboard Schema" -ForegroundColor Red
Write-Host " Drops the old dashboard schema from the game database." -ForegroundColor DarkGray
Write-Host " Only run after confirming dashboard migrated successfully." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [Q] Quit" -ForegroundColor White
Write-Host ""
}
@@ -1526,6 +1535,9 @@ function Run-Setup {
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
$CertDir = Join-Path $ProjectRoot "ssl"
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
$LeConfigDir = Join-Path $ProjectRoot "certbot\config"
$LeWorkDir = Join-Path $ProjectRoot "certbot\work"
$LeLogsDir = Join-Path $ProjectRoot "certbot\logs"
$CaCertPath = Join-Path $CertDir "ca.pem"
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
$SslCertPath = Join-Path $CertDir "cert.pem"
@@ -1572,8 +1584,14 @@ function Run-Setup {
$certbotUseModule = ($certbotCmd.Source -eq "python")
New-Item -ItemType Directory -Path $LeConfigDir -Force | Out-Null
New-Item -ItemType Directory -Path $LeWorkDir -Force | Out-Null
New-Item -ItemType Directory -Path $LeLogsDir -Force | Out-Null
$certbotDirArgs = @("--config-dir", $LeConfigDir, "--work-dir", $LeWorkDir, "--logs-dir", $LeLogsDir)
if ($certbotUseModule) {
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos")
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos") + $certbotDirArgs
if ($LeEmail) {
$certbotArgs += "--email"
$certbotArgs += $LeEmail
@@ -1587,7 +1605,7 @@ function Run-Setup {
"-d", $DomainName,
"--non-interactive",
"--agree-tos"
)
) + $certbotDirArgs
if ($LeEmail) {
$certbotArgs += "--email"
$certbotArgs += $LeEmail
@@ -1600,13 +1618,9 @@ function Run-Setup {
if ($certbotResult.ExitCode -eq 0) {
$UseLetsEncrypt = $true
$LeCertPath = "C:\ProgramData\certbot\live\$DomainName\fullchain.pem"
$LeKeyPath = "C:\ProgramData\certbot\live\$DomainName\privkey.pem"
if (-not (Test-Path $LeCertPath)) {
$LeCertPath = "C:\Certbot\live\$DomainName\fullchain.pem"
$LeKeyPath = "C:\Certbot\live\$DomainName\privkey.pem"
}
$LeLiveDir = Join-Path $LeConfigDir "live\$DomainName"
$LeCertPath = Join-Path $LeLiveDir "fullchain.pem"
$LeKeyPath = Join-Path $LeLiveDir "privkey.pem"
if (Test-Path $LeCertPath) {
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
@@ -1645,8 +1659,11 @@ function Run-Setup {
}
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
$SanDnsArray = "['localhost'"
if ($DomainName) { $SanDnsArray += ", '" + $DomainName + "'" }
$SanDnsArray += "]"
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=['localhost'])"
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=$SanDnsArray)"
$SslCert = "'$SslCertPath'"
$SslKey = "'$SslKeyPath'"
@@ -1778,7 +1795,7 @@ function Run-Setup {
$certbotPath = "certbot"
}
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet"
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet --config-dir `"$LeConfigDir`" --work-dir `"$LeWorkDir`" --logs-dir `"$LeLogsDir`""
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
@@ -2872,6 +2889,208 @@ function Start-NewDashboard {
Write-Host ""
}
function Repair-GameDatabase {
Write-Host ""
Write-Host " Game Database Repair" -ForegroundColor Cyan
Write-Host " =====================" -ForegroundColor Cyan
Write-Host ""
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if (-not (Test-Path $settingsFile)) {
Write-Host "[ERROR] settings.yaml not found. Run setup first (option 2)." -ForegroundColor Red
return
}
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if (-not $settingsJson) {
Write-Host "[ERROR] Could not read settings.yaml." -ForegroundColor Red
return
}
$settings = $settingsJson | ConvertFrom-Json
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$Namespace = $settings.kubernetes.namespace
$SSHKey = $null
if ($settings.server.ssh_key -and $settings.server.ssh_key -ne 'null') {
$SSHKey = $settings.server.ssh_key
}
if (-not $SSHKey) {
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
}
if (-not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP') {
Write-Host "[ERROR] Server IP not configured in settings.yaml." -ForegroundColor Red
return
}
if (-not $Namespace) {
Write-Host "[ERROR] Kubernetes namespace not configured." -ForegroundColor Red
return
}
if (-not (Test-Path $SSHKey)) {
Write-Host "[ERROR] SSH key not found at: $SSHKey" -ForegroundColor Red
return
}
Write-Host " Server: $ServerHost" -ForegroundColor White
Write-Host " Namespace: $Namespace" -ForegroundColor White
Write-Host ""
$confirm = Read-Host " This will transfer dashboard schema ownership to the dune user. Continue? (y/N)"
if ($confirm -ne 'y' -and $confirm -ne 'Y') {
Write-Host " Cancelled." -ForegroundColor Yellow
return
}
Write-Host ""
# 1. Find the database pod
Write-Host "[1/4] Finding database pod..." -ForegroundColor Yellow
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
if (-not $dbPod) {
Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red
return
}
Write-Host " [OK] Database pod: $dbPod" -ForegroundColor Green
# 2. Run the ownership fix SQL
Write-Host "[2/4] Running ownership fix..." -ForegroundColor Yellow
# Build a temp .ps1 script where each line uses --% with values directly embedded.
# After --%, PowerShell passes everything literally to ssh.exe — no parsing issues.
$tmpFile = Join-Path $env:TEMP "dune_repair_$([System.IO.Path]::GetRandomFileName()).ps1"
$sshBase = "ssh --% -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -i `"$SSHKey`" `"$SSHUser@$ServerHost`""
$scriptLines = @(
"$sshBase `"printf 'ALTER SCHEMA dashboard OWNER TO dune;\n' > /tmp/repair.sql`""
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER TABLE dashboard.\x27 || quote_ident(r.tablename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER SEQUENCE dashboard.\x27 || quote_ident(r.sequencename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON TABLES TO dune;\n' >> /tmp/repair.sql`""
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON SEQUENCES TO dune;\n' >> /tmp/repair.sql`""
"$sshBase `"cat /tmp/repair.sql | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune`""
"$sshBase `"printf 'CREATE SCHEMA IF NOT EXISTS dashboard;\nGRANT ALL PRIVILEGES ON SCHEMA dashboard TO dune;\n' | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d template1`""
)
$scriptLines | Out-File -FilePath $tmpFile -Encoding ASCII
$sqlResult = powershell -NoProfile -File $tmpFile 2>&1
Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue
Write-Host " $sqlResult" -ForegroundColor DarkGray
Write-Host " [OK] Ownership fix applied" -ForegroundColor Green
# 3. Delete failed util pods
Write-Host "[3/4] Cleaning up failed utility pods..." -ForegroundColor Yellow
$deleted = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace | grep 'db.*util' | grep -v Running | awk '{print \$1}' | xargs -r sudo kubectl delete pod -n $Namespace --wait=false" 2>$null
if ($deleted) {
Write-Host " $deleted" -ForegroundColor DarkGray
Write-Host " [OK] Failed util pods deleted" -ForegroundColor Green
} else {
Write-Host " [OK] No failed util pods found" -ForegroundColor Green
}
# 4. Instructions
Write-Host "[4/4] Done!" -ForegroundColor Yellow
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Repair Complete!" -ForegroundColor Green
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " If game servers still show errors, restart the battlegroup:" -ForegroundColor White
Write-Host " 1. In the battlegroup management UI, select option 5" -ForegroundColor White
Write-Host " (Restart battlegroup)" -ForegroundColor DarkGray
Write-Host " 2. Wait for all pods to come back healthy" -ForegroundColor White
Write-Host ""
Write-Host " The dashboard will auto-fix ownership on every startup," -ForegroundColor Green
Write-Host " so this should not happen again." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return to the menu..." -ForegroundColor DarkGray
Read-Host
}
function Cleanup-OldDashboardSchema {
Write-Host ""
Write-Host " Clean Up Old Dashboard Schema" -ForegroundColor Cyan
Write-Host " ===============================" -ForegroundColor Cyan
Write-Host ""
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if ( -not (Test-Path $settingsFile) ) {
Write-Host "[ERROR] settings.yaml not found." -ForegroundColor Red
return
}
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if ( -not $settingsJson ) { Write-Host "[ERROR] Could not read settings." -ForegroundColor Red; return }
$settings = $settingsJson | ConvertFrom-Json
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$Namespace = $settings.kubernetes.namespace
$SSHKey = $settings.server.ssh_key
if ( -not $SSHKey -or $SSHKey -eq 'null' ) {
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
}
if ( -not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP' ) { Write-Host "[ERROR] Server IP not configured." -ForegroundColor Red; return }
if ( -not $Namespace ) { Write-Host "[ERROR] Namespace not configured." -ForegroundColor Red; return }
if ( -not (Test-Path $SSHKey) ) { Write-Host "[ERROR] SSH key not found." -ForegroundColor Red; return }
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
if ( -not $dbPod ) { Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red; return }
$hasOldSchema = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -t -c ""SELECT count(*) FROM information_schema.schemata WHERE schema_name = 'dashboard'"" 2>&1" 2>$null
$hasOldSchema = $hasOldSchema.Trim()
if ( $hasOldSchema -eq '0' ) {
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
if ( -not $hasOldSchema ) {
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
Write-Host " [WARN] Old dashboard schema found in the game database." -ForegroundColor Yellow
Write-Host ""
Write-Host " This drops: dashboard.audit_log, dashboard.bans, dashboard.player_ips," -ForegroundColor White
Write-Host " dashboard.player_actions, dashboard.chat_history, dashboard.settings" -ForegroundColor White
Write-Host ""
Write-Host " Make sure the dashboard has migrated this data to the new database first." -ForegroundColor Yellow
Write-Host " (The dashboard does this automatically on next startup.)" -ForegroundColor DarkGray
Write-Host ""
$confirm = Read-Host " Type 'yes' to drop the old dashboard schema"
if ($confirm -ne 'yes') {
Write-Host " Cancelled." -ForegroundColor Yellow
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
$confirm2 = Read-Host " REALLY drop? This cannot be undone. Type 'yes' again"
if ($confirm2 -ne 'yes') {
Write-Host " Cancelled." -ForegroundColor Yellow
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
Write-Host ""
Write-Host " Dropping old dashboard schema..." -ForegroundColor Yellow
$result = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -c ""DROP SCHEMA IF EXISTS dashboard CASCADE"" 2>&1"
Write-Host " $result" -ForegroundColor DarkGray
Write-Host " [OK] Old dashboard schema dropped." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
}
# ── Main Loop ───────────────────────────────────────────────────────────
Show-Banner
@@ -2889,9 +3108,11 @@ while ($true) {
"6" { Start-DashboardDebug; break }
"7" { Start-NewDashboard; break }
"8" { Reset-ToFactoryDefaults; break }
"9" { Repair-GameDatabase; break }
"10" { Cleanup-OldDashboardSchema; break }
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-8, or Q." -ForegroundColor Yellow; Write-Host "" }
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-10, or Q." -ForegroundColor Yellow; Write-Host "" }
}
Write-Host ""
+1
View File
@@ -38,6 +38,7 @@ database:
min_connections: 2
max_connections: 10
dashboard_schema: "dashboard" # Schema for dashboard's own tables (isolated from game DB for backup compatibility)
dashboard_database_name: "dashboard" # Dedicated database for dashboard tables (auto-created on startup)
# Kubernetes
kubernetes:
+110 -19
View File
@@ -185,6 +185,7 @@
<script>
let bgData = null;
let charTransferData = null;
let scaleData = {};
async function loadDirector() {
const banner = document.getElementById('loading-banner');
@@ -214,6 +215,7 @@ async function loadDirector() {
if (ctResp.ok) {
charTransferData = await ctResp.json();
}
await loadScaleData(bgData);
if (document.getElementById('maps-container').children.length === 0) {
renderStats();
renderMaps();
@@ -238,6 +240,21 @@ document.getElementById('btn-retry-director')?.addEventListener('click', () => {
loadDirector();
});
async function loadScaleData(bg) {
const maps = [];
const addMaps = (obj) => { if (obj) Object.keys(obj).forEach(k => maps.push(k)); };
addMaps(bg.dimensionMaps);
addMaps(bg.instancedMaps);
addMaps(bg.singleServerMaps);
const results = await Promise.allSettled(
maps.map(m => fetch(`/api/director/server_set_scale/${encodeURIComponent(m)}`).then(r => r.json()))
);
maps.forEach((m, i) => {
const r = results[i];
scaleData[m] = (r.status === 'fulfilled') ? r.value : { replicas: 0, partitions: [] };
});
}
function updateStats() {
const t = calcTotals();
document.getElementById('stat-players').textContent = t.total;
@@ -301,6 +318,13 @@ function updateMapCards() {
const nameSpan = summaryParts[i].querySelector('.name');
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
}
const repInput = document.getElementById(`cfg-${mapName}-replicas`);
if (repInput) {
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
repInput.value = sc.replicas;
repInput.max = sc.partitions.length || 1;
}
}
}
@@ -381,7 +405,7 @@ function renderMaps() {
}
function buildMapCard(mapName, mapData, type) {
const cfg = mapData.cfg || {};
const cfg = { ...(mapData.cfg || {}), ...(mapData.webOverrideCfg || {}) };
let serversHtml = '';
let configHtml = '';
let summaryHtml = '';
@@ -505,6 +529,7 @@ function buildDimensionConfig(mapName, cfg) {
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
const phCap = cfg.playerHardCap ?? '';
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
return `
<div class="config-row">
<div class="config-field">
@@ -527,6 +552,10 @@ function buildDimensionConfig(mapName, cfg) {
<label>Scale Throttle (s)</label>
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
</div>
<div class="config-field">
<label>Replicas</label>
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
</div>
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
</div>
@@ -539,6 +568,7 @@ function buildInstancedConfig(mapName, cfg) {
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
const phCap = cfg.playerHardCap ?? '';
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
return `
<div class="config-row">
<div class="config-field">
@@ -561,6 +591,10 @@ function buildInstancedConfig(mapName, cfg) {
<label>Scale Throttle (s)</label>
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
</div>
<div class="config-field">
<label>Replicas</label>
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
</div>
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
</div>
@@ -625,23 +659,45 @@ async function applyConfig(mapName, type, btn) {
}
try {
const resp = await fetch('/api/director/update_config', {
const resp = await csrfFetch('/api/director/update_config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
if (!resp.ok) {
let errMsg = `HTTP ${resp.status}`;
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
throw new Error(errMsg);
}
btn.classList.remove('applying');
btn.classList.add('applied');
btn.textContent = 'Applied!';
setTimeout(() => {
btn.classList.remove('applied');
btn.textContent = 'Apply';
btn.disabled = false;
}, 2000);
btn.disabled = false;
const replicasInput = document.getElementById(`cfg-${mapName}-replicas`);
if (replicasInput && type !== 'single') {
const sc = scaleData[mapName] || { partitions: [], replicas: 1 };
const newReplicas = parseInt(replicasInput.value) || 1;
if (newReplicas !== sc.replicas) {
const partInput = document.getElementById(`cfg-${mapName}-partitions`);
let partitions = sc.partitions;
if (partInput) {
try { partitions = JSON.parse('[' + partInput.value + ']'); } catch(_){}
}
csrfFetch(`/api/director/server_set_scale/${encodeURIComponent(mapName)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ replicas: newReplicas, partitions: partitions })
}).catch(() => {});
}
}
setTimeout(() => { btn.textContent = 'Apply'; btn.classList.remove('applied'); loadDirector(); }, 1200);
} catch (e) {
btn.classList.remove('applying');
btn.textContent = 'Failed';
const errDiv = document.getElementById('error-banner');
if (errDiv) { errDiv.textContent = 'Config apply error: ' + e.message; errDiv.style.display = 'block'; }
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
}
}
@@ -650,15 +706,23 @@ async function clearConfig(mapName, btn) {
btn.disabled = true;
btn.textContent = 'Clearing...';
try {
const resp = await fetch('/api/director/clear_config', {
const resp = await csrfFetch('/api/director/clear_config', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: mapName
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
if (!resp.ok) {
let errMsg = `HTTP ${resp.status}`;
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
throw new Error(errMsg);
}
btn.textContent = 'Cleared!';
setTimeout(() => { loadDirector(); }, 1500);
btn.disabled = false;
setTimeout(() => { btn.textContent = 'Clear'; loadDirector(); }, 1200);
} catch (e) {
btn.textContent = 'Failed';
const errDiv = document.getElementById('error-banner');
if (errDiv) { errDiv.textContent = 'Config clear error: ' + e.message; errDiv.style.display = 'block'; }
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
}
}
@@ -671,17 +735,24 @@ document.getElementById('btn-apply-world')?.addEventListener('click', async func
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
};
try {
const resp = await fetch('/api/director/character_transfer', {
const resp = await csrfFetch('/api/director/character_transfer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
if (!resp.ok) {
let errMsg = `HTTP ${resp.status}`;
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
throw new Error(errMsg);
}
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
this.textContent = 'Applied!';
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
this.disabled = false;
setTimeout(() => { this.textContent = 'Apply'; }, 2000);
} catch (e) {
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
const errDiv = document.getElementById('error-banner');
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
this.textContent = 'Apply'; this.disabled = false;
}
});
@@ -691,12 +762,19 @@ document.getElementById('btn-clear-world')?.addEventListener('click', async func
this.textContent = 'Clearing...';
try {
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
if (!resp.ok) {
let errMsg = `HTTP ${resp.status}`;
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
throw new Error(errMsg);
}
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
this.textContent = 'Cleared!';
setTimeout(() => { loadDirector(); }, 1500);
this.disabled = false;
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
} catch (e) {
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
const errDiv = document.getElementById('error-banner');
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
this.textContent = 'Clear'; this.disabled = false;
}
});
@@ -716,12 +794,18 @@ document.getElementById('btn-apply-transfer')?.addEventListener('click', async f
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
if (!resp.ok) {
let errMsg = `HTTP ${resp.status}`;
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
throw new Error(errMsg);
}
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
this.textContent = 'Applied!';
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
} catch (e) {
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
const errDiv = document.getElementById('error-banner');
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
this.textContent = 'Apply'; this.disabled = false;
}
});
@@ -731,12 +815,19 @@ document.getElementById('btn-clear-transfer')?.addEventListener('click', async f
this.textContent = 'Clearing...';
try {
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
if (!resp.ok) {
let errMsg = `HTTP ${resp.status}`;
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
throw new Error(errMsg);
}
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
this.textContent = 'Cleared!';
setTimeout(() => { loadDirector(); }, 1500);
this.disabled = false;
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
} catch (e) {
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
const errDiv = document.getElementById('error-banner');
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
this.textContent = 'Clear'; this.disabled = false;
}
});
+74 -21
View File
@@ -85,14 +85,28 @@
<div class="card-header">Active Server IDs</div>
<div class="card-body">
{% if active_servers %}
<ul style="list-style:none;">
{% for s in active_servers %}
<li style="padding:4px 0;font-family:monospace;font-size:12px;">
<span style="font-weight:600;">{{ s.server_id }}</span>
{% if s.map %} — <span style="color:var(--primary);">{{ s.map }}</span>{% endif %}
</li>
{% endfor %}
</ul>
<div class="table-wrap">
<table>
<thead><tr><th>Server ID</th><th>Map</th><th>Actions</th></tr></thead>
<tbody>
{% for s in active_servers %}
<tr>
<td style="font-family:monospace;font-size:12px;font-weight:600;">{{ s.server_id }}</td>
<td style="color:var(--primary);">{{ s.map or '' }}</td>
<td>
{% if s.deployment %}
<button class="partition-btn" data-deploy="{{ s.deployment }}" data-map="{{ s.server_id }}" title="Restart this server's deployment. Players on this map will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
{% elif not deployments %}
<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>
{% else %}
<span style="color:var(--text-muted);font-size:11px;">No deploy</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="empty">No active servers</div>
{% endif %}
@@ -116,7 +130,7 @@
<td>{{ p.dimension_index }}</td>
<td>{{ 'Yes' if p.blocked else 'No' }}</td>
<td>{{ p.label or '' }}</td>
<td>{% if p.deployment %}<button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>{% else %}&mdash;{% endif %}</td>
<td>{% if p.deployment %}<div style="display:flex;gap:4px;flex-wrap:wrap;"><button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Restart this partition's deployment. Players on this map will disconnect." style="padding:4px 10px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Restart</button><button class="partition-status-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Show rollout status for this partition's deployment." style="padding:4px 10px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Status</button></div>{% elif not deployments %}<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>{% else %}<span style="color:var(--text-muted);font-size:11px;">No deploy</span>{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="7" class="empty">No partitions found</td></tr>
@@ -137,6 +151,13 @@
</div>
<div class="card-body">
{% if deploys_ok %}
<div style="margin-bottom:10px;padding:10px;background:#1a1a2e;border-radius:6px;font-size:12px;line-height:1.5;color:#a0a0b0;">
<strong>Button Guide:</strong>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e67e22;">Restart</span> — rolling restart of pods</span>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#3498db;">Status</span> — rollout status</span>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e74c3c;">Scale to 0</span> — stop all pods</span>
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#27ae60;">Scale to 1</span> — start a pod</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Deployment</th><th>Actions</th></tr></thead>
@@ -145,10 +166,10 @@
<tr>
<td style="font-family:monospace;font-size:13px;">{{ d.replace('deployment.apps/','') }}</td>
<td>
<button class="btn-action" data-deploy="{{ d }}" data-action="restart" style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="status" style="padding:4px 12px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Status</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_0" style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 0</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="restart" title="Performs a rolling restart of this deployment's pods. Players will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="status" title="Show rollout status: whether the deployment is successfully rolled out, pending, or failed." style="padding:4px 12px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Status</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_0" title="Scale to 0 replicas. Stops all pods for this deployment. Use to shut down a server." style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 0</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" title="Scale to 1 replica. Starts a single pod. Use to bring a stopped server back online." style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
</td>
</tr>
{% endfor %}
@@ -339,7 +360,7 @@ document.querySelectorAll('.partition-btn').forEach(btn => {
if (!confirm(`Restart "${map}" partition (${deploy})?`)) return;
if (!confirm('Are you sure? Players on this map will be disconnected.')) return;
this.disabled = true;
this.textContent = 'Restarting...';
this.textContent = 'Working...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
@@ -359,10 +380,36 @@ document.querySelectorAll('.partition-btn').forEach(btn => {
});
});
document.getElementById('refresh-pods')?.addEventListener('click', async function() {
this.disabled = true;
this.textContent = 'Loading...';
document.querySelectorAll('.partition-status-btn').forEach(btn => {
btn.addEventListener('click', async function() {
const deploy = this.dataset.deploy;
const map = this.dataset.map;
const label = this.textContent.trim();
this.disabled = true;
this.textContent = 'Loading...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
outputText.textContent = `Fetching status for ${deploy}...`;
try {
const form = new FormData();
form.append('deployment', deploy);
form.append('action', 'status');
const resp = await csrfFetch('/server/action', { method: 'POST', body: form });
const data = await resp.json();
outputText.textContent = data.output || (data.success ? 'No status output' : 'Failed');
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = label;
});
});
async function refreshPods() {
const btn = document.getElementById('refresh-pods');
const pre = document.getElementById('pods-text');
if (btn) { btn.disabled = true; btn.textContent = 'Loading...'; }
pre.textContent = 'Fetching pod list...';
try {
const resp = await fetch('/server/pods');
@@ -371,9 +418,10 @@ document.getElementById('refresh-pods')?.addEventListener('click', async functio
} catch (e) {
pre.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = 'Refresh Pods';
});
if (btn) { btn.disabled = false; btn.textContent = 'Refresh Pods'; }
}
document.getElementById('refresh-pods')?.addEventListener('click', refreshPods);
async function bgAction(action, btn) {
const confirmMsgs = {
@@ -603,7 +651,8 @@ debugToggle.addEventListener('change', async function() {
try {
const resp = await csrfFetch('/api/settings/debug', {
method: 'POST',
body: { enabled: enabled }
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: enabled })
});
const data = await resp.json();
if (data.success) {
@@ -628,5 +677,9 @@ debugToggle.addEventListener('change', async function() {
// Load debug status on page load
loadDebugStatus();
// Auto-load battlegroup and pods once on page load, then require manual refresh
bgRefreshStatus();
refreshPods();
</script>
{% endblock %}