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
This commit is contained in:
Reditus committed 2026-05-27 01:02:39 +01:00
1 parent 15af849d2c
commit 0f173dc107
15 files changed
+837 -163

No files matched your search

+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