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': '',
+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,
+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
+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 = {}