Initial release - Dune Awakening Dashboard beta
This commit is contained in:
commit
59cc98133c
51 files changed
+8428
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Dune Awakening Server Dashboard - Application Package"""
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
"""Settings loader - reads settings.yaml with env var overrides"""
|
||||
|
||||
import os
|
||||
import yaml
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULTS = {
|
||||
'server': {
|
||||
'host': '127.0.0.1',
|
||||
'user': 'dune',
|
||||
'ssh_key': None,
|
||||
},
|
||||
'dashboard': {
|
||||
'host': '127.0.0.1',
|
||||
'port': 5050,
|
||||
'debug': False,
|
||||
'secret_key': 'change-me-to-random-string',
|
||||
},
|
||||
'database': {
|
||||
'host': '127.0.0.1',
|
||||
'port': 15433,
|
||||
'user': 'postgres',
|
||||
'password': 'postgres',
|
||||
'name': 'dune',
|
||||
'schema': 'dune',
|
||||
'min_connections': 2,
|
||||
'max_connections': 10,
|
||||
},
|
||||
'kubernetes': {
|
||||
'namespace': '',
|
||||
'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
|
||||
},
|
||||
'director': {
|
||||
'port': 32479,
|
||||
},
|
||||
'filebrowser': {
|
||||
'port': 18888,
|
||||
},
|
||||
'cache': {
|
||||
'chat_pod_ttl': 60,
|
||||
'chat_messages_ttl': 10,
|
||||
'static_data_ttl': 300,
|
||||
},
|
||||
'auth': {
|
||||
'enabled': True,
|
||||
'username': 'admin',
|
||||
'password': 'changeme',
|
||||
},
|
||||
'logging': {
|
||||
'level': 'INFO',
|
||||
'file': 'logs/dashboard.log',
|
||||
'max_bytes': 10485760,
|
||||
'backup_count': 5,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def deep_merge(base, override):
|
||||
"""Deep merge override dict into base dict."""
|
||||
result = base.copy()
|
||||
for key, value in override.items():
|
||||
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
||||
result[key] = deep_merge(result[key], value)
|
||||
else:
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def load_settings(settings_path=None):
|
||||
"""Load settings from YAML file with defaults and env var overrides."""
|
||||
if settings_path is None:
|
||||
settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yaml')
|
||||
|
||||
settings = DEFAULTS.copy()
|
||||
|
||||
if os.path.exists(settings_path):
|
||||
try:
|
||||
with open(settings_path, 'r') as f:
|
||||
file_settings = yaml.safe_load(f) or {}
|
||||
settings = deep_merge(settings, file_settings)
|
||||
logger.info(f"Settings loaded from {settings_path}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load settings from {settings_path}: {e}")
|
||||
logger.warning("Using default settings")
|
||||
else:
|
||||
logger.warning(f"Settings file not found at {settings_path}, using defaults")
|
||||
|
||||
env_overrides = {}
|
||||
|
||||
if os.environ.get('DUNE_SERVER_HOST'):
|
||||
env_overrides.setdefault('server', {})['host'] = os.environ['DUNE_SERVER_HOST']
|
||||
if os.environ.get('DUNE_SERVER_USER'):
|
||||
env_overrides.setdefault('server', {})['user'] = os.environ['DUNE_SERVER_USER']
|
||||
if os.environ.get('DUNE_DB_PASSWORD'):
|
||||
env_overrides.setdefault('database', {})['password'] = os.environ['DUNE_DB_PASSWORD']
|
||||
if os.environ.get('DUNE_K8S_NAMESPACE'):
|
||||
env_overrides.setdefault('kubernetes', {})['namespace'] = os.environ['DUNE_K8S_NAMESPACE']
|
||||
if os.environ.get('DUNE_AUTH_PASSWORD'):
|
||||
env_overrides.setdefault('auth', {})['password'] = os.environ['DUNE_AUTH_PASSWORD']
|
||||
if os.environ.get('DUNE_DASHBOARD_PORT'):
|
||||
env_overrides.setdefault('dashboard', {})['port'] = int(os.environ['DUNE_DASHBOARD_PORT'])
|
||||
|
||||
if env_overrides:
|
||||
settings = deep_merge(settings, env_overrides)
|
||||
logger.info("Environment variable overrides applied")
|
||||
|
||||
return settings
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
"""Application factory - creates and configures the Flask app"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
import logging.handlers
|
||||
from flask import Flask, request
|
||||
from flask_socketio import SocketIO
|
||||
from flask_talisman import Talisman
|
||||
|
||||
from app.config import load_settings
|
||||
from app.services.database import DatabaseService
|
||||
from app.services.ssh import SSHService
|
||||
from app.services.k8s import K8sService
|
||||
from app.services.player import PlayerService
|
||||
from app.services.vehicle import VehicleService
|
||||
from app.services.chat import ChatService
|
||||
from app.services.admin import AdminService
|
||||
from app.utils.cache import MultiCache
|
||||
from app.routes.main import register_routes
|
||||
from app.routes.api import register_api_routes
|
||||
from app.routes.auth import init_auth
|
||||
from app.websocket.shell import register_websocket_handlers
|
||||
|
||||
|
||||
def create_app(settings_path=None):
|
||||
settings = load_settings(settings_path)
|
||||
|
||||
base_dir = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
app = Flask(
|
||||
__name__,
|
||||
template_folder=os.path.join(base_dir, 'templates'),
|
||||
static_folder=os.path.join(base_dir, 'static'),
|
||||
static_url_path='/static'
|
||||
)
|
||||
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
|
||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
||||
|
||||
if not settings['dashboard']['debug']:
|
||||
Talisman(app, content_security_policy=None, force_https=False)
|
||||
|
||||
_setup_logging(settings)
|
||||
|
||||
db_config = {
|
||||
'host': settings['database']['host'],
|
||||
'port': settings['database']['port'],
|
||||
'user': settings['database']['user'],
|
||||
'password': settings['database']['password'],
|
||||
'database': settings['database']['name'],
|
||||
}
|
||||
|
||||
db_service = DatabaseService(
|
||||
db_config,
|
||||
min_conn=settings['database']['min_connections'],
|
||||
max_conn=settings['database']['max_connections']
|
||||
)
|
||||
db_service.ensure_tables()
|
||||
|
||||
ssh_service = SSHService(
|
||||
host=settings['server']['host'],
|
||||
user=settings['server']['user'],
|
||||
ssh_key=settings['server'].get('ssh_key')
|
||||
)
|
||||
|
||||
k8s_service = K8sService(
|
||||
ssh_service=ssh_service,
|
||||
namespace=settings['kubernetes']['namespace']
|
||||
)
|
||||
|
||||
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
||||
|
||||
player_svc = PlayerService(db_service)
|
||||
vehicle_svc = VehicleService(db_service)
|
||||
chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache)
|
||||
admin_svc = AdminService(db_service, ssh_service)
|
||||
|
||||
services = {
|
||||
'db': db_service,
|
||||
'ssh': ssh_service,
|
||||
'k8s': k8s_service,
|
||||
'player': player_svc,
|
||||
'vehicle': vehicle_svc,
|
||||
'chat': chat_svc,
|
||||
'admin': admin_svc,
|
||||
'static_cache': static_cache,
|
||||
}
|
||||
|
||||
socketio = SocketIO(app, cors_allowed_origins=[], async_mode='threading')
|
||||
|
||||
if settings['auth']['enabled']:
|
||||
init_auth(app, settings)
|
||||
|
||||
register_routes(app, services, settings)
|
||||
register_api_routes(app, services, settings)
|
||||
register_websocket_handlers(socketio, settings)
|
||||
|
||||
@app.teardown_appcontext
|
||||
def cleanup_db(exc):
|
||||
pass
|
||||
|
||||
if settings['kubernetes']['namespace'] == '':
|
||||
try:
|
||||
k8s_service.auto_detect_namespace()
|
||||
if k8s_service.namespace:
|
||||
settings['kubernetes']['namespace'] = k8s_service.namespace
|
||||
except Exception as e:
|
||||
logging.warning(f"Could not auto-detect K8s namespace: {e}")
|
||||
|
||||
app.dune_settings = settings
|
||||
app.dune_services = services
|
||||
|
||||
return app, socketio
|
||||
|
||||
|
||||
def _setup_logging(settings):
|
||||
log_level = getattr(logging, settings['logging']['level'].upper(), logging.INFO)
|
||||
log_file = settings['logging']['file']
|
||||
|
||||
os.makedirs(os.path.dirname(log_file), exist_ok=True)
|
||||
|
||||
handler = logging.handlers.RotatingFileHandler(
|
||||
log_file,
|
||||
maxBytes=settings['logging']['max_bytes'],
|
||||
backupCount=settings['logging']['backup_count']
|
||||
)
|
||||
handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
))
|
||||
handler.setLevel(log_level)
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s - %(levelname)s - %(message)s'
|
||||
))
|
||||
console_handler.setLevel(log_level)
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(log_level)
|
||||
root_logger.addHandler(handler)
|
||||
root_logger.addHandler(console_handler)
|
||||
|
||||
audit_logger = logging.getLogger('audit')
|
||||
audit_handler = logging.handlers.RotatingFileHandler(
|
||||
'logs/audit.log',
|
||||
maxBytes=settings['logging']['max_bytes'],
|
||||
backupCount=settings['logging']['backup_count']
|
||||
)
|
||||
audit_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s - %(message)s'
|
||||
))
|
||||
audit_logger.addHandler(audit_handler)
|
||||
audit_logger.setLevel(logging.INFO)
|
||||
@@ -0,0 +1 @@
|
||||
"""Routes package"""
|
||||
@@ -0,0 +1,700 @@
|
||||
"""API routes - server actions, player management, debug endpoints"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from flask import Blueprint, request, jsonify
|
||||
from app.utils.constants import NAV_PAGES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def register_api_routes(app, services, settings):
|
||||
db = services['db']
|
||||
ssh = services['ssh']
|
||||
k8s = services['k8s']
|
||||
chat_svc = services['chat']
|
||||
admin_svc = services['admin']
|
||||
vehicle_svc = services['vehicle']
|
||||
|
||||
# Server actions
|
||||
@app.route('/server/action', methods=['POST'])
|
||||
def server_action():
|
||||
deployment = request.form.get('deployment', '')
|
||||
action = request.form.get('action', '')
|
||||
if not deployment or not action:
|
||||
return jsonify({'success': False, 'output': 'Missing deployment or action'})
|
||||
|
||||
actions = {
|
||||
'restart': f'rollout restart deployment/{deployment}',
|
||||
'status': f'rollout status deployment/{deployment}',
|
||||
'scale_0': f'scale deployment/{deployment} --replicas=0',
|
||||
'scale_1': f'scale deployment/{deployment} --replicas=1',
|
||||
'describe': f'describe deployment/{deployment}',
|
||||
}
|
||||
cmd = actions.get(action)
|
||||
if not cmd:
|
||||
return jsonify({'success': False, 'output': f'Unknown action: {action}'})
|
||||
|
||||
out, err, rc = k8s.run(cmd)
|
||||
return jsonify({'success': rc == 0, 'output': out + '\n' + err})
|
||||
|
||||
@app.route('/server/pods')
|
||||
def server_pods():
|
||||
out, err, rc = k8s.run('get pods -o wide')
|
||||
if rc != 0:
|
||||
return jsonify({'success': False, 'output': err})
|
||||
return jsonify({'success': True, 'output': out})
|
||||
|
||||
@app.route('/server/metrics')
|
||||
def server_metrics():
|
||||
metrics = k8s.get_node_metrics()
|
||||
if metrics:
|
||||
return jsonify(metrics)
|
||||
return jsonify({'cpu': 'N/A', 'memory': 'N/A'})
|
||||
|
||||
# Battlegroup
|
||||
@app.route('/server/battlegroup/status')
|
||||
def battlegroup_status():
|
||||
bg_script = settings['kubernetes']['battlegroup_script']
|
||||
out, err, rc = ssh.run(f'{bg_script} status', timeout=30)
|
||||
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
|
||||
|
||||
@app.route('/server/battlegroup/action', methods=['POST'])
|
||||
def battlegroup_action():
|
||||
action = request.form.get('action', '')
|
||||
if action not in ('start', 'stop', 'restart'):
|
||||
return jsonify({'success': False, 'output': f'Unknown action: {action}'})
|
||||
bg_script = settings['kubernetes']['battlegroup_script']
|
||||
out, err, rc = ssh.run(f'{bg_script} {action}', timeout=120)
|
||||
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
|
||||
|
||||
@app.route('/server/battlegroup/update', methods=['POST'])
|
||||
def battlegroup_update():
|
||||
bg_script = settings['kubernetes']['battlegroup_script']
|
||||
out, err, rc = ssh.run(f'{bg_script} update', timeout=600)
|
||||
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
|
||||
|
||||
# Chat API
|
||||
@app.route('/api/chat_logs')
|
||||
def api_chat_logs():
|
||||
try:
|
||||
chat_svc.ensure_history_table()
|
||||
|
||||
db_messages = chat_svc.get_history(1)
|
||||
if not db_messages or len(db_messages) < 10:
|
||||
chat_svc.catch_up(settings['kubernetes']['namespace'])
|
||||
|
||||
db_messages = chat_svc.get_history(200)
|
||||
messages = []
|
||||
for row in db_messages:
|
||||
ts = row.get('timestamp')
|
||||
messages.append({
|
||||
'channel': row.get('channel', ''),
|
||||
'sender': row.get('sender', ''),
|
||||
'message': row.get('message', ''),
|
||||
'timestamp': ts.isoformat() if ts else '',
|
||||
'location': {'X': row.get('location_x', 0), 'Y': row.get('location_y', 0), 'Z': row.get('location_z', 0)},
|
||||
'target': row.get('target', ''),
|
||||
'is_admin': row.get('is_admin', False),
|
||||
})
|
||||
|
||||
return jsonify({'success': True, 'messages': messages, 'count': len(messages)})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
# Player IP management
|
||||
@app.route('/api/set_player_ip', methods=['POST'])
|
||||
def api_set_player_ip():
|
||||
try:
|
||||
player_id = request.form.get('player_id', type=int)
|
||||
ip_address = request.form.get('ip_address', '').strip()
|
||||
if not player_id:
|
||||
return jsonify({'success': False, 'error': 'Missing player_id'})
|
||||
if not ip_address:
|
||||
return jsonify({'success': False, 'error': 'Missing ip_address'})
|
||||
|
||||
if admin_svc.set_player_ip(player_id, ip_address):
|
||||
return jsonify({'success': True, 'message': f'IP {ip_address} set for player {player_id}'})
|
||||
return jsonify({'success': False, 'error': 'Failed to set IP'})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
@app.route('/api/detect_player_ips', methods=['POST'])
|
||||
def api_detect_player_ips():
|
||||
try:
|
||||
success, message = admin_svc.detect_player_ips(settings['kubernetes']['namespace'])
|
||||
return jsonify({'success': success, 'message': message})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
# Ban management
|
||||
@app.route('/api/ban_player', methods=['POST'])
|
||||
def api_ban_player():
|
||||
try:
|
||||
player_id = request.form.get('player_id', type=int)
|
||||
duration = request.form.get('duration', '0')
|
||||
reason = request.form.get('reason', '')
|
||||
note = request.form.get('note', '')
|
||||
|
||||
if not player_id:
|
||||
return jsonify({'success': False, 'error': 'Missing player_id'})
|
||||
|
||||
success, message = admin_svc.ban_player(player_id, duration, reason, note)
|
||||
return jsonify({'success': success, 'message': message})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
@app.route('/api/get_player_ban', methods=['POST'])
|
||||
def api_get_player_ban():
|
||||
try:
|
||||
player_id = request.form.get('player_id', type=int)
|
||||
if not player_id:
|
||||
return jsonify({'success': False, 'error': 'Missing player_id'})
|
||||
|
||||
ban = admin_svc.get_player_ban(player_id)
|
||||
if ban:
|
||||
return jsonify({
|
||||
'success': True, 'banned': True,
|
||||
'reason': ban.get('reason', ''),
|
||||
'note': ban.get('note', ''),
|
||||
'duration': ban.get('duration', 0),
|
||||
'banned_at': ban.get('banned_at').isoformat() if ban.get('banned_at') else '',
|
||||
'expires_at': ban.get('expires_at').isoformat() if ban.get('expires_at') else 'Permanent'
|
||||
})
|
||||
return jsonify({'success': True, 'banned': False})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
@app.route('/api/get_player_history', methods=['POST'])
|
||||
def api_get_player_history():
|
||||
try:
|
||||
player_id = request.form.get('player_id', type=int)
|
||||
if not player_id:
|
||||
return jsonify({'success': False, 'error': 'Missing player_id'})
|
||||
|
||||
actions = admin_svc.get_player_history(player_id)
|
||||
history = []
|
||||
for a in actions:
|
||||
history.append({
|
||||
'action': a.get('action_type', ''),
|
||||
'reason': a.get('reason', ''),
|
||||
'note': a.get('note', ''),
|
||||
'duration': a.get('duration_minutes', 0),
|
||||
'ip': a.get('ip_address', ''),
|
||||
'created_at': a.get('created_at').isoformat() if a.get('created_at') else ''
|
||||
})
|
||||
return jsonify({'success': True, 'history': history})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
@app.route('/api/unban_player', methods=['POST'])
|
||||
def api_unban_player():
|
||||
try:
|
||||
player_id = request.form.get('player_id', type=int)
|
||||
if not player_id:
|
||||
return jsonify({'success': False, 'error': 'Missing player_id'})
|
||||
|
||||
success, message = admin_svc.unban_player(player_id)
|
||||
return jsonify({'success': success, 'message': message})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
@app.route('/api/emergency_unban', methods=['POST'])
|
||||
def api_emergency_unban():
|
||||
try:
|
||||
ip = request.form.get('ip', '').strip()
|
||||
if not ip:
|
||||
return jsonify({'success': False, 'error': 'Missing IP'})
|
||||
success, message = admin_svc.emergency_unban(ip)
|
||||
return jsonify({'success': success, 'message': message})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
@app.route('/api/kick_player', methods=['POST'])
|
||||
def api_kick_player():
|
||||
try:
|
||||
player_id = request.form.get('player_id', type=int)
|
||||
if not player_id:
|
||||
return jsonify({'success': False, 'error': 'Missing player_id'})
|
||||
|
||||
success, message = admin_svc.kick_player(player_id)
|
||||
return jsonify({'success': success, 'message': message})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
# Vitals editing
|
||||
@app.route('/api/edit_vitals', methods=['POST'])
|
||||
def api_edit_vitals():
|
||||
try:
|
||||
pawn_id = request.form.get('pawn_id', type=int)
|
||||
current_health = request.form.get('current_health', type=float)
|
||||
max_health = request.form.get('max_health', type=float)
|
||||
current_hydration = request.form.get('current_hydration', type=float)
|
||||
current_spice = request.form.get('current_spice', type=float)
|
||||
|
||||
success, result = admin_svc.edit_vitals(pawn_id, current_health, max_health, current_hydration, current_spice)
|
||||
if success:
|
||||
return jsonify({'success': True, **result})
|
||||
return jsonify({'success': False, 'error': result})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
# Maintenance
|
||||
@app.route('/api/maintenance/create_indexes', methods=['POST'])
|
||||
def api_create_indexes():
|
||||
try:
|
||||
success, created, error = admin_svc.create_indexes()
|
||||
if success:
|
||||
return jsonify({'success': True, 'created': created, 'count': len(created)})
|
||||
return jsonify({'success': False, 'error': error})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
|
||||
# Delete vehicle
|
||||
@app.route('/api/vehicles/<int:vehicle_id>', methods=['DELETE'])
|
||||
def delete_vehicle(vehicle_id):
|
||||
success, message = vehicle_svc.delete_vehicle(vehicle_id)
|
||||
if success:
|
||||
return jsonify({'success': True, 'message': message})
|
||||
return jsonify({'success': False, 'error': message}), 404 if 'not found' in message.lower() else 500
|
||||
|
||||
# Delete building
|
||||
@app.route('/api/buildings/<int:building_id>', methods=['DELETE'])
|
||||
def delete_building(building_id):
|
||||
conn = db.get_connection()
|
||||
if not conn:
|
||||
return jsonify({'success': False, 'error': 'Database connection failed'}), 500
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SET session_replication_role = replica")
|
||||
cur.execute("DELETE FROM dune.building_instances WHERE building_id = %s", [building_id])
|
||||
cur.execute("DELETE FROM dune.buildings WHERE id = %s RETURNING id", [building_id])
|
||||
deleted = cur.fetchone()
|
||||
if deleted:
|
||||
cur.execute("DELETE FROM dune.actors WHERE id = %s RETURNING id", [building_id])
|
||||
conn.commit()
|
||||
cur.execute("SET session_replication_role = default")
|
||||
return jsonify({'success': True, 'message': f'Building {building_id} deleted'})
|
||||
else:
|
||||
conn.rollback()
|
||||
cur.execute("SET session_replication_role = default")
|
||||
return jsonify({'success': False, 'error': 'Building not found'}), 404
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete building {building_id}: {e}")
|
||||
try:
|
||||
cur.execute("SET session_replication_role = default")
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
db.return_connection(conn)
|
||||
|
||||
# Debug endpoints (should be restricted in production)
|
||||
@app.route('/api/debug/vehicle_properties/<int:vehicle_id>')
|
||||
def debug_vehicle_properties(vehicle_id):
|
||||
try:
|
||||
vehicle = db.query("""
|
||||
SELECT a.id, a.class, a.properties
|
||||
FROM dune.actors a JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s
|
||||
""", [vehicle_id], one=True)
|
||||
if not vehicle:
|
||||
return jsonify({'error': 'Vehicle not found'}), 404
|
||||
|
||||
props = vehicle.get('properties', {})
|
||||
keys = list(props.keys()) if props else []
|
||||
damageable = props.get('DamageableActorComponent', {})
|
||||
damageable_keys = list(damageable.keys()) if damageable else []
|
||||
weapon_comp = props.get('WeaponActorComponent', {})
|
||||
weapon_keys = list(weapon_comp.keys()) if weapon_comp else []
|
||||
|
||||
class_key = [k for k in keys if k.startswith('BP_')][0] if [k for k in keys if k.startswith('BP_')] else None
|
||||
vehicle_bp = props.get(class_key, {}) if class_key else {}
|
||||
|
||||
def extract_all_keys(d, prefix='', max_depth=3, depth=0):
|
||||
if depth >= max_depth:
|
||||
return []
|
||||
result = []
|
||||
if isinstance(d, dict):
|
||||
for k, v in d.items():
|
||||
result.append(prefix + k)
|
||||
if isinstance(v, dict):
|
||||
result.extend(extract_all_keys(v, prefix + k + '.', max_depth, depth + 1))
|
||||
elif isinstance(v, list) and v and isinstance(v[0], dict):
|
||||
result.append(prefix + k + '[]')
|
||||
result.extend(extract_all_keys(v[0], prefix + k + '[0].', max_depth, depth + 1))
|
||||
return result
|
||||
|
||||
all_keys = extract_all_keys(props)[:100]
|
||||
relevant = [k for k in all_keys if any(x in k.lower() for x in ['health', 'damage', 'part', 'module', 'component', 'hit', 'armor', 'slot'])]
|
||||
|
||||
return jsonify({
|
||||
'id': vehicle_id, 'class': vehicle['class'],
|
||||
'all_keys_sample': all_keys[:50], 'relevant_keys': relevant[:30]
|
||||
})
|
||||
except Exception as e:
|
||||
logger.exception("Error fetching vehicle properties")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/vehicle_children/<int:vehicle_id>/')
|
||||
def debug_vehicle_children(vehicle_id):
|
||||
try:
|
||||
children = db.query("""
|
||||
SELECT a.id, a.class, a.map, a.properties
|
||||
FROM dune.actors a
|
||||
WHERE a.properties::text LIKE %s LIMIT 50
|
||||
""", [f'!!act#{vehicle_id}']) or []
|
||||
|
||||
results = []
|
||||
for c in children:
|
||||
props = c.get('properties', {})
|
||||
results.append({
|
||||
'id': c['id'], 'class': c['class'], 'map': c['map'],
|
||||
'keys': list(props.keys())[:15] if props else []
|
||||
})
|
||||
return jsonify({'vehicle_id': vehicle_id, 'found_children': len(results), 'children': results})
|
||||
except Exception as e:
|
||||
logger.exception("Error fetching vehicle children")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/vehicle_parts/<int:vehicle_id>')
|
||||
def debug_vehicle_parts(vehicle_id):
|
||||
try:
|
||||
parts = db.query("""
|
||||
SELECT a.id, a.class, a.properties FROM dune.actors
|
||||
WHERE a.properties::text LIKE %s LIMIT 100
|
||||
""", [f'%!!act#{vehicle_id}%']) or []
|
||||
|
||||
results = []
|
||||
for p in parts:
|
||||
props = p.get('properties', {})
|
||||
current_health = props.get('DamageableActorComponent', {}).get('m_CurrentMaxHealth')
|
||||
max_health = props.get('DamageableActorComponent', {}).get('m_TotalMaxHealth')
|
||||
results.append({
|
||||
'id': p['id'],
|
||||
'class': p['class'][:100] if p.get('class') else '',
|
||||
'current_health': current_health, 'max_health': max_health
|
||||
})
|
||||
|
||||
vehicle = db.query("""
|
||||
SELECT a.id, a.class, a.properties FROM dune.actors a
|
||||
JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s
|
||||
""", [vehicle_id], one=True)
|
||||
|
||||
return jsonify({
|
||||
'vehicle_id': vehicle_id,
|
||||
'vehicle_class': vehicle.get('class', '') if vehicle else '',
|
||||
'keys': list(vehicle.get('properties', {}).keys()) if vehicle else [],
|
||||
'bp_keys': list(vehicle.get('properties', {}).get('BP_MediumOrnithopter_CHOAM_C', {}).keys()) if vehicle else []
|
||||
})
|
||||
except Exception as e:
|
||||
logger.exception("Error fetching vehicle parts")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/list_tables')
|
||||
def list_tables():
|
||||
try:
|
||||
tables = db.query("""
|
||||
SELECT table_name FROM information_schema.tables
|
||||
WHERE table_schema = 'dune' ORDER BY table_name
|
||||
""") or []
|
||||
return jsonify({'tables': [t.get('table_name', '') for t in tables]})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/vehicle_modules/<int:vehicle_id>')
|
||||
def debug_vehicle_modules(vehicle_id):
|
||||
try:
|
||||
vehicle_modules = db.query("SELECT * FROM dune.vehicle_modules WHERE vehicle_id = %s LIMIT 50", [vehicle_id]) or []
|
||||
return jsonify({'vehicle_id': vehicle_id, 'found': len(vehicle_modules), 'modules': vehicle_modules})
|
||||
except Exception as e:
|
||||
logger.exception("Error fetching vehicle modules")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/vmi/<int:vehicle_id>')
|
||||
def debug_vmi(vehicle_id):
|
||||
try:
|
||||
invs = db.query("SELECT * FROM dune.vehicle_module_inventories WHERE vehicle_id = %s LIMIT 10", [vehicle_id])
|
||||
return jsonify({'data': invs})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)[:100]})
|
||||
|
||||
@app.route('/api/debug/vm_schema')
|
||||
def debug_vm_schema():
|
||||
try:
|
||||
cols = db.query("""
|
||||
SELECT column_name, data_type FROM information_schema.columns
|
||||
WHERE table_name = 'vehicle_modules' AND table_schema = 'dune'
|
||||
ORDER BY ordinal_position
|
||||
""") or []
|
||||
return jsonify({'columns': cols})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/vm_stats/<int:vehicle_id>')
|
||||
def debug_vm_stats(vehicle_id):
|
||||
try:
|
||||
modules = db.query("SELECT id, template_id, stats FROM dune.vehicle_modules WHERE vehicle_id = %s", [vehicle_id]) or []
|
||||
results = []
|
||||
for m in modules:
|
||||
stats = m.get('stats', {})
|
||||
durability = stats.get('FVehicleModuleDurabilityStats', [{}])[1] if stats.get('FVehicleModuleDurabilityStats') else {}
|
||||
results.append({
|
||||
'id': m['id'], 'template': m['template_id'],
|
||||
'durability_keys': list(durability.keys()) if durability else [],
|
||||
'durability': durability
|
||||
})
|
||||
return jsonify({'vehicle_id': vehicle_id, 'modules': results})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/vehicle_row/<int:vehicle_id>')
|
||||
def debug_vehicle_row(vehicle_id):
|
||||
try:
|
||||
v = db.query("SELECT * FROM dune.vehicles WHERE id = %s", [vehicle_id], one=True)
|
||||
return jsonify({'vehicle': v})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/debug/module_tables')
|
||||
def debug_module_tables():
|
||||
try:
|
||||
tables = db.query("""
|
||||
SELECT table_name FROM information_schema.tables
|
||||
WHERE table_schema = 'dune' AND (table_name LIKE '%module%' OR table_name LIKE '%vehicle%')
|
||||
ORDER BY table_name
|
||||
""") or []
|
||||
return jsonify({'tables': [t.get('table_name', '') for t in tables]})
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
# File browser
|
||||
def _get_fb_pod():
|
||||
"""Get the FileBrowser pod name dynamically."""
|
||||
pod = k8s.find_pod_by_pattern('fb-deploy')
|
||||
return pod
|
||||
|
||||
def _fb_exec(command, timeout=10):
|
||||
"""Execute kubectl exec in the FileBrowser pod with correct namespace placement."""
|
||||
pod = _get_fb_pod()
|
||||
if not pod:
|
||||
return '', 'FileBrowser pod not found', 1
|
||||
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
|
||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
||||
|
||||
@app.route('/api/files/list', methods=['POST'])
|
||||
def api_files_list():
|
||||
path = request.form.get('path', '/srv')
|
||||
out, err, rc = _fb_exec(f'ls -la "{path}"', timeout=10)
|
||||
if rc != 0:
|
||||
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
|
||||
|
||||
files = []
|
||||
for line in out.strip().split('\n')[1:]:
|
||||
parts = line.split(None, 8)
|
||||
if len(parts) >= 9:
|
||||
perms = parts[0]
|
||||
size = parts[4]
|
||||
date = ' '.join(parts[5:8])
|
||||
name = parts[8]
|
||||
if name in ('.', '..'):
|
||||
continue
|
||||
files.append({
|
||||
'name': name,
|
||||
'is_dir': perms.startswith('d'),
|
||||
'size': size if not perms.startswith('d') else '',
|
||||
'perms': perms,
|
||||
'date': date,
|
||||
})
|
||||
return jsonify({'success': True, 'files': files})
|
||||
|
||||
@app.route('/api/files/view')
|
||||
def api_files_view():
|
||||
path = request.args.get('path', '')
|
||||
if not path:
|
||||
return jsonify({'success': False, 'error': 'Missing path'})
|
||||
out, err, rc = _fb_exec(f'head -c 100000 "{path}"', timeout=10)
|
||||
if rc != 0:
|
||||
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
||||
return jsonify({'success': True, 'content': out, 'path': path})
|
||||
|
||||
@app.route('/api/files/save', methods=['POST'])
|
||||
def api_files_save():
|
||||
path = request.form.get('path', '')
|
||||
content = request.form.get('content', '')
|
||||
if not path:
|
||||
return jsonify({'success': False, 'error': 'Missing path'})
|
||||
import base64
|
||||
content_b64 = base64.b64encode(content.encode()).decode()
|
||||
out, err, rc = _fb_exec(f'sh -c \'echo {content_b64} | base64 -d > "{path}"\'', timeout=15)
|
||||
if rc != 0:
|
||||
return jsonify({'success': False, 'error': err or 'Failed to save file'})
|
||||
return jsonify({'success': True})
|
||||
|
||||
director_port = settings.get('director', {}).get('port', 32479)
|
||||
director_base = f"http://{settings['server']['host']}:{director_port}"
|
||||
k8s_ns = settings['kubernetes']['namespace']
|
||||
cm_name = f"{k8s_ns}-bgd-conf-cm"
|
||||
|
||||
def _patch_configmap(new_ini_content):
|
||||
"""Patch the BGD ConfigMap with new director.ini content via base64 pipe."""
|
||||
import base64
|
||||
cm_out, cm_err, cm_rc = k8s.run(f'get configmap {cm_name} -o json')
|
||||
if cm_rc != 0 or not cm_out:
|
||||
logger.warning(f"Could not get ConfigMap: {cm_err}")
|
||||
return False
|
||||
cm = json.loads(cm_out)
|
||||
cm['data']['director.ini'] = new_ini_content
|
||||
cm_json = json.dumps(cm)
|
||||
cm_b64 = base64.b64encode(cm_json.encode()).decode()
|
||||
patch_cmd = f'echo {cm_b64} | base64 -d | sudo kubectl apply -f - -n {k8s_ns}'
|
||||
out, err, rc = ssh.run(patch_cmd, timeout=15)
|
||||
if rc != 0:
|
||||
logger.warning(f"ConfigMap patch failed: {err}")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _update_ini_section(map_name, key_values, remove_section=False):
|
||||
"""Read ConfigMap INI, modify section, write back."""
|
||||
import configparser
|
||||
import io
|
||||
cm_out, _, cm_rc = k8s.run(f'get configmap {cm_name} -o json')
|
||||
if cm_rc != 0 or not cm_out:
|
||||
return False
|
||||
cm = json.loads(cm_out)
|
||||
ini_content = cm['data'].get('director.ini', '')
|
||||
cfg = configparser.ConfigParser()
|
||||
cfg.read_string(ini_content)
|
||||
if remove_section:
|
||||
if cfg.has_section(map_name):
|
||||
cfg.remove_section(map_name)
|
||||
else:
|
||||
if not cfg.has_section(map_name):
|
||||
cfg.add_section(map_name)
|
||||
for key, value in key_values.items():
|
||||
if value is not None:
|
||||
cfg.set(map_name, key, str(value))
|
||||
buf = io.StringIO()
|
||||
cfg.write(buf)
|
||||
return _patch_configmap(buf.getvalue())
|
||||
|
||||
# Director API proxy
|
||||
@app.route('/api/director/battlegroup')
|
||||
def director_battlegroup():
|
||||
try:
|
||||
import urllib.request
|
||||
req = urllib.request.Request(f"{director_base}/v0/battlegroup")
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
data = resp.read().decode()
|
||||
return data, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/update_config', methods=['POST'])
|
||||
def director_update_config():
|
||||
try:
|
||||
import urllib.request
|
||||
config = request.get_json()
|
||||
map_name = config.get('MapName', '')
|
||||
req = urllib.request.Request(f"{director_base}/v0/BattlegroupUpdateServerGroupConfig", data=json.dumps(config).encode(), headers={'Content-Type': 'application/json'}, method='POST')
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
result = resp.read().decode()
|
||||
|
||||
if map_name:
|
||||
kv = {}
|
||||
if 'DimensionServerGroupConfig' in config:
|
||||
dcfg = config['DimensionServerGroupConfig']
|
||||
if dcfg.get('playerHardCap') is not None:
|
||||
kv['PlayerHardCap'] = dcfg['playerHardCap']
|
||||
if dcfg.get('minServers') is not None:
|
||||
kv['MinServers'] = dcfg['minServers']
|
||||
if dcfg.get('numExtraServers') is not None:
|
||||
kv['NumExtraServers'] = dcfg['numExtraServers']
|
||||
if 'enableAutomaticInstanceScaling' in dcfg:
|
||||
kv['EnableAutomaticInstanceScaling'] = str(dcfg['enableAutomaticInstanceScaling'])
|
||||
if dcfg.get('instanceScalingThrottlingSeconds') is not None:
|
||||
kv['InstanceScalingThrottlingSeconds'] = dcfg['instanceScalingThrottlingSeconds']
|
||||
elif 'ClassicalInstancingGroupConfig' in config:
|
||||
icfg = config['ClassicalInstancingGroupConfig']
|
||||
if icfg.get('playerHardCap') is not None:
|
||||
kv['PlayerHardCap'] = icfg['playerHardCap']
|
||||
if icfg.get('minServers') is not None:
|
||||
kv['MinServers'] = icfg['minServers']
|
||||
if icfg.get('numExtraServers') is not None:
|
||||
kv['NumExtraServers'] = icfg['numExtraServers']
|
||||
if 'enableAutomaticInstanceScaling' in icfg:
|
||||
kv['EnableAutomaticInstanceScaling'] = str(icfg['enableAutomaticInstanceScaling'])
|
||||
if icfg.get('instanceScalingThrottlingSeconds') is not None:
|
||||
kv['InstanceScalingThrottlingSeconds'] = icfg['instanceScalingThrottlingSeconds']
|
||||
elif 'SingleServerConfig' in config:
|
||||
scfg = config['SingleServerConfig']
|
||||
if scfg.get('playerHardCap') is not None:
|
||||
kv['PlayerHardCap'] = scfg['playerHardCap']
|
||||
if kv:
|
||||
_update_ini_section(map_name, kv)
|
||||
|
||||
return result, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/clear_config', methods=['POST'])
|
||||
def director_clear_config():
|
||||
try:
|
||||
import urllib.request
|
||||
map_name = request.get_data(as_text=True).strip()
|
||||
req = urllib.request.Request(f"{director_base}/v0/BattlegroupClearMapConfigOverrides", data=map_name.encode(), headers={'Content-Type': 'application/json'}, method='POST')
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
result = resp.read().decode()
|
||||
if map_name:
|
||||
_update_ini_section(map_name, {}, remove_section=True)
|
||||
return result, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/character_transfer', methods=['GET'])
|
||||
def director_character_transfer_get():
|
||||
try:
|
||||
import urllib.request
|
||||
req = urllib.request.Request(f"{director_base}/v0/BattlegroupFetchCharacterTransferRules")
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
data = resp.read().decode()
|
||||
return data, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/character_transfer', methods=['POST'])
|
||||
def director_character_transfer_update():
|
||||
try:
|
||||
import urllib.request
|
||||
config = request.get_json()
|
||||
req = urllib.request.Request(f"{director_base}/v0/BattlegroupUpdateCharacterTransferSettings", data=json.dumps(config).encode(), headers={'Content-Type': 'application/json'}, method='POST')
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
result = resp.read().decode()
|
||||
|
||||
kv = {}
|
||||
if 'ForceIsWorldClosed' in config:
|
||||
kv['ForceIsWorldClosed'] = str(config['ForceIsWorldClosed'])
|
||||
if 'ForceIsWorldClosingSoon' in config:
|
||||
kv['ForceIsWorldClosingSoon'] = str(config['ForceIsWorldClosingSoon'])
|
||||
if kv:
|
||||
_update_ini_section('CharacterTransfers', kv)
|
||||
|
||||
return result, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/director/character_transfer_clear', methods=['POST'])
|
||||
def director_character_transfer_clear():
|
||||
try:
|
||||
import urllib.request
|
||||
req = urllib.request.Request(f"{director_base}/v0/BattlegroupClearCharacterTransferOverrides", method='POST')
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
result = resp.read().decode()
|
||||
|
||||
_update_ini_section('CharacterTransfers', {}, remove_section=True)
|
||||
|
||||
return result, 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Authentication routes - login, logout"""
|
||||
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash
|
||||
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
||||
|
||||
login_manager = LoginManager()
|
||||
login_manager.login_view = 'auth.login'
|
||||
login_manager.login_message = 'Please log in to access the dashboard.'
|
||||
|
||||
|
||||
class AdminUser(UserMixin):
|
||||
def __init__(self, username):
|
||||
self.id = username
|
||||
|
||||
|
||||
def init_auth(app, settings):
|
||||
login_manager.init_app(app)
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id):
|
||||
auth_settings = settings.get('auth', {})
|
||||
if auth_settings.get('username') == user_id:
|
||||
return AdminUser(user_id)
|
||||
return None
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('overview'))
|
||||
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username', '')
|
||||
password = request.form.get('password', '')
|
||||
auth_settings = settings.get('auth', {})
|
||||
|
||||
if username == auth_settings.get('username') and password == auth_settings.get('password'):
|
||||
user = AdminUser(username)
|
||||
login_user(user)
|
||||
next_page = request.args.get('next')
|
||||
return redirect(next_page or url_for('overview'))
|
||||
else:
|
||||
flash('Invalid username or password', 'error')
|
||||
|
||||
return render_template('login.html')
|
||||
|
||||
@app.route('/logout')
|
||||
@login_required
|
||||
def logout():
|
||||
logout_user()
|
||||
return redirect(url_for('login'))
|
||||
@@ -0,0 +1,438 @@
|
||||
"""Main route blueprints"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from flask import Blueprint, render_template, request, jsonify
|
||||
from flask_login import login_required, current_user
|
||||
from app.utils.constants import NAV_PAGES, GUILD_ROLES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def register_routes(app, services, settings):
|
||||
db = services['db']
|
||||
ssh = services['ssh']
|
||||
k8s = services['k8s']
|
||||
player_svc = services['player']
|
||||
vehicle_svc = services['vehicle']
|
||||
chat_svc = services['chat']
|
||||
admin_svc = services['admin']
|
||||
static_cache = services['static_cache']
|
||||
|
||||
def fmt_role(role_id):
|
||||
return GUILD_ROLES.get(role_id, f'Role {role_id}')
|
||||
|
||||
def get_static_data():
|
||||
current_time = __import__('datetime').datetime.now().timestamp()
|
||||
cached = static_cache.get('static_data')
|
||||
if cached and (current_time - cached['timestamp']) < settings['cache']['static_data_ttl']:
|
||||
return cached
|
||||
|
||||
data = {
|
||||
'factions': db.query("SELECT id, name FROM dune.factions ORDER BY id") or [],
|
||||
'guilds': db.query("SELECT guild_id, guild_name FROM dune.guilds ORDER BY guild_name") or [],
|
||||
'maps': db.query("SELECT DISTINCT map FROM dune.actors WHERE class LIKE %s AND map IS NOT NULL ORDER BY map", ['%DunePlayerCharacter_C']) or [],
|
||||
'keystones': db.query("SELECT id, name FROM dune.specialization_keystones_map ORDER BY id") or [],
|
||||
'timestamp': current_time,
|
||||
}
|
||||
static_cache.set('static_data', data)
|
||||
logger.info("Static data cache refreshed")
|
||||
return data
|
||||
|
||||
@app.context_processor
|
||||
def inject_globals():
|
||||
conn_ok = db.check_health()
|
||||
return dict(
|
||||
nav_pages=NAV_PAGES,
|
||||
current_path=request.path if request else '/',
|
||||
fmt_role=fmt_role,
|
||||
conn_ok=conn_ok,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
@app.template_filter('inv_label')
|
||||
def inv_label_filter(inv_type):
|
||||
from app.utils.constants import INVENTORY_TYPE_LABELS
|
||||
if inv_type is None:
|
||||
return 'Unknown'
|
||||
return INVENTORY_TYPE_LABELS.get(inv_type, f'Type {inv_type}')
|
||||
|
||||
@app.template_filter('currency_label')
|
||||
def currency_label_filter(currency_id):
|
||||
from app.utils.constants import CURRENCY_ID_LABELS
|
||||
return CURRENCY_ID_LABELS.get(currency_id, f'Currency {currency_id}')
|
||||
|
||||
@app.template_filter('class_name')
|
||||
def class_name_filter(s):
|
||||
if not s:
|
||||
return ''
|
||||
short = s.split('/')[-1] if '/' in s else s
|
||||
if short.endswith('_C'):
|
||||
short = short[:-2]
|
||||
if '.' in short:
|
||||
short = short.split('.')[-1]
|
||||
return short
|
||||
|
||||
@app.template_filter('truncate')
|
||||
def truncate_filter(s, length=100):
|
||||
if s and len(s) > length:
|
||||
return s[:length] + '...'
|
||||
return s or ''
|
||||
|
||||
@app.template_filter('json_format')
|
||||
def json_format_filter(val):
|
||||
if val is None:
|
||||
return ''
|
||||
if isinstance(val, dict):
|
||||
return json.dumps(val, indent=2, ensure_ascii=False)
|
||||
return str(val)
|
||||
|
||||
@app.template_filter('format_number')
|
||||
def format_number_filter(val):
|
||||
if val is None:
|
||||
return '0'
|
||||
try:
|
||||
n = int(val)
|
||||
return f'{n:,}'
|
||||
except (ValueError, TypeError):
|
||||
return str(val)
|
||||
|
||||
# Health check
|
||||
@app.route('/health')
|
||||
def health_check():
|
||||
health = {'status': 'healthy', 'checks': {}}
|
||||
port_ok = __import__('socket').socket(__import__('socket').AF_INET, __import__('socket').SOCK_STREAM).connect_ex(('127.0.0.1', settings['database']['port'])) == 0
|
||||
health['checks']['ssh_tunnel'] = 'ok' if port_ok else 'down'
|
||||
if not port_ok:
|
||||
health['status'] = 'degraded'
|
||||
health['checks']['database'] = 'unknown'
|
||||
return jsonify(health), 503
|
||||
|
||||
if db.check_health():
|
||||
health['checks']['database'] = 'ok'
|
||||
else:
|
||||
health['status'] = 'unhealthy'
|
||||
health['checks']['database'] = 'connection failed'
|
||||
return jsonify(health), 503
|
||||
return jsonify(health)
|
||||
|
||||
# Overview
|
||||
@app.route('/')
|
||||
def overview():
|
||||
try:
|
||||
counts = player_svc.get_overview_counts()
|
||||
data = {
|
||||
'faction_dist': player_svc.get_faction_distribution(),
|
||||
'per_map': player_svc.get_players_per_map(),
|
||||
'players_online': player_svc.get_players_online(),
|
||||
}
|
||||
data.update(counts or {})
|
||||
return render_template('overview.html', **data)
|
||||
except Exception as e:
|
||||
logger.exception("Error in overview route")
|
||||
return render_template('overview.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Players list
|
||||
@app.route('/players')
|
||||
def players():
|
||||
try:
|
||||
search = request.args.get('search', '')
|
||||
faction_id = request.args.get('faction', '')
|
||||
guild_id = request.args.get('guild', '')
|
||||
map_filter = request.args.get('map', '')
|
||||
online_filter = request.args.get('online', '')
|
||||
|
||||
players_list = player_svc.get_players_list(
|
||||
search=search, faction_id=faction_id, guild_id=guild_id,
|
||||
map_filter=map_filter, online_filter=online_filter
|
||||
)
|
||||
|
||||
static_data = get_static_data()
|
||||
return render_template('players.html',
|
||||
players=players_list, factions=static_data['factions'],
|
||||
guilds=static_data['guilds'], maps=static_data['maps'],
|
||||
search=search, sel_faction=faction_id, sel_guild=guild_id,
|
||||
sel_map=map_filter, sel_online=online_filter)
|
||||
except Exception as e:
|
||||
logger.exception("Error in players route")
|
||||
return render_template('players.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Player detail
|
||||
@app.route('/players/<int:player_id>')
|
||||
def player_detail(player_id):
|
||||
try:
|
||||
player = player_svc.get_player_detail(player_id)
|
||||
if not player:
|
||||
return render_template('player_detail.html', not_found=True)
|
||||
|
||||
player_controller_id = player.get('player_controller_id')
|
||||
|
||||
vitals = player_svc.get_player_vitals(player.get('state_pawn_id'))
|
||||
guild = player_svc.get_player_guild(player_controller_id)
|
||||
player_vehicles = player_svc.get_player_vehicles(player_controller_id)
|
||||
buildings_result = player_svc.get_player_buildings(player_id)
|
||||
currency = player_svc.get_player_currency(player_controller_id)
|
||||
inventories = player_svc.get_player_inventories(player_id)
|
||||
landclaims = player_svc.get_player_landclaims(player.get('owner_account_id'))
|
||||
specialization = player_svc.get_player_specialization(player_controller_id)
|
||||
tech_knowledge = player_svc.get_player_tech_knowledge(player_id)
|
||||
purchased_keystones = player_svc.get_player_keystones(player_controller_id)
|
||||
faction_reputation = player_svc.get_player_faction_reputation(player_controller_id)
|
||||
landsraad_info = player_svc.get_player_landsraad(player_controller_id)
|
||||
|
||||
is_online = player_svc.is_online(player_controller_id) if player_controller_id else False
|
||||
|
||||
static_data = get_static_data()
|
||||
|
||||
return render_template('player_detail.html',
|
||||
player=player, guild=guild, vehicles=player_vehicles,
|
||||
buildings=buildings_result, currency=currency,
|
||||
inventories=inventories, landclaims=landclaims,
|
||||
specialization=specialization, tech_knowledge=tech_knowledge,
|
||||
purchased_keystones=purchased_keystones, all_keystones=static_data['keystones'],
|
||||
faction_reputation=faction_reputation, landsraad_info=landsraad_info,
|
||||
vitals=vitals, is_online=is_online)
|
||||
except Exception as e:
|
||||
logger.exception("Error in player_detail route")
|
||||
return render_template('player_detail.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Vehicles
|
||||
@app.route('/vehicles')
|
||||
def vehicles():
|
||||
try:
|
||||
vehicles_list = vehicle_svc.get_all_vehicles()
|
||||
return render_template('vehicles.html', vehicles=vehicles_list)
|
||||
except Exception as e:
|
||||
logger.exception("Error in vehicles route")
|
||||
return render_template('vehicles.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Vehicle detail
|
||||
@app.route('/vehicles/<int:vehicle_id>')
|
||||
def vehicle_detail(vehicle_id):
|
||||
try:
|
||||
vehicle = vehicle_svc.get_vehicle(vehicle_id)
|
||||
if not vehicle:
|
||||
return render_template('vehicle_detail.html', not_found=True)
|
||||
|
||||
modules = vehicle_svc.get_vehicle_modules(vehicle_id)
|
||||
from app.services.vehicle import parse_vehicle_modules
|
||||
parsed_modules = parse_vehicle_modules(modules, vehicle.get('class', ''))
|
||||
|
||||
return render_template('vehicle_detail.html', vehicle=vehicle, modules=parsed_modules)
|
||||
except Exception as e:
|
||||
logger.exception("Error in vehicle_detail route")
|
||||
return render_template('vehicle_detail.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Guilds
|
||||
@app.route('/guilds')
|
||||
def guilds():
|
||||
try:
|
||||
guilds_list = db.query("""
|
||||
SELECT g.*, f.name as faction_name,
|
||||
(SELECT COUNT(*)::int FROM dune.guild_members gm WHERE gm.guild_id = g.guild_id) as member_count,
|
||||
(SELECT COUNT(*)::int FROM dune.guild_members gm
|
||||
JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id
|
||||
WHERE gm.guild_id = g.guild_id AND ps.online_status::text = 'Online') as online_count
|
||||
FROM dune.guilds g
|
||||
LEFT JOIN dune.factions f ON g.guild_faction = f.id
|
||||
ORDER BY g.guild_name
|
||||
""") or []
|
||||
return render_template('guilds.html', guilds=guilds_list)
|
||||
except Exception as e:
|
||||
logger.exception("Error in guilds route")
|
||||
return render_template('guilds.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Guild detail
|
||||
@app.route('/guilds/<int:guild_id>')
|
||||
def guild_detail(guild_id):
|
||||
try:
|
||||
guild = db.query("""
|
||||
SELECT g.*, f.name as faction_name
|
||||
FROM dune.guilds g
|
||||
LEFT JOIN dune.factions f ON g.guild_faction = f.id
|
||||
WHERE g.guild_id = %s
|
||||
""", [guild_id], one=True)
|
||||
if not guild:
|
||||
return render_template('guild_detail.html', not_found=True)
|
||||
|
||||
members = db.query("""
|
||||
SELECT ps.player_pawn_id as actor_id, ea.user as account_email, gm.role_id,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || ps.player_pawn_id::text) as player_name,
|
||||
ps.online_status::text as online_status,
|
||||
ps.player_controller_id,
|
||||
pawn_a.map as player_map,
|
||||
CASE WHEN pawn_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving' = 'True' THEN TRUE ELSE FALSE END as is_driving,
|
||||
vehicle_a.class as driving_vehicle_class
|
||||
FROM dune.guild_members gm
|
||||
JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id
|
||||
JOIN dune.encrypted_accounts ea ON ps.account_id = ea.id
|
||||
LEFT JOIN dune.accounts acc ON ea.id = acc.id
|
||||
LEFT JOIN dune.actors pawn_a ON ps.player_pawn_id = pawn_a.id
|
||||
LEFT JOIN dune.actors vehicle_a ON pawn_a.properties->'BP_DunePlayerCharacter_C'->>'m_CurrentVehicleId' = CONCAT('!!act#', vehicle_a.id::text)
|
||||
AND (pawn_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving')::boolean = TRUE
|
||||
WHERE gm.guild_id = %s
|
||||
ORDER BY gm.role_id DESC, player_name
|
||||
""", [guild_id]) or []
|
||||
|
||||
return render_template('guild_detail.html', guild=guild, members=members)
|
||||
except Exception as e:
|
||||
logger.exception("Error in guild_detail route")
|
||||
return render_template('guild_detail.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Buildings
|
||||
@app.route('/buildings')
|
||||
def buildings():
|
||||
try:
|
||||
buildings_list = db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'ID:' || b.owner_id::text) as owner_name,
|
||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count,
|
||||
a.properties->>'m_bIsPowered' as is_powered,
|
||||
a.properties->>'m_PowerLevel' as power_level,
|
||||
a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id
|
||||
FROM dune.buildings b
|
||||
JOIN dune.actors a ON b.id = a.id
|
||||
LEFT JOIN dune.player_state ps ON b.owner_id = ps.player_pawn_id
|
||||
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
|
||||
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
|
||||
)
|
||||
ORDER BY owner_name
|
||||
LIMIT 200
|
||||
""") or []
|
||||
return render_template('buildings.html', buildings=buildings_list)
|
||||
except Exception as e:
|
||||
logger.exception("Error in buildings route")
|
||||
return render_template('buildings.html', db_error=f"{type(e).__name__}: {e}")
|
||||
|
||||
# Events
|
||||
@app.route('/events')
|
||||
def events_page():
|
||||
game_events = []
|
||||
event_logs = []
|
||||
try:
|
||||
game_events = db.query("SELECT id, event_type, actor_id, actor_name, map, universe_time, x, y, z FROM dune.game_events ORDER BY universe_time DESC LIMIT 50") or []
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching game_events: {e}")
|
||||
try:
|
||||
event_logs = db.query("SELECT id, event_type, category, function_name, message, event_time, meta FROM dune.event_log ORDER BY event_time DESC LIMIT 100") or []
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching event_logs: {e}")
|
||||
return render_template('events.html', game_events=game_events, event_logs=event_logs)
|
||||
|
||||
# Chat
|
||||
@app.route('/chat')
|
||||
def chat_logs():
|
||||
return render_template('chat.html', max_lines=200)
|
||||
|
||||
# Shell
|
||||
@app.route('/shell')
|
||||
def shell_page():
|
||||
pods = []
|
||||
ssh_command = ''
|
||||
namespace = settings['kubernetes']['namespace']
|
||||
try:
|
||||
out, err, rc = ssh.run(f'sudo kubectl get pods -n {namespace} -o custom-columns=NAME:.metadata.name,ROLE:.metadata.labels.role,STATUS:.status.phase')
|
||||
if out:
|
||||
for line in out.strip().split('\n')[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 3:
|
||||
pods.append({'name': parts[0], 'role': parts[1] if parts[1] != '<none>' else '', 'status': parts[2]})
|
||||
|
||||
ssh_key = settings['server'].get('ssh_key')
|
||||
if ssh_key:
|
||||
ssh_command = f'ssh -i "{ssh_key}" {settings["server"]["user"]}@{settings["server"]["host"]}'
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return render_template('shell.html', pods=pods, ssh_command=ssh_command, namespace=namespace)
|
||||
|
||||
# Files (stub)
|
||||
@app.route('/files')
|
||||
def files_page():
|
||||
return render_template('files.html')
|
||||
|
||||
@app.route('/files/view')
|
||||
def files_view():
|
||||
path = request.args.get('path', '')
|
||||
return render_template('file_view.html', path=path)
|
||||
|
||||
# Director
|
||||
@app.route('/director')
|
||||
def director_page():
|
||||
director_port = settings.get('director', {}).get('port', 32479)
|
||||
return render_template('director.html', director_port=director_port)
|
||||
|
||||
# Admin
|
||||
@app.route('/admin')
|
||||
def admin_page():
|
||||
try:
|
||||
bans = admin_svc.get_bans()
|
||||
except Exception:
|
||||
bans = []
|
||||
return render_template('admin.html', bans=bans)
|
||||
|
||||
# Server status
|
||||
@app.route('/server')
|
||||
def server_status():
|
||||
try:
|
||||
active_servers = db.query("""
|
||||
SELECT a.server_id, w.map
|
||||
FROM dune.active_server_ids a
|
||||
LEFT JOIN dune.world_partition w ON a.server_id = w.server_id
|
||||
ORDER BY w.map, a.server_id
|
||||
""") or []
|
||||
per_map = player_svc.get_players_per_map()
|
||||
online_players = db.query(
|
||||
"SELECT ps.character_name, a.map, ps.online_status::text as online_status, "
|
||||
"ps.life_state::text as life_state, ps.last_login_time, ps.last_avatar_activity "
|
||||
"FROM dune.player_state ps "
|
||||
"JOIN dune.actors a ON ps.player_pawn_id = a.id "
|
||||
"WHERE ps.online_status::text = 'Online' "
|
||||
"ORDER BY ps.character_name"
|
||||
) or []
|
||||
partitions = db.query("SELECT * FROM dune.world_partition ORDER BY map, partition_id LIMIT 50") or []
|
||||
overmap_count = db.query("SELECT COUNT(*) c FROM dune.overmap_players", one=True)
|
||||
online_count = db.query("SELECT COUNT(*) c FROM dune.player_state WHERE online_status::text = 'Online'", one=True)
|
||||
|
||||
deployments = k8s.get_deployments()
|
||||
node_metrics = k8s.get_node_metrics()
|
||||
|
||||
for p in partitions:
|
||||
sid = (p.get('server_id') or '').lower().replace('_', '-')
|
||||
p['deployment'] = ''
|
||||
mp = (p.get('map') or '').lower().replace('_', '-')
|
||||
|
||||
for d in deployments:
|
||||
short = d.replace('deployment.apps/', '')
|
||||
if sid and sid in short.lower():
|
||||
p['deployment'] = d
|
||||
break
|
||||
if mp and mp in short.lower():
|
||||
p['deployment'] = d
|
||||
break
|
||||
|
||||
if not p['deployment']:
|
||||
mid = '-sg-' + sid
|
||||
for d in deployments:
|
||||
short = d.replace('deployment.apps/', '')
|
||||
if mid in short.lower():
|
||||
p['deployment'] = d
|
||||
break
|
||||
|
||||
if not p['deployment'] and mp:
|
||||
for d in deployments:
|
||||
short = d.replace('deployment.apps/', '')
|
||||
if mp in short.lower() and 'pod' in short.lower():
|
||||
p['deployment'] = d
|
||||
break
|
||||
|
||||
return render_template('server.html',
|
||||
active_servers=active_servers, per_map=per_map,
|
||||
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='',
|
||||
node_metrics=node_metrics)
|
||||
except Exception as e:
|
||||
logger.exception("Error in server_status route")
|
||||
return render_template('server.html', db_error=f"{type(e).__name__}: {e}")
|
||||
@@ -0,0 +1 @@
|
||||
"""Services package"""
|
||||
@@ -0,0 +1,393 @@
|
||||
"""Admin service - ban, kick, unban, vitals, IP detection"""
|
||||
|
||||
import re
|
||||
import time
|
||||
import threading
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AdminService:
|
||||
def __init__(self, db_service, ssh_service):
|
||||
self.db = db_service
|
||||
self.ssh = ssh_service
|
||||
|
||||
def ban_player(self, player_id, duration=0, reason='', note=''):
|
||||
try:
|
||||
duration_int = int(duration) if duration else 0
|
||||
except (ValueError, TypeError):
|
||||
duration_int = 0
|
||||
|
||||
player_row = self.db.query(
|
||||
"SELECT ps.account_id, ps.character_name FROM dune.player_state ps WHERE ps.player_controller_id = %s",
|
||||
[player_id], one=True
|
||||
)
|
||||
|
||||
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 dune.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,
|
||||
note = EXCLUDED.note, duration = EXCLUDED.duration,
|
||||
banned_at = NOW(), expires_at = NULL, active = TRUE
|
||||
""", [player_id, account_id, reason, note, duration_int])
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.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,
|
||||
note = EXCLUDED.note, duration = EXCLUDED.duration,
|
||||
banned_at = NOW(), expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
||||
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
|
||||
else:
|
||||
if duration_int == 0:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.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,
|
||||
duration = EXCLUDED.duration, banned_at = NOW(),
|
||||
expires_at = NULL, active = TRUE
|
||||
""", [player_id, reason, note, duration_int])
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.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,
|
||||
duration = EXCLUDED.duration, banned_at = NOW(),
|
||||
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
||||
""", [player_id, reason, note, duration_int, duration_int, duration_int])
|
||||
|
||||
conn.commit()
|
||||
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 dune.bans WHERE player_id = %s", [player_id])
|
||||
conn.commit()
|
||||
|
||||
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 else None
|
||||
|
||||
ips_to_unblock = []
|
||||
if account_id:
|
||||
all_ips = self.db.query("""
|
||||
SELECT ip_address FROM dune.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')]
|
||||
else:
|
||||
ip_row = self.db.query("SELECT ip_address FROM dune.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 dune.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id])
|
||||
conn.commit()
|
||||
|
||||
for ip in ips_to_unblock:
|
||||
self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null')
|
||||
self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null')
|
||||
|
||||
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("""
|
||||
SELECT ps.character_name, a.map FROM dune.player_state ps
|
||||
JOIN dune.actors a ON ps.player_pawn_id = a.id
|
||||
WHERE ps.player_controller_id = %s
|
||||
""", [player_id], one=True)
|
||||
|
||||
if not player:
|
||||
return False, "Player not found"
|
||||
|
||||
player_name = player.get('character_name', 'Unknown')
|
||||
ip_row = self.db.query("SELECT ip_address FROM dune.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:
|
||||
return False, "Player IP not known. Detect IPs first."
|
||||
|
||||
def temporary_block(ip):
|
||||
self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP')
|
||||
self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP')
|
||||
time.sleep(60)
|
||||
self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP')
|
||||
self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP')
|
||||
|
||||
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
|
||||
thread.start()
|
||||
|
||||
self.db.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
|
||||
|
||||
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
|
||||
|
||||
def edit_vitals(self, pawn_id, current_health=None, max_health=None, current_hydration=None, current_spice=None):
|
||||
if pawn_id is None or current_hydration is None or current_spice is None:
|
||||
return False, "Missing parameters"
|
||||
|
||||
controller_row = self.db.query(
|
||||
"SELECT player_controller_id FROM dune.player_state WHERE player_pawn_id = %s LIMIT 1",
|
||||
[pawn_id], one=True
|
||||
)
|
||||
if controller_row:
|
||||
from app.services.player import PlayerService
|
||||
ps = PlayerService(self.db)
|
||||
if ps.is_online(controller_row['player_controller_id']):
|
||||
return False, "Player must be offline to edit vitals. Log out first."
|
||||
|
||||
health = max(0.0, float(current_health)) if current_health is not None else None
|
||||
max_h = max(0.0, float(max_health)) if max_health is not None else None
|
||||
hydration = max(0.0, float(current_hydration))
|
||||
spice = max(0.0, float(current_spice))
|
||||
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if health is not None:
|
||||
cur.execute(
|
||||
"UPDATE dune.actors SET properties = jsonb_set(properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float)) WHERE id = %s",
|
||||
[health, pawn_id]
|
||||
)
|
||||
if max_h is not None:
|
||||
cur.execute(
|
||||
"UPDATE dune.actors SET properties = jsonb_set(properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float)) WHERE id = %s",
|
||||
[max_h, pawn_id]
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE dune.actors SET gas_attributes = jsonb_set("
|
||||
" jsonb_set(jsonb_set(jsonb_set(gas_attributes, "
|
||||
" '{DuneHydrationAttributeSet,CurrentHydration,CurrentValue}', to_jsonb(%s::float)), "
|
||||
" '{DuneHydrationAttributeSet,CurrentHydration,BaseValue}', to_jsonb(%s::float)), "
|
||||
" '{DuneSpiceAddictionAttributeSet,CurrentSpice,CurrentValue}', to_jsonb(%s::float)), "
|
||||
" '{DuneSpiceAddictionAttributeSet,CurrentSpice,BaseValue}', to_jsonb(%s::float)) "
|
||||
"WHERE id = %s",
|
||||
[hydration, hydration, spice, spice, pawn_id]
|
||||
)
|
||||
conn.commit()
|
||||
return True, {"health": health, "max_health": max_h, "hydration": hydration, "spice": spice}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to edit vitals for pawn {pawn_id}: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def detect_player_ips(self, namespace):
|
||||
out, err, rc = self.ssh.run(f'sudo kubectl get pods -n {namespace} -o name 2>/dev/null')
|
||||
if rc != 0 or not out:
|
||||
return False, "Failed to list pods"
|
||||
|
||||
game_pods = []
|
||||
for line in out.strip().split('\n'):
|
||||
pod = line.replace('pod/', '').strip()
|
||||
if '-sg-' in pod and '-pod-' in pod:
|
||||
map_name = pod.split('-sg-')[-1].split('-pod-')[0] if '-sg-' in pod else 'Unknown'
|
||||
game_pods.append((pod, map_name))
|
||||
|
||||
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)
|
||||
if not out_logs:
|
||||
continue
|
||||
|
||||
log_files = [l.strip() for l in out_logs.strip().split('\n') if l.strip()]
|
||||
for log_file in log_files:
|
||||
cat_cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- cat "{log_file}" 2>/dev/null'
|
||||
out, err, rc = self.ssh.run(cat_cmd)
|
||||
if not out:
|
||||
continue
|
||||
|
||||
ip_to_player = {}
|
||||
current_ip = None
|
||||
|
||||
for line in out.split('\n'):
|
||||
ip_match = re.search(r'RemoteAddr:\s*([0-9.]+):(\d+)', line)
|
||||
if ip_match:
|
||||
current_ip = ip_match.group(1)
|
||||
continue
|
||||
|
||||
if 'Login request:' in line and current_ip:
|
||||
name_match = re.search(r'Name=([^?#]+)', line)
|
||||
if name_match:
|
||||
current_player = name_match.group(1).split('#')[0]
|
||||
if current_player and current_ip and current_ip != '65.21.198.100':
|
||||
ip_to_player[current_ip] = current_player
|
||||
current_ip = None
|
||||
|
||||
if ip_to_player:
|
||||
for ip, name in ip_to_player.items():
|
||||
cur.execute("""
|
||||
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]
|
||||
account_id = row[1]
|
||||
cur.execute("""
|
||||
INSERT INTO dune.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 dune.bans
|
||||
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
|
||||
LIMIT 1
|
||||
""", [pid, account_id], one=True)
|
||||
|
||||
if ban_check:
|
||||
self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP')
|
||||
self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP')
|
||||
|
||||
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 dune.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])
|
||||
|
||||
def emergency_unban(self, ip):
|
||||
self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null')
|
||||
self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null')
|
||||
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 dune.bans b
|
||||
LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id
|
||||
ORDER BY b.banned_at DESC
|
||||
LIMIT %s
|
||||
""", [limit]) or []
|
||||
|
||||
def get_player_ban(self, player_id):
|
||||
return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dune.bans WHERE player_id = %s", [player_id], one=True)
|
||||
|
||||
def get_player_history(self, player_id, limit=20):
|
||||
return self.db.query("""
|
||||
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
|
||||
FROM dune.player_actions
|
||||
WHERE player_id = %s
|
||||
ORDER BY created_at DESC
|
||||
LIMIT %s
|
||||
""", [player_id, limit]) or []
|
||||
|
||||
def create_indexes(self):
|
||||
indexes = [
|
||||
("idx_actors_class", "CREATE INDEX IF NOT EXISTS idx_actors_class ON dune.actors (class)"),
|
||||
("idx_actors_map", "CREATE INDEX IF NOT EXISTS idx_actors_map ON dune.actors (map)"),
|
||||
("idx_actors_owner_account", "CREATE INDEX IF NOT EXISTS idx_actors_owner_account ON dune.actors (owner_account_id)"),
|
||||
("idx_player_state_controller", "CREATE INDEX IF NOT EXISTS idx_player_state_controller ON dune.player_state (player_controller_id)"),
|
||||
("idx_player_state_pawn", "CREATE INDEX IF NOT EXISTS idx_player_state_pawn ON dune.player_state (player_pawn_id)"),
|
||||
("idx_player_state_account", "CREATE INDEX IF NOT EXISTS idx_player_state_account ON dune.player_state (account_id)"),
|
||||
("idx_player_state_online", "CREATE INDEX IF NOT EXISTS idx_player_state_online ON dune.player_state (online_status)"),
|
||||
("idx_guild_members_player", "CREATE INDEX IF NOT EXISTS idx_guild_members_player ON dune.guild_members (player_id)"),
|
||||
("idx_guild_members_guild", "CREATE INDEX IF NOT EXISTS idx_guild_members_guild ON dune.guild_members (guild_id)"),
|
||||
("idx_player_faction_actor", "CREATE INDEX IF NOT EXISTS idx_player_faction_actor ON dune.player_faction (actor_id)"),
|
||||
("idx_permission_actor_rank_player", "CREATE INDEX IF NOT EXISTS idx_permission_actor_rank_player ON dune.permission_actor_rank (player_id)"),
|
||||
("idx_permission_actor_rank_actor", "CREATE INDEX IF NOT EXISTS idx_permission_actor_rank_actor ON dune.permission_actor_rank (permission_actor_id)"),
|
||||
("idx_buildings_owner", "CREATE INDEX IF NOT EXISTS idx_buildings_owner ON dune.buildings (owner_id)"),
|
||||
("idx_inventories_actor", "CREATE INDEX IF NOT EXISTS idx_inventories_actor ON dune.inventories (actor_id)"),
|
||||
("idx_items_inventory", "CREATE INDEX IF NOT EXISTS idx_items_inventory ON dune.items (inventory_id)"),
|
||||
("idx_specialization_tracks_player", "CREATE INDEX IF NOT EXISTS idx_specialization_tracks_player ON dune.specialization_tracks (player_id)"),
|
||||
("idx_player_faction_reputation_actor", "CREATE INDEX IF NOT EXISTS idx_player_faction_reputation_actor ON dune.player_faction_reputation (actor_id)"),
|
||||
("idx_player_virtual_currency_controller", "CREATE INDEX IF NOT EXISTS idx_player_virtual_currency_controller ON dune.player_virtual_currency_balances (player_controller_id)"),
|
||||
]
|
||||
|
||||
created = []
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, [], "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for name, sql in indexes:
|
||||
try:
|
||||
cur.execute(sql)
|
||||
created.append(name)
|
||||
except Exception as e:
|
||||
logger.warning(f"Index {name} failed: {e}")
|
||||
conn.commit()
|
||||
return True, created, None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create indexes: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, [], str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Chat service - chat history and log parsing"""
|
||||
|
||||
import json
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(self, db_service, k8s_service, ssh_service, cache):
|
||||
self.db = db_service
|
||||
self.k8s = k8s_service
|
||||
self.ssh = ssh_service
|
||||
self.cache = cache
|
||||
self.ensured_table = False
|
||||
|
||||
def ensure_history_table(self):
|
||||
if self.ensured_table:
|
||||
return True
|
||||
try:
|
||||
self.db.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.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
|
||||
)
|
||||
""")
|
||||
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dune.chat_history (timestamp DESC)")
|
||||
self.ensured_table = True
|
||||
logger.info("Chat history table ready")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create chat history table: {e}")
|
||||
return False
|
||||
|
||||
def save_message(self, channel, sender, message, target='', location=None, is_admin=False):
|
||||
loc_x = location.get('X', 0) if location else 0
|
||||
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 dune.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])
|
||||
|
||||
def save_messages_batch(self, messages):
|
||||
if not messages:
|
||||
return 0
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return 0
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for msg in messages:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.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'],
|
||||
msg.get('target', ''),
|
||||
msg.get('location', {}).get('X', 0),
|
||||
msg.get('location', {}).get('Y', 0),
|
||||
msg.get('location', {}).get('Z', 0),
|
||||
msg.get('is_admin', False)
|
||||
])
|
||||
conn.commit()
|
||||
return len(messages)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save chat messages batch: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return 0
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def get_history(self, limit=200):
|
||||
return self.db.query("""
|
||||
SELECT id, timestamp, channel, sender, message, target,
|
||||
location_x, location_y, location_z, is_admin
|
||||
FROM dune.chat_history
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT %s
|
||||
""", [limit])
|
||||
|
||||
def catch_up(self, namespace):
|
||||
db_messages = self.get_history(1)
|
||||
has_history = db_messages and len(db_messages) >= 10
|
||||
if has_history:
|
||||
return 0
|
||||
|
||||
pod_name = self.k8s.get_text_router_pod()
|
||||
if not pod_name:
|
||||
logger.warning("Cannot catch up - no text-router pod found")
|
||||
return 0
|
||||
|
||||
out, err, rc = self.ssh.run(
|
||||
f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null | "
|
||||
"grep 'CLOG.*TextChat' | grep -v 'Starting filtering' | grep -v 'Skipping filtering' | grep -v 'Redirected message'",
|
||||
timeout=30
|
||||
)
|
||||
|
||||
messages = []
|
||||
seen = set()
|
||||
for line in (out or '').strip().split('\n'):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
idx = line.index('received message from ')
|
||||
rest = line[idx + len('received message from '):]
|
||||
parts = rest.split(' to ', 1)
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
sender_id = parts[0].strip()
|
||||
target_and_json = parts[1]
|
||||
target_idx = target_and_json.index(': ')
|
||||
target = target_and_json[:target_idx].strip()
|
||||
msg_str = target_and_json[target_idx + 2:].strip()
|
||||
|
||||
msg_data = json.loads(msg_str)
|
||||
content = json.loads(msg_data.get('content', '{}'))
|
||||
|
||||
dedup_key = (
|
||||
content.get('m_ChannelType', ''),
|
||||
content.get('m_FuncomIdFrom', ''),
|
||||
content.get('m_Message', {}).get('m_UnlocalizedMessage', ''),
|
||||
)
|
||||
if dedup_key in seen:
|
||||
continue
|
||||
seen.add(dedup_key)
|
||||
|
||||
messages.append({
|
||||
'channel': content.get('m_ChannelType', 'Unknown'),
|
||||
'sender': content.get('m_FuncomIdFrom', sender_id),
|
||||
'message': content.get('m_Message', {}).get('m_UnlocalizedMessage', ''),
|
||||
'target': target,
|
||||
'location': content.get('m_OriginLocation', {}),
|
||||
'is_admin': False,
|
||||
})
|
||||
except (ValueError, KeyError, json.JSONDecodeError, IndexError):
|
||||
continue
|
||||
|
||||
if messages:
|
||||
saved = self.save_messages_batch(messages)
|
||||
logger.info(f"Caught up {saved} chat messages from pod logs")
|
||||
return saved
|
||||
return 0
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Database service - connection pool and query helpers"""
|
||||
|
||||
import logging
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
import psycopg2.pool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DatabaseService:
|
||||
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.pool = None
|
||||
|
||||
def init_pool(self):
|
||||
if self.pool is None:
|
||||
try:
|
||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||
minconn=self.min_conn,
|
||||
maxconn=self.max_conn,
|
||||
**self.db_config
|
||||
)
|
||||
logger.info("Database connection pool initialized")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize database pool: {e}")
|
||||
self.pool = None
|
||||
return self.pool
|
||||
|
||||
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(f"Failed to get database connection: {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(f"Error closing pool: {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(f"Database query error: {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(f"Database execute error: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.return_connection(conn)
|
||||
|
||||
def execute_with_conn(self, conn, sql, params=None):
|
||||
cur = conn.cursor()
|
||||
try:
|
||||
cur.execute(sql, params)
|
||||
return cur
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
|
||||
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:
|
||||
return False
|
||||
|
||||
def ensure_tables(self):
|
||||
conn = self.get_connection()
|
||||
if not conn:
|
||||
return
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.player_ips (
|
||||
player_id BIGINT PRIMARY KEY,
|
||||
ip_address INET NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
)
|
||||
""")
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.bans (
|
||||
id SERIAL PRIMARY KEY,
|
||||
player_id BIGINT UNIQUE,
|
||||
account_id BIGINT,
|
||||
reason TEXT DEFAULT '',
|
||||
note TEXT DEFAULT '',
|
||||
duration INT DEFAULT 0,
|
||||
banned_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMP,
|
||||
active BOOLEAN DEFAULT TRUE
|
||||
)
|
||||
""")
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.player_actions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
player_id BIGINT NOT NULL,
|
||||
action_type VARCHAR(50) NOT NULL,
|
||||
reason TEXT DEFAULT '',
|
||||
note TEXT DEFAULT '',
|
||||
duration_minutes INT DEFAULT 0,
|
||||
ip_address INET,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
logger.info("Dashboard tables ensured (player_ips, bans, player_actions)")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to ensure dashboard tables: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.return_connection(conn)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Kubernetes service - kubectl operations via SSH"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class K8sService:
|
||||
def __init__(self, ssh_service, namespace):
|
||||
self.ssh = ssh_service
|
||||
self.namespace = namespace
|
||||
|
||||
def run(self, kubectl_command, timeout=30):
|
||||
full_cmd = f'sudo kubectl {kubectl_command} -n {self.namespace}'
|
||||
return self.ssh.run(full_cmd, timeout=timeout)
|
||||
|
||||
def get_pods(self):
|
||||
out, err, rc = self.run('get pods -o name')
|
||||
if rc != 0:
|
||||
logger.error(f"Failed to get pods: {err}")
|
||||
return []
|
||||
return [line.replace('pod/', '').strip() for line in (out or '').strip().split('\n') if line.strip()]
|
||||
|
||||
def find_pod_by_pattern(self, pattern):
|
||||
pods = self.get_pods()
|
||||
for pod in pods:
|
||||
if pattern.lower() in pod.lower():
|
||||
return pod
|
||||
return None
|
||||
|
||||
def get_text_router_pod(self):
|
||||
pod = self.find_pod_by_pattern('tr-deploy')
|
||||
if pod:
|
||||
return pod
|
||||
pod = self.find_pod_by_pattern('text')
|
||||
if pod:
|
||||
return pod
|
||||
pod = self.find_pod_by_pattern('router')
|
||||
return pod
|
||||
|
||||
def get_rabbitmq_pod(self):
|
||||
pod = self.find_pod_by_pattern('mq-admin')
|
||||
if pod:
|
||||
return pod
|
||||
pod = self.find_pod_by_pattern('mq-game')
|
||||
return pod
|
||||
|
||||
def get_deployments(self):
|
||||
out, err, rc = self.run('get deployments -o name')
|
||||
if rc != 0:
|
||||
return []
|
||||
return [d.strip() for d in (out or '').strip().split('\n') if d.strip()]
|
||||
|
||||
def get_node_metrics(self):
|
||||
out, err, rc = self.run('top nodes')
|
||||
if rc == 0 and out.strip():
|
||||
lines = out.strip().split('\n')
|
||||
if len(lines) >= 2:
|
||||
parts = lines[1].split()
|
||||
if len(parts) >= 4:
|
||||
return {
|
||||
'cpu': parts[2],
|
||||
'memory': parts[3],
|
||||
'cpu_pct': parts[1]
|
||||
}
|
||||
return {}
|
||||
|
||||
def auto_detect_namespace(self):
|
||||
out, err, rc = self.ssh.run('sudo kubectl get namespaces -o name', timeout=10)
|
||||
if rc == 0:
|
||||
for line in (out or '').strip().split('\n'):
|
||||
ns = line.replace('namespace/', '').strip()
|
||||
if ns.startswith('funcom-seabass-'):
|
||||
logger.info(f"Auto-detected K8s namespace: {ns}")
|
||||
self.namespace = ns
|
||||
return ns
|
||||
return None
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Player service - player queries and operations"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LIKE_PC = '%DunePlayerCharacter_C'
|
||||
|
||||
|
||||
class PlayerService:
|
||||
def __init__(self, db_service):
|
||||
self.db = db_service
|
||||
|
||||
def is_online(self, player_controller_id):
|
||||
result = self.db.query(
|
||||
"SELECT 1 FROM dune.player_state WHERE player_controller_id = %s AND online_status::text = 'Online' LIMIT 1",
|
||||
[player_controller_id],
|
||||
one=True
|
||||
)
|
||||
return bool(result)
|
||||
|
||||
def get_overview_counts(self):
|
||||
return self.db.query("""
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM dune.accounts) as account_count,
|
||||
(SELECT COUNT(*) FROM dune.player_state) as player_count,
|
||||
(SELECT COUNT(*) FROM dune.vehicles) as vehicle_count,
|
||||
(SELECT COUNT(*) FROM dune.buildings) as building_count,
|
||||
(SELECT COUNT(*) FROM dune.guilds) as guild_count,
|
||||
(SELECT COUNT(*) FROM dune.actors) as actor_count,
|
||||
(SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') as online_count
|
||||
""", one=True)
|
||||
|
||||
def get_faction_distribution(self):
|
||||
return self.db.query("""
|
||||
SELECT f.name, COUNT(pf.actor_id)::int count
|
||||
FROM dune.player_faction pf
|
||||
JOIN dune.factions f ON pf.faction_id = f.id
|
||||
GROUP BY f.name
|
||||
ORDER BY count DESC
|
||||
""")
|
||||
|
||||
def get_players_per_map(self):
|
||||
return self.db.query("""
|
||||
SELECT a.map, COUNT(*)::int as count
|
||||
FROM dune.player_state ps
|
||||
JOIN dune.actors a ON ps.player_pawn_id = a.id
|
||||
WHERE a.class LIKE %s AND a.map IS NOT NULL
|
||||
GROUP BY a.map
|
||||
ORDER BY count DESC
|
||||
""", [LIKE_PC])
|
||||
|
||||
def get_players_online(self):
|
||||
return self.db.query("""
|
||||
SELECT ps.character_name, ps.player_pawn_id as pawn_id, a.map,
|
||||
ps.online_status::text as online_status
|
||||
FROM dune.player_state ps
|
||||
JOIN dune.actors a ON ps.player_pawn_id = a.id
|
||||
WHERE ps.online_status::text = 'Online'
|
||||
ORDER BY ps.character_name
|
||||
""")
|
||||
|
||||
def get_players_list(self, search='', faction_id='', guild_id='', map_filter='', online_filter='', limit=200):
|
||||
where = ["a.class LIKE %s"]
|
||||
params = [LIKE_PC]
|
||||
|
||||
if search:
|
||||
where.append("""(
|
||||
ps.character_name ILIKE %s
|
||||
OR acc.funcom_id ILIKE %s
|
||||
OR ea.user ILIKE %s
|
||||
OR a.properties::text ILIKE %s
|
||||
)""")
|
||||
params.extend([f'%{search}%'] * 4)
|
||||
if faction_id:
|
||||
where.append("pf.faction_id = %s")
|
||||
params.append(faction_id)
|
||||
if guild_id:
|
||||
where.append("gm.guild_id = %s")
|
||||
params.append(guild_id)
|
||||
if map_filter:
|
||||
where.append("a.map = %s")
|
||||
params.append(map_filter)
|
||||
if online_filter == 'online':
|
||||
where.append("ps.online_status::text = 'Online'")
|
||||
elif online_filter == 'offline':
|
||||
where.append("ps.online_status::text = 'Offline'")
|
||||
|
||||
where_clause = ' AND '.join(where)
|
||||
players = self.db.query(f"""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
||||
ps.online_status::text as online_status,
|
||||
ps.life_state::text as life_state,
|
||||
ps.last_login_time,
|
||||
ps.last_avatar_activity,
|
||||
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
|
||||
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
|
||||
LEFT JOIN dune.player_state ps ON a.owner_account_id = ps.account_id AND a.id = ps.player_pawn_id
|
||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.actor_id
|
||||
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 dune.player_ips pi ON ps.player_controller_id = pi.player_id
|
||||
WHERE {where_clause}
|
||||
ORDER BY player_name
|
||||
LIMIT %s
|
||||
""", params + [limit])
|
||||
|
||||
if not players:
|
||||
return []
|
||||
|
||||
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
|
||||
actor_ids = [p.get('id') for p in players if p.get('id')]
|
||||
|
||||
vehicle_counts = {}
|
||||
if player_ids:
|
||||
vc = self.db.query("""
|
||||
SELECT par.player_id, COUNT(DISTINCT par.permission_actor_id)::int as cnt
|
||||
FROM dune.permission_actor_rank par
|
||||
JOIN dune.vehicles v ON par.permission_actor_id = v.id
|
||||
WHERE par.rank = 1 AND par.player_id = ANY(%s)
|
||||
GROUP BY par.player_id
|
||||
""", [player_ids])
|
||||
vehicle_counts = {r['player_id']: r['cnt'] for r in (vc or []) if r.get('player_id')}
|
||||
|
||||
building_counts = {}
|
||||
if actor_ids:
|
||||
bc = self.db.query("""
|
||||
SELECT owner_id, COUNT(*)::int as cnt
|
||||
FROM dune.buildings
|
||||
WHERE owner_id = ANY(%s)
|
||||
GROUP BY owner_id
|
||||
""", [actor_ids])
|
||||
building_counts = {r['owner_id']: r['cnt'] for r in (bc or []) if r.get('owner_id')}
|
||||
|
||||
for p in players:
|
||||
pid = p.get('player_controller_id') or p.get('id')
|
||||
p['vehicle_count'] = vehicle_counts.get(pid, 0)
|
||||
p['building_count'] = building_counts.get(p.get('id'), 0)
|
||||
|
||||
return players
|
||||
|
||||
def get_player_detail(self, player_id):
|
||||
player = self.db.query("""
|
||||
SELECT a.*, a.transform::text as transform_text,
|
||||
ea.id as account_id, ea.user as account_email, ea.platform_id,
|
||||
acc.funcom_id,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
||||
ps.online_status::text as online_status,
|
||||
ps.life_state::text as life_state,
|
||||
ps.last_login_time,
|
||||
ps.last_avatar_activity,
|
||||
ps.player_controller_id,
|
||||
ps.player_pawn_id as state_pawn_id,
|
||||
f.name as faction_name, pf.faction_id, pf.utc_time_faction_change
|
||||
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
|
||||
LEFT JOIN dune.player_state ps ON a.owner_account_id = ps.account_id AND a.id = ps.player_pawn_id
|
||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.actor_id
|
||||
LEFT JOIN dune.factions f ON pf.faction_id = f.id
|
||||
WHERE a.id = %s AND a.class LIKE %s
|
||||
""", [player_id, LIKE_PC], one=True)
|
||||
return player
|
||||
|
||||
def get_player_vitals(self, state_pawn_id):
|
||||
if not state_pawn_id:
|
||||
return {}
|
||||
try:
|
||||
return self.db.query("""
|
||||
SELECT
|
||||
(properties->'DamageableActorComponent'->>'m_CurrentMaxHealth')::float as current_health,
|
||||
(properties->'DamageableActorComponent'->>'m_TotalMaxHealth')::float as max_health,
|
||||
(gas_attributes->'DuneHydrationAttributeSet'->'CurrentHydration'->>'CurrentValue')::float as current_hydration,
|
||||
(gas_attributes->'DuneHydrationAttributeSet'->'DehydrationPenalty'->>'CurrentValue')::float as dehydration_penalty,
|
||||
(gas_attributes->'DuneSpiceAddictionAttributeSet'->'CurrentSpice'->>'CurrentValue')::float as current_spice,
|
||||
(gas_attributes->'DuneSpiceAddictionAttributeSet'->'SpiceAddictionLevel'->'CurrentValue'->>'Value')::float as spice_addiction_level,
|
||||
(gas_attributes->'DuneSpiceAddictionAttributeSet'->'SpiceTolerance'->'CurrentValue'->>'Value')::float as spice_tolerance
|
||||
FROM dune.actors WHERE id = %s
|
||||
""", [state_pawn_id], one=True) or {}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get vitals: {e}")
|
||||
return {}
|
||||
|
||||
def get_player_guild(self, player_controller_id):
|
||||
return self.db.query("""
|
||||
SELECT g.guild_id, g.guild_name, g.guild_description, f.name as faction_name, gm.role_id
|
||||
FROM dune.guild_members gm
|
||||
JOIN dune.guilds g ON gm.guild_id = g.guild_id
|
||||
LEFT JOIN dune.factions f ON g.guild_faction = f.id
|
||||
WHERE gm.player_id = %s
|
||||
""", [player_controller_id], one=True)
|
||||
|
||||
def get_player_vehicles(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
return self.db.query("""
|
||||
SELECT v_a.id, v_a.class, v_a.map, v_a.transform::text as transform_text,
|
||||
pa.actor_name,
|
||||
par.rank as ownership_rank
|
||||
FROM dune.permission_actor_rank par
|
||||
JOIN dune.vehicles v ON par.permission_actor_id = v.id
|
||||
JOIN dune.actors v_a ON v.id = v_a.id
|
||||
LEFT JOIN dune.permission_actor pa ON v.id = pa.actor_id AND pa.is_child = FALSE
|
||||
WHERE par.player_id = %s
|
||||
ORDER BY v_a.class
|
||||
""", [player_controller_id]) or []
|
||||
|
||||
def get_player_buildings(self, player_id):
|
||||
try:
|
||||
return self.db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
|
||||
FROM dune.buildings b
|
||||
JOIN dune.actors a ON b.id = a.id
|
||||
WHERE b.owner_id = %s
|
||||
ORDER BY a.map
|
||||
""", [player_id]) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_currency(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT pvcb.currency_id, pvcb.balance FROM dune.player_virtual_currency_balances pvcb WHERE pvcb.player_controller_id = %s",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_inventories(self, player_id):
|
||||
try:
|
||||
inventories = self.db.query("""
|
||||
SELECT i.id, i.actor_id, i.inventory_type,
|
||||
COALESCE(json_agg(
|
||||
json_build_object(
|
||||
'id', items.id,
|
||||
'template_id', items.template_id,
|
||||
'stack_size', items.stack_size,
|
||||
'quality_level', items.quality_level,
|
||||
'is_new', items.is_new,
|
||||
'stats_text', items.stats::text
|
||||
) ORDER BY items.position_index
|
||||
) FILTER (WHERE items.id IS NOT NULL), '[]') as item_list
|
||||
FROM dune.inventories i
|
||||
LEFT JOIN dune.items ON i.id = items.inventory_id
|
||||
WHERE i.actor_id = %s
|
||||
GROUP BY i.id, i.actor_id, i.inventory_type
|
||||
ORDER BY i.inventory_type
|
||||
""", [player_id]) or []
|
||||
for inv in inventories:
|
||||
inv['item_list'] = inv.get('item_list', []) or []
|
||||
return inventories
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get inventories: {e}")
|
||||
inventories = self.db.query(
|
||||
"SELECT i.* FROM dune.inventories i WHERE i.actor_id = %s ORDER BY i.inventory_type",
|
||||
[player_id]
|
||||
) or []
|
||||
for inv in inventories:
|
||||
inv['item_list'] = []
|
||||
return inventories
|
||||
|
||||
def get_player_landclaims(self, owner_account_id):
|
||||
try:
|
||||
return self.db.query("""
|
||||
SELECT DISTINCT a.id, a.class, a.map, a.transform::text as transform_text
|
||||
FROM dune.landclaim_segments lcs
|
||||
JOIN dune.actors a ON lcs.totem_id = a.id
|
||||
WHERE a.owner_account_id = %s
|
||||
""", [owner_account_id]) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_specialization(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT track_type, xp_amount, level FROM dune.specialization_tracks WHERE player_id = %s",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_tech_knowledge(self, player_id):
|
||||
try:
|
||||
tech_row = self.db.query(
|
||||
"SELECT (properties->'TechKnowledgePlayerComponent'->>'m_TechKnowledgePoints')::int as xp_points FROM dune.actors WHERE id = %s",
|
||||
[player_id], one=True
|
||||
)
|
||||
return tech_row['xp_points'] if tech_row else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def get_player_keystones(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT ks.id, ks.name FROM dune.purchased_specialization_keystones psk JOIN dune.specialization_keystones_map ks ON psk.keystone_id = ks.id WHERE psk.player_id = %s ORDER BY ks.id",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_faction_reputation(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT pfr.faction_id, f.name as faction_name, pfr.reputation_amount FROM dune.player_faction_reputation pfr JOIN dune.factions f ON pfr.faction_id = f.id WHERE pfr.actor_id = %s ORDER BY pfr.faction_id",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_landsraad(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return {}
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT (properties->'LandsraadCharacterComponent'->>'m_DailyRewardCharges')::int as daily_reward_charges, "
|
||||
"(properties->'LandsraadCharacterComponent'->>'m_LastViewedLandsraadTermId')::int as last_viewed_term_id, "
|
||||
"(properties->'LandsraadCharacterComponent'->>'m_DailyRewardLastProcessedTimestamp')::bigint as daily_reward_last_processed "
|
||||
"FROM dune.actors WHERE id = %s",
|
||||
[player_controller_id], one=True
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
@@ -0,0 +1,43 @@
|
||||
"""SSH service - remote command execution"""
|
||||
|
||||
import subprocess
|
||||
import logging
|
||||
import os
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SSHService:
|
||||
def __init__(self, host, user, ssh_key=None):
|
||||
self.host = host
|
||||
self.user = user
|
||||
self.ssh_key = ssh_key
|
||||
|
||||
def run(self, command, timeout=30):
|
||||
args = [
|
||||
'ssh',
|
||||
'-i', self.ssh_key,
|
||||
'-o', 'StrictHostKeyChecking=accept-new',
|
||||
'-o', 'ConnectTimeout=10',
|
||||
'-o', 'BatchMode=yes',
|
||||
f'{self.user}@{self.host}',
|
||||
command
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout
|
||||
)
|
||||
return result.stdout, result.stderr, result.returncode
|
||||
except FileNotFoundError:
|
||||
return '', 'ssh command not found', -1
|
||||
except subprocess.TimeoutExpired:
|
||||
return '', 'SSH command timed out', -1
|
||||
except Exception as ex:
|
||||
return '', str(ex), -1
|
||||
|
||||
def check_connection(self):
|
||||
out, err, rc = self.run('echo ok', timeout=5)
|
||||
return rc == 0 and 'ok' in out
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Vehicle service - vehicle queries and operations"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VEHICLE_TYPE_MAP = {
|
||||
'BP_MediumOrnithopter_CHOAM': 'Medium Ornithopter',
|
||||
'BP_TransportOrnithopter_CHOAM': 'Transport Ornithopter',
|
||||
'BP_Buggy_CHOAM': 'Buggy',
|
||||
'BP_LightOrnithopter_Choam': 'Light Ornithopter',
|
||||
'BP_Sandbike_CHOAM': 'Sandbike',
|
||||
}
|
||||
|
||||
TYPE_CONFIGS = {
|
||||
'Ornithopter': {
|
||||
'base': {'Chassis': 2200, 'Engine': 2000, 'Generator': 2000, 'Hull': 1650, 'HullFront': 1650, 'HullBack': 1650, 'Locomotion': 2000, 'Boost': 2000, 'Launcher': 2000},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'HullFront': 'Cockpit', 'HullBack': 'Tail', 'Locomotion': 'Wing', 'Boost': 'Boost', 'Launcher': 'Launcher'}
|
||||
},
|
||||
'Transport': {
|
||||
'base': {'Chassis': 2200, 'Engine': 2000, 'Generator': 2000, 'Hull': 1650, 'HullFront': 1650, 'HullBack': 1650, 'Locomotion': 2000},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'HullFront': 'Main Hull', 'HullBack': 'Tail Hull', 'Locomotion': 'Wing'}
|
||||
},
|
||||
'Buggy': {
|
||||
'base': {'Chassis': 3500, 'Engine': 1750, 'Generator': 1750, 'Hull': 2625, 'HullFront': 2625, 'HullBack': 2625, 'Locomotion': 1750},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'PSU', 'Hull': 'Hull', 'HullFront': 'Front', 'HullBack': 'Rear', 'Locomotion': 'Tread'}
|
||||
},
|
||||
'Sandcrawler': {
|
||||
'base': {'Chassis': 4250, 'Hull': 3187, 'Locomotion': 2500, 'SpiceHeader': 2500, 'Generator': 2500, 'Engine': 2500, 'SpiceContainer': 3200},
|
||||
'names': {'Chassis': 'Chassis', 'Hull': 'Hull', 'Locomotion': 'Tread', 'SpiceHeader': 'Spice Header', 'Generator': 'PSU', 'Engine': 'Engine', 'SpiceContainer': 'Spice Container'}
|
||||
},
|
||||
'Sandbike': {
|
||||
'base': {'Chassis': 1500, 'Engine': 1200, 'Generator': 1200, 'Hull': 1000, 'Locomotion': 1200},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'Locomotion': 'Wheel'}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def vehicle_type_name(cls):
|
||||
if '/' in cls:
|
||||
short = cls.split('/')[-1].replace('_C', '')
|
||||
for key, name in VEHICLE_TYPE_MAP.items():
|
||||
if key in short:
|
||||
return name
|
||||
return short.replace('BP_', '').replace('_CHOAM', '').replace('_Choam', '').replace('_', ' ')
|
||||
return cls
|
||||
|
||||
|
||||
def get_vehicle_type_config(vehicle_class):
|
||||
type_order = ['Sandcrawler', 'Sandbike', 'Buggy', 'Transport', 'Ornithopter', 'Light', 'Medium']
|
||||
for t in type_order:
|
||||
if t in vehicle_class:
|
||||
return TYPE_CONFIGS.get(t, TYPE_CONFIGS['Buggy'])
|
||||
return TYPE_CONFIGS['Buggy']
|
||||
|
||||
|
||||
def parse_vehicle_modules(modules, vehicle_class):
|
||||
config = get_vehicle_type_config(vehicle_class)
|
||||
parsed = []
|
||||
for m in modules:
|
||||
stats = m.get('stats', {})
|
||||
durability = stats.get('FVehicleModuleDurabilityStats', [{}])[1] if stats.get('FVehicleModuleDurabilityStats') else {}
|
||||
current = durability.get('CurrentDurability', 0)
|
||||
max_durability = durability.get('MaxDurability') or durability.get('DecayedMaxDurability') or current
|
||||
|
||||
template = m.get('template_id', '')
|
||||
mod_clean = template.replace('Ornithopter', '').replace('Buggy', '').replace('Sandcrawler', '').replace('Sandbike', '').replace('_6', '').replace('_0', '')
|
||||
mod_type = mod_clean.replace('Medium', '').replace('Transport', '').replace('Light', '').replace('Heavy', '').replace('Front', '').replace('Back', '').replace('Left', '').replace('Right', '').replace('Center', '').replace('1', '').replace('2', '')
|
||||
name = config['names'].get(mod_type, mod_clean)
|
||||
|
||||
parsed.append({
|
||||
'id': m['id'],
|
||||
'name': name,
|
||||
'template': template,
|
||||
'current': round(current, 1),
|
||||
'max': round(max_durability, 1),
|
||||
'damage_cause': durability.get('LastDeteriorationCause', '')
|
||||
})
|
||||
return parsed
|
||||
|
||||
|
||||
class VehicleService:
|
||||
def __init__(self, db_service):
|
||||
self.db = db_service
|
||||
|
||||
def get_all_vehicles(self, limit=200):
|
||||
return self.db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
pa.actor_name,
|
||||
pilot_ps.character_name as pilot_name,
|
||||
pilot_a.id as pilot_pawn_id,
|
||||
ps_owner.character_name as owner_name,
|
||||
ps_owner.player_pawn_id as owner_pawn_id,
|
||||
par.rank as owner_rank
|
||||
FROM dune.actors a
|
||||
JOIN dune.vehicles v ON a.id = v.id
|
||||
LEFT JOIN dune.permission_actor pa ON a.id = pa.actor_id AND pa.is_child = FALSE
|
||||
LEFT JOIN dune.actors pilot_a ON pilot_a.properties->'BP_DunePlayerCharacter_C'->>'m_CurrentVehicleId' = CONCAT('!!act#', a.id::text)
|
||||
AND (pilot_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving')::boolean = TRUE
|
||||
LEFT JOIN dune.player_state pilot_ps ON pilot_a.owner_account_id = pilot_ps.account_id AND pilot_a.id = pilot_ps.player_pawn_id
|
||||
LEFT JOIN dune.permission_actor_rank par ON a.id = par.permission_actor_id AND par.rank = 1
|
||||
LEFT JOIN dune.player_state ps_owner ON par.player_id = ps_owner.player_controller_id
|
||||
ORDER BY a.class
|
||||
LIMIT %s
|
||||
""", [limit]) or []
|
||||
|
||||
def get_vehicle(self, vehicle_id):
|
||||
return self.db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
pa.actor_name,
|
||||
ps.character_name as owner_name,
|
||||
ps.player_pawn_id as owner_pawn_id
|
||||
FROM dune.actors a
|
||||
JOIN dune.vehicles v ON a.id = v.id
|
||||
LEFT JOIN dune.permission_actor pa ON a.id = pa.actor_id AND pa.is_child = FALSE
|
||||
LEFT JOIN dune.permission_actor_rank par ON a.id = par.permission_actor_id AND par.rank = 1
|
||||
LEFT JOIN dune.player_state ps ON par.player_id = ps.player_controller_id
|
||||
WHERE a.id = %s
|
||||
""", [vehicle_id], one=True)
|
||||
|
||||
def get_vehicle_modules(self, vehicle_id):
|
||||
return self.db.query("""
|
||||
SELECT id, template_id, stats
|
||||
FROM dune.vehicle_modules
|
||||
WHERE vehicle_id = %s
|
||||
ORDER BY id
|
||||
""", [vehicle_id]) or []
|
||||
|
||||
def delete_vehicle(self, vehicle_id):
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SET session_replication_role = replica")
|
||||
cur.execute("DELETE FROM dune.vehicles WHERE id = %s RETURNING id", [vehicle_id])
|
||||
deleted = cur.fetchone()
|
||||
if deleted:
|
||||
cur.execute("DELETE FROM dune.actors WHERE id = %s RETURNING id", [vehicle_id])
|
||||
conn.commit()
|
||||
cur.execute("SET session_replication_role = default")
|
||||
return True, f"Vehicle {vehicle_id} deleted"
|
||||
else:
|
||||
conn.rollback()
|
||||
cur.execute("SET session_replication_role = default")
|
||||
return False, "Vehicle not found"
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete vehicle {vehicle_id}: {e}")
|
||||
try:
|
||||
cur.execute("SET session_replication_role = default")
|
||||
except Exception:
|
||||
pass
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
@@ -0,0 +1 @@
|
||||
"""Utils package"""
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Simple TTL-based cache"""
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TTLCache:
|
||||
def __init__(self, ttl_seconds=60):
|
||||
self._data = None
|
||||
self._timestamp = 0
|
||||
self._ttl = ttl_seconds
|
||||
|
||||
def get(self):
|
||||
current_time = datetime.datetime.now().timestamp()
|
||||
if self._data and (current_time - self._timestamp) < self._ttl:
|
||||
return self._data
|
||||
return None
|
||||
|
||||
def set(self, data):
|
||||
self._data = data
|
||||
self._timestamp = datetime.datetime.now().timestamp()
|
||||
|
||||
def invalidate(self):
|
||||
self._data = None
|
||||
self._timestamp = 0
|
||||
|
||||
|
||||
class MultiCache:
|
||||
def __init__(self, ttl_seconds=60):
|
||||
self._cache = {}
|
||||
self._ttl = ttl_seconds
|
||||
|
||||
def get(self, key):
|
||||
entry = self._cache.get(key)
|
||||
if not entry:
|
||||
return None
|
||||
current_time = datetime.datetime.now().timestamp()
|
||||
if (current_time - entry['timestamp']) < self._ttl:
|
||||
return entry['data']
|
||||
return None
|
||||
|
||||
def set(self, key, data):
|
||||
self._cache[key] = {'data': data, 'timestamp': datetime.datetime.now().timestamp()}
|
||||
|
||||
def invalidate(self, key=None):
|
||||
if key:
|
||||
self._cache.pop(key, None)
|
||||
else:
|
||||
self._cache = {}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Shared data constants and helpers"""
|
||||
|
||||
INVENTORY_TYPE_LABELS = {
|
||||
0: 'Main Inventory',
|
||||
1: 'Equipped Items',
|
||||
5: 'Hotbar',
|
||||
12: 'Storage',
|
||||
14: 'Recipes',
|
||||
15: 'Key Items',
|
||||
20: 'Crafting Queue',
|
||||
25: 'Schematics',
|
||||
27: 'Emotes',
|
||||
29: 'Quest Items',
|
||||
30: 'Bank',
|
||||
31: 'Power Pack Slots',
|
||||
32: 'Module Slots',
|
||||
33: 'Augment Slots',
|
||||
}
|
||||
|
||||
CURRENCY_ID_LABELS = {
|
||||
0: 'Solari Credits',
|
||||
1: 'House Script',
|
||||
2: 'Spice',
|
||||
}
|
||||
|
||||
GUILD_ROLES = {100: 'Leader', 90: 'Officer', 80: 'Officer', 50: 'Member', 1: 'Member'}
|
||||
|
||||
NAV_PAGES = [
|
||||
('/', 'Overview'),
|
||||
('/server', 'Server'),
|
||||
('/director', 'Director'),
|
||||
('/shell', 'Shell'),
|
||||
('/files', 'Files'),
|
||||
('/events', 'Events'),
|
||||
('/chat', 'Chat'),
|
||||
('/players', 'Players'),
|
||||
('/vehicles', 'Vehicles'),
|
||||
('/guilds', 'Guilds'),
|
||||
('/buildings', 'Buildings'),
|
||||
('/admin', 'Admin'),
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
"""WebSocket handlers package"""
|
||||
@@ -0,0 +1,124 @@
|
||||
"""WebSocket shell handler - interactive terminal via SSH"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
import logging
|
||||
|
||||
try:
|
||||
import paramiko
|
||||
HAS_PARAMIKO = True
|
||||
except ImportError:
|
||||
HAS_PARAMIKO = False
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
shell_processes = {}
|
||||
|
||||
|
||||
def register_websocket_handlers(socketio, settings):
|
||||
if not HAS_PARAMIKO:
|
||||
logger.warning("Paramiko not installed. WebSocket shell disabled.")
|
||||
return
|
||||
|
||||
@socketio.on('shell_create')
|
||||
def handle_shell_create(data):
|
||||
shell_type = data.get('type', 'vm')
|
||||
shell_id = request.sid
|
||||
|
||||
try:
|
||||
ssh_key = _find_ssh_key(settings)
|
||||
if not ssh_key:
|
||||
return emit('shell_created', {'success': False, 'error': 'SSH key not found'})
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.WarningPolicy())
|
||||
|
||||
server_host = settings['server']['host']
|
||||
server_user = settings['server']['user']
|
||||
|
||||
if shell_type == 'vm':
|
||||
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
|
||||
chan = client.invoke_shell(term='xterm-256color', width=80, height=24)
|
||||
else:
|
||||
namespace = settings['kubernetes']['namespace']
|
||||
pod = data.get('pod', '')
|
||||
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
|
||||
transport = client.get_transport()
|
||||
chan = transport.open_session()
|
||||
chan.get_pty(term='xterm-256color', width=80, height=24)
|
||||
chan.exec_command(f'sudo kubectl exec -it {pod} -n {namespace} -- /bin/bash')
|
||||
|
||||
shell_processes[shell_id] = {'client': client, 'channel': chan, 'type': shell_type}
|
||||
|
||||
def read_channel():
|
||||
time.sleep(0.5)
|
||||
socketio.emit('shell_output', {'data': '\r\nConnected. Press Enter...\r\n', 'type': 'stdout', 'target': shell_type}, room=shell_id)
|
||||
while shell_id in shell_processes:
|
||||
try:
|
||||
while chan.recv_ready():
|
||||
data = chan.recv(65535).decode('utf-8', errors='replace')
|
||||
if data:
|
||||
socketio.emit('shell_output', {'data': data, 'type': 'stdout', 'target': shell_type}, room=shell_id)
|
||||
while chan.recv_stderr_ready():
|
||||
data = chan.recv_stderr(65535).decode('utf-8', errors='replace')
|
||||
if data:
|
||||
socketio.emit('shell_output', {'data': data, 'type': 'stderr', 'target': shell_type}, room=shell_id)
|
||||
if chan.closed:
|
||||
socketio.emit('shell_output', {'data': '\r\n[Disconnected]\r\n', 'type': 'stdout', 'target': shell_type}, room=shell_id)
|
||||
break
|
||||
except Exception:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
threading.Thread(target=read_channel, daemon=True).start()
|
||||
socketio.emit('shell_created', {'success': True, 'shell_id': shell_id}, room=shell_id)
|
||||
except Exception as e:
|
||||
socketio.emit('shell_created', {'success': False, 'error': str(e)}, room=shell_id)
|
||||
|
||||
@socketio.on('shell_input')
|
||||
def handle_shell_input(data):
|
||||
shell_id = request.sid
|
||||
if shell_id in shell_processes:
|
||||
try:
|
||||
chan = shell_processes[shell_id]['channel']
|
||||
if chan and chan.send_ready():
|
||||
chan.send(data.get('data', ''))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@socketio.on('shell_disconnect')
|
||||
def handle_shell_disconnect():
|
||||
shell_id = request.sid
|
||||
if shell_id in shell_processes:
|
||||
try:
|
||||
if 'client' in shell_processes[shell_id]:
|
||||
shell_processes[shell_id]['client'].close()
|
||||
except Exception:
|
||||
pass
|
||||
del shell_processes[shell_id]
|
||||
|
||||
|
||||
def _find_ssh_key(settings):
|
||||
key = settings['server'].get('ssh_key')
|
||||
if key and os.path.exists(key):
|
||||
return key
|
||||
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||
temp_dir = os.environ.get('TEMP') or os.environ.get('TMPDIR') or ('/tmp' if os.name != 'nt' else 'C:\\Temp')
|
||||
potential_paths = [
|
||||
os.path.join(temp_dir, 'dune-tunnel-key'),
|
||||
os.path.join(temp_dir, 'dune-awakening-server-sshKey'),
|
||||
os.path.join(base_dir, 'internal-scripts', 'ssh', 'sshKey'),
|
||||
os.path.join(os.path.dirname(base_dir), 'internal-scripts', 'ssh', 'sshKey'),
|
||||
]
|
||||
for p in potential_paths:
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
# Import flask globals inside functions to avoid circular imports
|
||||
from flask import request
|
||||
from flask_socketio import emit
|
||||
Reference in new issue
Block a user