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:
1 parent
15af849d2c
commit
0f173dc107
15 files changed
+837
-163
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user