"""API routes - server actions, player management, debug endpoints""" import json import logging import os import re import shlex import time from datetime import datetime from flask import Blueprint, request, jsonify from flask_login import login_required from flask_limiter import Limiter from flask_limiter.util import get_remote_address from app.utils.constants import NAV_PAGES logger = logging.getLogger(__name__) K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") def require_k8s_name(value, label): """Validate that a value is a valid Kubernetes resource name.""" value = str(value or "").strip() if not value or not K8S_NAME_RE.fullmatch(value): raise ValueError(f"Invalid {label}") return value def quote_remote(value): """Shell-quote a value for safe use in remote commands.""" return shlex.quote(str(value)) def fb_within_roots(canonical, roots): """True when a canonical absolute path is inside one of the roots.""" canonical = '/' + str(canonical or '').strip().lstrip('/') canonical = canonical.rstrip('/') or '/' for root in roots or []: root = str(root).strip().rstrip('/') or '/' root = '/' + root.lstrip('/') if canonical == root or canonical.startswith(root + '/'): return True return False 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'] backup_svc = services.get('backup') lifecycle_svc = services.get('lifecycle') broadcasts_svc = services.get('broadcasts') audit_svc = services.get('audit') # Get or create rate limiter - use existing one from factory if available if not hasattr(app, 'limiter'): limiter = Limiter( app=app, key_func=get_remote_address, default_limits=[], # Disabled storage_uri="memory://", ) else: limiter = app.limiter # Only require login if auth is enabled auth_req = login_required if settings.get('auth', {}).get('enabled', True) else lambda f: f # Server actions @app.route('/server/action', methods=['POST']) @auth_req 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'}) try: deployment = require_k8s_name(deployment, 'deployment') except ValueError as e: return jsonify({'success': False, 'output': str(e)}) 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) # Audit logging for server actions if audit_svc and action in ['restart', 'scale_0', 'scale_1']: severity = 'warning' if action in ['restart', 'scale_0'] else 'info' audit_svc.log(f'server_{action}', {'deployment': deployment, 'result': rc}, user='admin', severity=severity) return jsonify({'success': rc == 0, 'output': out + '\n' + err}) @app.route('/server/pods') @auth_req 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') @auth_req 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') @auth_req 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']) @auth_req 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']) @auth_req def battlegroup_update(): # Safety guard: refuse to update while game servers are online. running = k8s.get_running_game_pods() if running is None: return jsonify({'success': False, 'output': 'Update blocked: could not verify pod status. ' 'Stop the server first, then try again.'}) if running: shown = ', '.join(running[:5]) if len(running) > 5: shown += f', ... ({len(running)} total)' return jsonify({'success': False, 'output': f'Update blocked: server is online ' f'({len(running)} game pod(s) Running: {shown}). ' f'Stop/shutdown the server first.'}) 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'}) # Lifecycle: graceful shutdown/start/restart + scheduled restarts @app.route('/server/lifecycle/status') @auth_req def lifecycle_status(): if not lifecycle_svc: return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) status = lifecycle_svc.status() status['success'] = True return jsonify(status) @app.route('/server/lifecycle/start', methods=['POST']) @auth_req def lifecycle_start(): if not lifecycle_svc: return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) if lifecycle_svc.status().get('active'): return jsonify({'success': False, 'output': 'A countdown is already running'}) bg_script = settings['kubernetes']['battlegroup_script'] out, err, rc = ssh.run(f'{bg_script} start', timeout=300) if audit_svc: audit_svc.log('server_start', {'result': rc}, user='admin', severity='warning' if rc != 0 else 'info') return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) @app.route('/server/lifecycle/shutdown', methods=['POST']) @auth_req def lifecycle_shutdown(): if not lifecycle_svc: return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) result = lifecycle_svc.start_shutdown(reason='manual') if audit_svc and result.get('success'): audit_svc.log('server_shutdown_countdown', {'action_at': result.get('action_at')}, user='admin', severity='warning') return jsonify(result) @app.route('/server/lifecycle/restart', methods=['POST']) @auth_req def lifecycle_restart(): if not lifecycle_svc: return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) result = lifecycle_svc.start_restart(reason='manual') if audit_svc and result.get('success'): audit_svc.log('server_restart_countdown', {'action_at': result.get('action_at')}, user='admin', severity='warning') return jsonify(result) @app.route('/server/lifecycle/cancel', methods=['POST']) @auth_req def lifecycle_cancel(): if not lifecycle_svc: return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) result = lifecycle_svc.cancel() if audit_svc and result.get('success'): audit_svc.log('server_lifecycle_cancel', {'kind': result.get('kind')}, user='admin', severity='info') return jsonify(result) @app.route('/server/lifecycle/schedule') @auth_req def lifecycle_schedule_get(): if not lifecycle_svc: return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) cfg = lifecycle_svc.get_schedule() return jsonify({'success': True, 'schedule': cfg}) @app.route('/server/lifecycle/schedule', methods=['POST']) @auth_req def lifecycle_schedule_set(): if not lifecycle_svc: return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) data = request.get_json() or {} try: cfg = lifecycle_svc.update_schedule(data) except ValueError as e: return jsonify({'success': False, 'error': str(e)}) except Exception as e: logger.error(f'Lifecycle schedule save failed: {e}') return jsonify({'success': False, 'error': 'Could not save schedule'}) if audit_svc: audit_svc.log('server_restart_schedule', {'enabled': cfg.get('enabled'), 'mode': cfg.get('mode'), 'next_run': cfg.get('next_run')}, user='admin', severity='info') return jsonify({'success': True, 'schedule': cfg}) @app.route('/server/lifecycle/schedule/enabled', methods=['POST']) @auth_req def lifecycle_schedule_enabled(): if not lifecycle_svc: return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) data = request.get_json() or {} cfg = lifecycle_svc.set_enabled(data.get('enabled', True)) if audit_svc: audit_svc.log('server_restart_schedule', {'enabled': cfg.get('enabled'), 'mode': cfg.get('mode'), 'next_run': cfg.get('next_run')}, user='admin', severity='info') return jsonify({'success': True, 'schedule': cfg}) @app.route('/server/lifecycle/schedule/clear', methods=['POST']) @auth_req def lifecycle_schedule_clear(): if not lifecycle_svc: return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) cfg = lifecycle_svc.clear_schedule() if audit_svc: audit_svc.log('server_restart_schedule', {'cleared': True, 'mode': cfg.get('mode')}, user='admin', severity='info') return jsonify({'success': True, 'schedule': cfg}) # Custom notifications (moved here from Experimental - confirmed working) @app.route('/server/broadcast', methods=['POST']) @auth_req def server_broadcast(): data = request.get_json() or {} title = (data.get('title') or '').strip() message = (data.get('message') or '').strip() try: duration = int(data.get('duration', 30)) except (ValueError, TypeError): duration = 30 duration = max(5, min(300, duration)) if not title or not message: return jsonify({'success': False, 'error': 'Title and message are required'}) success, result = admin_svc.send_global_broadcast(title, message, duration) if audit_svc and success: audit_svc.log('server_broadcast', {'title': title, 'duration': duration}, user='admin', severity='info') return jsonify({'success': success, 'output': result}) @app.route('/server/broadcasts/schedule') @auth_req def broadcasts_schedule_list(): if not broadcasts_svc: return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) return jsonify({'success': True, 'entries': broadcasts_svc.list_entries()}) @app.route('/server/broadcasts/schedule', methods=['POST']) @auth_req def broadcasts_schedule_save(): if not broadcasts_svc: return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) data = request.get_json() or {} try: entry = broadcasts_svc.save_entry(data) except ValueError as e: return jsonify({'success': False, 'error': str(e)}) except Exception as e: logger.error(f'Broadcast schedule save failed: {e}') return jsonify({'success': False, 'error': 'Could not save scheduled notification'}) if audit_svc: audit_svc.log('server_broadcast_schedule', {'id': entry.get('id'), 'enabled': entry.get('enabled'), 'mode': entry.get('mode'), 'next_run': entry.get('next_run')}, user='admin', severity='info') return jsonify({'success': True, 'entry': entry}) @app.route('/server/broadcasts/schedule/enabled', methods=['POST']) @auth_req def broadcasts_schedule_enabled(): if not broadcasts_svc: return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) data = request.get_json() or {} try: entry = broadcasts_svc.set_enabled(data.get('id'), data.get('enabled', True)) except ValueError as e: return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': True, 'entry': entry}) @app.route('/server/broadcasts/schedule/delete', methods=['POST']) @auth_req def broadcasts_schedule_delete(): if not broadcasts_svc: return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) data = request.get_json() or {} ok = broadcasts_svc.delete_entry(str(data.get('id') or '')) if audit_svc and ok: audit_svc.log('server_broadcast_schedule', {'deleted': str(data.get('id') or '')}, user='admin', severity='info') return jsonify({'success': ok}) # Firewall management def _get_bgd_nodeport(): """Resolve the current BGD service NodePort from K8s.""" ns = settings.get('kubernetes', {}).get('namespace', '') if not ns: return None out, _, rc = k8s.run(f'get svc -n {ns} -o wide') if rc != 0 or not out: return None for line in out.split('\n'): if '-bgd-svc' in line and 'NodePort' in line: parts = line.split() for p in parts: if ':' in p and p[0].isdigit(): port_str = p.split(':')[1].split('/')[0] try: return int(port_str) except ValueError: continue return None @app.route('/server/firewall') @auth_req def firewall_status(): bgd_port = _get_bgd_nodeport() port_map = { 'filebrowser': {'port': 18888, 'name': 'File Browser'}, } if bgd_port: port_map['director'] = {'port': bgd_port, 'name': 'Battlegroup Director'} else: port_map['director'] = {'port': None, 'name': 'Battlegroup Director (not running)'} active_ports = [str(p['port']) for p in port_map.values() if p['port']] all_ports_re = '|'.join(active_ports) if active_ports else 'NONE' out, _, _ = ssh.run(f'sudo iptables -L INPUT -n 2>/dev/null | grep -E "dpt:({all_ports_re})"; sudo iptables -L FORWARD -n 2>/dev/null | grep -E "dpt:({all_ports_re})"; sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E "dpt:({all_ports_re})"', timeout=15) blocked_ports = set() rules = {} port_strs = [str(p['port']) for p in port_map.values()] for line in out.split('\n'): for port in port_strs: if f'dpt:{port}' in line and 'DROP' in line: blocked_ports.add(port) rules[port] = line.strip() blocked = [] available = [] for key, info in port_map.items(): port_str = str(info['port']) if port_str in blocked_ports: blocked.append(info) else: available.append(info) return jsonify({ 'success': True, 'blocked': blocked, 'available': available, 'iptables_rules': rules, }) @app.route('/server/firewall/block', methods=['POST']) @auth_req def firewall_block(): port = request.form.get('port', type=int) bgd_port = _get_bgd_nodeport() allowed_ports = {18888} if bgd_port: allowed_ports.add(bgd_port) if port not in allowed_ports: return jsonify({'success': False, 'output': f'Invalid port. Allowed: {", ".join(str(p) for p in sorted(allowed_ports))}'}) cmd = ( f'sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && ' f'sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP && ' f'sudo iptables -I FORWARD 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && ' f'sudo iptables -I FORWARD 2 -p tcp --dport {port} -j DROP && ' f'sudo iptables -t mangle -I PREROUTING 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && ' f'sudo iptables -t mangle -I PREROUTING 2 -p tcp --dport {port} -j DROP' ) out, err, rc = ssh.run(cmd, timeout=20) if rc != 0 and 'already exists' not in (out + err): return jsonify({'success': False, 'output': err}) port_key = None if port == 18888: port_key = 'block_filebrowser' elif port == bgd_port: port_key = 'block_director' if port_key: settings.setdefault('firewall', {})[port_key] = True import yaml settings_path = None for p in ['settings.yaml', 'settings.yml']: import os if os.path.exists(p): settings_path = p break if settings_path: with open(settings_path, 'w') as f: yaml.dump(dict(settings), f) return jsonify({'success': True, 'output': f'Port {port} blocked (localhost allowed)'}) @app.route('/server/firewall/unblock', methods=['POST']) @auth_req def firewall_unblock(): port = request.form.get('port', type=int) bgd_port = _get_bgd_nodeport() allowed_ports = {18888} if bgd_port: allowed_ports.add(bgd_port) if port not in allowed_ports: return jsonify({'success': False, 'output': f'Invalid port. Allowed: {", ".join(str(p) for p in sorted(allowed_ports))}'}) cmd = ( f'sudo iptables -D INPUT -p tcp --dport {port} -j DROP 2>/dev/null; ' f'sudo iptables -D INPUT -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; ' f'sudo iptables -D FORWARD -p tcp --dport {port} -j DROP 2>/dev/null; ' f'sudo iptables -D FORWARD -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; ' f'sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -j DROP 2>/dev/null; ' f'sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; ' f'echo DONE' ) out, err, rc = ssh.run(cmd, timeout=20) combined = (out + err).strip() all_ok = 'DONE' in out or rc == 0 port_key = None if port == 18888: port_key = 'block_filebrowser' elif port == bgd_port: port_key = 'block_director' if port_key: settings.setdefault('firewall', {})[port_key] = False import yaml settings_path = None for p in ['settings.yaml', 'settings.yml']: import os if os.path.exists(p): settings_path = p break if settings_path: with open(settings_path, 'w') as f: yaml.dump(dict(settings), f) return jsonify({'success': all_ok, 'output': 'Port unblocked' if all_ok else combined}) # Chat API @app.route('/api/chat_logs') @auth_req 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), }) note = None if not messages: note = "Chat messages are not available in this server version. The text-router pod does not expose chat logs via kubectl." return jsonify({'success': True, 'messages': messages, 'count': len(messages), 'note': note}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) # Player IP management @app.route('/api/set_player_ip', methods=['POST']) @auth_req 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']) @auth_req 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']) @auth_req 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']) @auth_req 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']) @auth_req 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']) @auth_req 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']) @auth_req 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']) @auth_req 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']) @auth_req 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)}) # Player editing endpoints @app.route('/api/edit_faction', methods=['POST']) @auth_req def api_edit_faction(): try: player_controller_id = request.form.get('player_controller_id', type=int) faction_id = request.form.get('faction_id', type=int) if not player_controller_id: return jsonify({'success': False, 'error': 'Missing player_controller_id'}) if faction_id is None: return jsonify({'success': False, 'error': 'Missing faction_id'}) success, result = admin_svc.edit_faction(player_controller_id, faction_id) if success: return jsonify({'success': True, 'message': f'Faction changed to {result["faction_id"]}'}) return jsonify({'success': False, 'error': result}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/edit_xp', methods=['POST']) @auth_req def api_edit_xp(): try: player_id = request.form.get('player_id', type=int) track_type = request.form.get('track_type', '').strip() xp_amount = request.form.get('xp_amount', type=float) level = request.form.get('level', type=float) if not player_id or not track_type or xp_amount is None: return jsonify({'success': False, 'error': 'Missing required parameters'}) success, result = admin_svc.edit_xp(player_id, track_type, xp_amount, level) if success: return jsonify({'success': True, 'message': f'XP updated for {track_type}'}) return jsonify({'success': False, 'error': result}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/edit_tech_knowledge', methods=['POST']) @auth_req def api_edit_tech_knowledge(): try: player_id = request.form.get('player_id', type=int) xp_points = request.form.get('xp_points', type=int) if not player_id or xp_points is None: return jsonify({'success': False, 'error': 'Missing required parameters'}) success, result = admin_svc.edit_tech_knowledge(player_id, xp_points) if success: return jsonify({'success': True, 'message': 'Tech knowledge updated'}) return jsonify({'success': False, 'error': result}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/edit_currency', methods=['POST']) @auth_req def api_edit_currency(): try: player_controller_id = request.form.get('player_controller_id', type=int) currency_id = request.form.get('currency_id', type=int) new_balance = request.form.get('new_balance', type=int) if not player_controller_id or currency_id is None or new_balance is None: return jsonify({'success': False, 'error': 'Missing required parameters'}) success, result = admin_svc.edit_currency(player_controller_id, currency_id, new_balance) if success: return jsonify({'success': True, 'message': 'Currency updated', 'new_balance': result['new_balance']}) return jsonify({'success': False, 'error': result}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/edit_item', methods=['POST']) @auth_req def api_edit_item(): try: item_id = request.form.get('item_id', type=int) field = request.form.get('field', '').strip() value = request.form.get('value', '').strip() if not item_id or not field or value == '': return jsonify({'success': False, 'error': 'Missing required parameters'}) success, result = admin_svc.edit_item(item_id, field, value) if success: return jsonify({'success': True, 'value': result['value']}) return jsonify({'success': False, 'error': result}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/delete_item', methods=['POST']) @auth_req def api_delete_item(): try: item_id = request.form.get('item_id', type=int) if not item_id: return jsonify({'success': False, 'error': 'Missing item_id'}) success, result = admin_svc.delete_item(item_id) if success: return jsonify({'success': True, 'message': f'Item {result["template_id"]} deleted'}) return jsonify({'success': False, 'error': result}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/add_item', methods=['POST']) @auth_req def api_add_item(): try: inventory_id = request.form.get('inventory_id', type=int) template_id = request.form.get('template_id', '').strip() stack_size = request.form.get('stack_size', type=int, default=1) quality_level = request.form.get('quality_level', type=int, default=0) if not inventory_id or not template_id: return jsonify({'success': False, 'error': 'Missing inventory_id or template_id'}) success, result = admin_svc.add_item(inventory_id, template_id, stack_size, quality_level) if success: return jsonify({'success': True, 'message': 'Item added', 'item_id': result['item_id']}) 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']) @auth_req 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 if success: return jsonify({'success': True, 'message': message}) return jsonify({'success': False, 'error': message}), 404 if 'not found' in message.lower() else 500 # Debug endpoints (should be restricted in production) @app.route('/api/debug/vehicle_properties/') @auth_req 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', 'fuel', 'gas', 'energy', 'resource'])] 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//') @auth_req 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/') @auth_req 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') @auth_req 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/') @auth_req 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/') @auth_req 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') @auth_req 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/') @auth_req 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/') @auth_req 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') @auth_req 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 FILEBROWSER_BASE_PATH = '/srv' # Built-in file-browser jail roots (used when settings has none). _FB_DEFAULT_ROOTS = ('/srv', '/home/dune/.dune') def _fb_allowed_roots(): """Allowed file-browser roots from settings, else built-in defaults.""" roots = (settings.get('filebrowser', {}) or {}).get('allowed_roots') if isinstance(roots, str): roots = [roots] cleaned = [] for root in roots or []: root = '/' + str(root or '').strip().lstrip('/') root = root.rstrip('/') or '/' if root and root not in cleaned: cleaned.append(root) return cleaned or list(_FB_DEFAULT_ROOTS) def _fb_resolve_path(path, pod_name=None, timeout=10): """Canonicalize a path in the target context and enforce the jail. Returns (canonical_path, error). error is '' on success, in which case canonical_path is safe to use in remote commands. """ raw = str(path or '') if '\x00' in raw: return '', 'Invalid path: access denied' if not raw.startswith('/'): return '', 'Invalid path: must be absolute' import posixpath roots = _fb_allowed_roots() lexical = posixpath.normpath(raw) out, err, rc = _fb_exec(f'realpath -m -- {quote_remote(raw)}', pod_name, timeout=timeout) if rc == 0 and (out or '').strip(): canonical = (out or '').strip().split('\n')[0].strip() else: # realpath unavailable in this context: fall back to the lexical # path (still blocks '..' escapes; symlinks stay unresolved). logger.warning('File browser: realpath unavailable, using lexical path check') canonical = lexical if not fb_within_roots(canonical, roots): return '', 'Invalid path: outside allowed directories' return canonical, '' def _get_fb_pod(): """Get the default FileBrowser pod name dynamically.""" pod = k8s.find_pod_by_pattern('fb-deploy') return pod def _list_pods(): """List all running pods available for file browsing, plus VM host.""" available = ['__VM__ (Host OS)'] pods = k8s.get_pods() for p in pods: if p.endswith('-sts-0') or '-deploy-' in p: available.append(p) return available # Pod names the file browser accepts: the VM host entries shown in the # pod selector, or real Kubernetes pod names (RFC 1123). _FB_VM_PODS = ('__VM__', '__VM__ (Host OS)') def _fb_check_pod(pod_name): """Validate a file-browser pod value. Returns an error string or ''.""" if not pod_name: return '' if pod_name in _FB_VM_PODS: return '' try: require_k8s_name(pod_name, 'pod') except ValueError as e: return str(e) return '' def _fb_exec(command, pod_name=None, timeout=10): """Execute a command on the VM host or in a K8s pod.""" if pod_name in _FB_VM_PODS: return k8s.ssh.run(command, timeout=timeout) pod = pod_name or _get_fb_pod() if not pod: return '', 'No pod specified or found', 1 err = _fb_check_pod(pod) if err: return '', f'Invalid pod name: {err}', 1 full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}' return k8s.ssh.run(full_cmd, timeout=timeout) def _fb_write_file(content_b64, path, pod_name=None, timeout=30): """Write a file to the pod filesystem.""" import base64 cmd = f"echo '{content_b64}' | base64 -d > {quote_remote(path)}" return _fb_exec(f"sh -c {quote_remote(cmd)}", pod_name, timeout) def _get_pod_from_request(): pod = request.form.get('pod', '') or request.args.get('pod', '') or request.get_json(silent=True) if isinstance(pod, dict): pod = pod.get('pod', '') return pod or None @app.route('/api/files/pods') @auth_req def api_files_pods(): try: pods = _list_pods() return jsonify({'success': True, 'pods': pods}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) @app.route('/api/files/list', methods=['POST']) @auth_req def api_files_list(): path = request.form.get('path', '/srv') pod_name = _get_pod_from_request() canonical, err = _fb_resolve_path(path, pod_name) if err: return jsonify({'success': False, 'error': err}) safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'ls -la {safe_path}', pod_name, 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') @auth_req def api_files_view(): path = request.args.get('path', '') pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) canonical, err = _fb_resolve_path(path, pod_name) if err: return jsonify({'success': False, 'error': err}) safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', pod_name, 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']) @auth_req def api_files_save(): path = request.form.get('path', '') content = request.form.get('content', '') pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) canonical, err = _fb_resolve_path(path, pod_name) if err: return jsonify({'success': False, 'error': err}) import base64 content_b64 = base64.b64encode(content.encode()).decode() out, err, rc = _fb_write_file(content_b64, canonical, pod_name) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to save file'}) return jsonify({'success': True}) @app.route('/api/files/download', methods=['POST']) @auth_req def api_files_download(): path = request.form.get('path', '') pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) canonical, err = _fb_resolve_path(path, pod_name) if err: return jsonify({'success': False, 'error': err}) import base64 safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'base64 {safe_path}', pod_name, timeout=30) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to read file'}) filename = path.rsplit('/', 1)[-1] if '/' in path else path return jsonify({'success': True, 'content': out.strip(), 'filename': filename}) @app.route('/api/files/upload', methods=['POST']) @auth_req def api_files_upload(): target_path = request.form.get('path', '/srv') uploaded = request.files.get('file') pod_name = _get_pod_from_request() if not uploaded: return jsonify({'success': False, 'error': 'No file provided'}) import base64 filename = uploaded.filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1] if uploaded.filename else 'uploaded_file' dest = target_path.rstrip('/') + '/' + filename canonical, err = _fb_resolve_path(dest, pod_name) if err: return jsonify({'success': False, 'error': 'Invalid destination path'}) content = uploaded.read() content_b64 = base64.b64encode(content).decode() out, err, rc = _fb_write_file(content_b64, canonical, pod_name) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to upload file'}) return jsonify({'success': True, 'filename': filename}) @app.route('/api/files/delete', methods=['POST']) @auth_req def api_files_delete(): path = request.form.get('path', '') pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) canonical, err = _fb_resolve_path(path, pod_name) if err: return jsonify({'success': False, 'error': err}) safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'rm -rf {safe_path}', pod_name, timeout=10) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to delete'}) return jsonify({'success': True}) director_svc = services.get('director') director_port = settings.get('director', {}).get('port', 32479) # Director API proxy @app.route('/api/director/battlegroup') @auth_req def director_battlegroup(): try: if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 logger.info("Director request: %s/v0/battlegroup", director_svc.base_url) data = director_svc.get_battlegroup() return data, 200, {'Content-Type': 'application/json'} except Exception as e: error_msg = str(e) logger.error("Director battlegroup error: %s", e) if 'refused' in error_msg.lower() or 'closed' in error_msg.lower() or 'aborted' in error_msg.lower(): return jsonify({ 'success': False, 'error': 'Director unavailable', 'detail': 'The Battlegroup Director service is not responding. This usually means the BGD pod is starting up or has crashed due to RabbitMQ/database connectivity issues.', 'hint': 'Check the BGD pod logs on the server: sudo kubectl logs -n -l app=-bgd-deploy --tail=50' }), 503 return jsonify({'success': False, 'error': error_msg}), 500 @app.route('/api/director/update_config', methods=['POST']) @auth_req def director_update_config(): try: if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 config = request.get_json() map_name = config.get('MapName', '') result = director_svc.update_server_config(config) if map_name: kv = director_svc.extract_server_config_kv(config) if kv: if not director_svc.update_ini_section(map_name, kv): logger.warning("ConfigMap update failed for map %s (director API call succeeded)", map_name) return result, 200, {'Content-Type': 'application/json'} except Exception as e: if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower(): return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503 return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/clear_config', methods=['POST']) @auth_req def director_clear_config(): try: if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 map_name = request.get_data(as_text=True).strip() result = director_svc.clear_map_config(map_name) if map_name: director_svc.update_ini_section(map_name, {}, remove_section=True) return result, 200, {'Content-Type': 'application/json'} except Exception as e: if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower(): return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503 return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/character_transfer', methods=['GET']) @auth_req def director_character_transfer_get(): try: if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 data = director_svc.fetch_character_transfer_rules() return data, 200, {'Content-Type': 'application/json'} except Exception as e: if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower(): return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503 return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/character_transfer', methods=['POST']) @auth_req def director_character_transfer_update(): try: if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 config = request.get_json() result = director_svc.update_character_transfer(config) kv = director_svc.extract_character_transfer_kv(config) if kv: director_svc.update_ini_section('CharacterTransfers', kv) return result, 200, {'Content-Type': 'application/json'} except Exception as e: if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower(): return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503 return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/character_transfer_clear', methods=['POST']) @auth_req def director_character_transfer_clear(): try: if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 result = director_svc.clear_character_transfer_overrides() director_svc.update_ini_section('CharacterTransfers', {}, remove_section=True) return result, 200, {'Content-Type': 'application/json'} except Exception as e: if 'refused' in str(e).lower() or 'closed' in str(e).lower() or 'aborted' in str(e).lower(): return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503 return jsonify({'success': False, 'error': str(e)}), 500 _MAP_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") def _require_map_name(map_name): """Validate a director map name (used in kubectl resource names).""" map_name = str(map_name or '').strip() if not _MAP_NAME_RE.fullmatch(map_name): raise ValueError('Invalid map name') return map_name @app.route('/api/director/server_set_scale/') @auth_req def director_server_set_scale_get(map_name): try: try: map_name = _require_map_name(map_name) except ValueError as e: return jsonify({'success': False, 'error': str(e)}), 400 if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 scale = director_svc.get_server_set_scale(map_name) if scale is None: return jsonify({'replicas': 0, 'partitions': []}) spec = scale.get('spec', {}) return jsonify({ 'replicas': spec.get('replicas', 0), 'partitions': [p for p in spec.get('partitions', []) if p is not None], }) except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/server_set_scale/', methods=['POST']) @auth_req def director_server_set_scale_patch(map_name): try: try: map_name = _require_map_name(map_name) except ValueError as e: return jsonify({'success': False, 'error': str(e)}), 400 if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 config = request.get_json() replicas = int(config.get('replicas', 1)) partitions_raw = config.get('partitions', []) partitions = [int(p) for p in partitions_raw if p is not None] if replicas > len(partitions): return jsonify({'success': False, 'error': 'replicas cannot exceed partition count'}), 400 if not director_svc.patch_server_set_scale(map_name, replicas, partitions): return jsonify({'success': False, 'error': 'Failed to patch ServerSetScale'}), 500 return jsonify({'success': True}) except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 # Pod actions (list, logs, delete, describe) @app.route('/api/pods') @auth_req def api_pods_list(): try: ns = settings['kubernetes']['namespace'] out, err, rc = ssh.run( f'sudo kubectl get pods -n {ns} -o custom-columns=NAME:.metadata.name,ROLE:.metadata.labels.role,STATUS:.status.phase') if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to list pods'}) pods = [] for line in (out or '').strip().split('\n')[1:]: parts = line.split(None, 2) if len(parts) >= 3: pods.append({ 'name': parts[0], 'role': parts[1] if parts[1] != '' else '', 'status': parts[2], }) return jsonify({'success': True, 'pods': pods}) except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 def _require_pod(data): """Extract + validate a pod name from a JSON body. Raises ValueError.""" pod = (data.get('pod', '') or '').strip() if not pod: raise ValueError('pod name required') return require_k8s_name(pod, 'pod') @app.route('/api/pod/logs', methods=['POST']) @auth_req def api_pod_logs(): try: data = request.get_json(force=True) or {} try: pod = _require_pod(data) except ValueError as e: return jsonify({'success': False, 'error': str(e)}) ns = settings['kubernetes']['namespace'] out, err, rc = ssh.run( f'sudo kubectl logs -n {shlex.quote(str(ns))} {shlex.quote(pod)} --tail=300 2>/dev/null || echo "NO_LOGS"', timeout=15) if rc != 0 and 'NO_LOGS' not in (out or ''): return jsonify({'success': False, 'error': err or 'Failed to get logs'}) logs = (out or '').replace('NO_LOGS\n', '').replace('NO_LOGS', '') return jsonify({'success': True, 'logs': logs, 'pod': pod}) except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/pod/delete', methods=['POST']) @auth_req def api_pod_delete(): try: data = request.get_json(force=True) or {} try: pod = _require_pod(data) except ValueError as e: return jsonify({'success': False, 'error': str(e)}) ns = settings['kubernetes']['namespace'] out, err, rc = ssh.run(f'sudo kubectl delete pod -n {shlex.quote(str(ns))} {shlex.quote(pod)} --wait=false', timeout=30) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to delete pod'}) return jsonify({'success': True, 'message': f'Pod {pod} deleted (will be recreated by its controller)'}) except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/pod/describe', methods=['POST']) @auth_req def api_pod_describe(): try: data = request.get_json(force=True) or {} try: pod = _require_pod(data) except ValueError as e: return jsonify({'success': False, 'error': str(e)}) ns = settings['kubernetes']['namespace'] out, err, rc = ssh.run(f'sudo kubectl describe pod -n {shlex.quote(str(ns))} {shlex.quote(pod)}', timeout=30) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to describe pod'}) return jsonify({'success': True, 'describe': out or '', 'pod': pod}) except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 # Update management @app.route('/api/update/status') @auth_req def api_update_status(): updater = services.get('updater') if not updater: return jsonify({'available': False}) return jsonify({ 'available': updater.update_available, 'status': updater.update_status, }) @app.route('/api/update/apply', methods=['POST']) @auth_req def api_update_apply(): updater = services.get('updater') if not updater: return jsonify({'success': False, 'error': 'Updater not available'}) success, message = updater.apply_update() return jsonify({'success': success, 'message': message}) @app.route('/api/update/test', methods=['POST']) @auth_req def api_update_test(): """Force show update banner for testing.""" updater = services.get('updater') if updater: updater._update_available = True return jsonify({'success': True, 'message': 'Update banner triggered'}) return jsonify({'success': False, 'error': 'Updater not available'}) @app.route('/api/update/check', methods=['POST']) @auth_req def api_update_check(): """Force a fresh check against GitHub.""" updater = services.get('updater') if not updater: return jsonify({'success': False, 'error': 'Updater not available'}) updater.check_for_updates() return jsonify({ 'available': updater.update_available, 'status': updater.update_status, 'local_version': updater._current_sha, 'remote_version': updater._latest_sha, }) # Audit logs from app.services.audit import AuditService audit_svc = AuditService() @app.route('/api/audit/logs', methods=['GET']) @auth_req def api_audit_logs(): """Get audit logs.""" action = request.args.get('action') user = request.args.get('user') limit = int(request.args.get('limit', 100)) offset = int(request.args.get('offset', 0)) logs = audit_svc.get_logs(action=action, user=user, limit=limit, offset=offset) return jsonify({'success': True, 'logs': logs}) @app.route('/api/audit/stats', methods=['GET']) @auth_req def api_audit_stats(): """Get audit log statistics.""" stats = audit_svc.get_stats() return jsonify({'success': True, 'stats': stats}) # Health check endpoint (no auth required for monitoring systems) @app.route('/api/health') def api_health(): """Health check for monitoring systems.""" health = { 'status': 'healthy', 'timestamp': datetime.now().isoformat(), 'checks': {} } # Debug logging for connection status checks debug_mode = settings.get('logging', {}).get('debug_enabled', False) # Check database try: db.execute('SELECT 1') health['checks']['database'] = {'status': 'ok'} if debug_mode: logger.debug("Health check: Database connection OK") except Exception as e: health['checks']['database'] = {'status': 'error', 'message': str(e)} health['status'] = 'degraded' logger.warning(f"Health check: Database connection FAILED - {e}") # Check SSH try: out, err, rc = ssh.run('echo OK') if rc == 0 and 'OK' in out: health['checks']['ssh'] = {'status': 'ok'} if debug_mode: logger.debug(f"Health check: SSH connection OK to {ssh.host}") else: health['checks']['ssh'] = {'status': 'error', 'message': 'SSH command failed'} health['status'] = 'degraded' logger.warning(f"Health check: SSH command failed (rc={rc})") except Exception as e: health['checks']['ssh'] = {'status': 'error', 'message': str(e)} health['status'] = 'degraded' logger.warning(f"Health check: SSH connection FAILED - {e}") # Check Kubernetes try: out, err, rc = k8s.run('get nodes') if rc == 0: health['checks']['kubernetes'] = {'status': 'ok'} if debug_mode: node_count = len(out.split('\n')) - 1 if out else 0 logger.debug(f"Health check: Kubernetes OK - {node_count} nodes") else: health['checks']['kubernetes'] = {'status': 'error', 'message': 'kubectl failed'} health['status'] = 'degraded' logger.warning(f"Health check: kubectl failed - {err[:100]}") except Exception as e: health['checks']['kubernetes'] = {'status': 'error', 'message': str(e)} health['status'] = 'degraded' logger.warning(f"Health check: Kubernetes FAILED - {e}") # Check BGD (Battlegroup Director) pod try: ns = settings.get('kubernetes', {}).get('namespace', '') bgd_out, bgd_err, bgd_rc = k8s.run(f"get pods -n {ns} -l app={ns}-bgd-deploy -o jsonpath='{{.items[*].status.phase}}'") if bgd_rc == 0 and bgd_out: pod_status = bgd_out.strip() if 'Running' in pod_status: health['checks']['bgd'] = {'status': 'ok', 'phase': pod_status} if debug_mode: logger.debug(f"Health check: BGD pod {pod_status}") else: health['checks']['bgd'] = {'status': 'degraded', 'phase': pod_status} logger.warning(f"Health check: BGD pod not running - {pod_status}") else: health['checks']['bgd'] = {'status': 'unavailable'} logger.warning("Health check: BGD pod not found") except Exception as e: health['checks']['bgd'] = {'status': 'error', 'message': str(e)} logger.warning(f"Health check: BGD check FAILED - {e}") # Check RabbitMQ (if accessible) try: mq_out, mq_err, mq_rc = k8s.run(f"get pods -n {ns} -l app=rabbitmq -o jsonpath='{{.items[*].status.phase}}'") if mq_rc == 0 and mq_out: mq_status = mq_out.strip() if 'Running' in mq_status: health['checks']['rabbitmq'] = {'status': 'ok', 'phase': mq_status} if debug_mode: logger.debug(f"Health check: RabbitMQ pod {mq_status}") else: health['checks']['rabbitmq'] = {'status': 'degraded', 'phase': mq_status} logger.warning(f"Health check: RabbitMQ not running - {mq_status}") except Exception as e: health['checks']['rabbitmq'] = {'status': 'unavailable', 'message': 'RabbitMQ check skipped'} # Add dashboard uptime start_time = getattr(app, '_start_time', None) if start_time: health['uptime_seconds'] = int(time.time() - start_time) status_code = 200 if health['status'] == 'healthy' else 503 return jsonify(health), status_code # Settings API - get and update dashboard settings @app.route('/api/settings', methods=['GET']) @login_required def get_settings(): """Get current dashboard settings (filtered).""" try: from app.config import get_settings current_settings = get_settings() # Filter out sensitive values safe_settings = { 'logging': { 'level': current_settings.get('logging', {}).get('level', 'INFO'), 'debug_enabled': current_settings.get('logging', {}).get('debug_enabled', False), }, 'shell_enabled': current_settings.get('shell', {}).get('shell_enabled', True), } return jsonify({'success': True, 'settings': safe_settings}) except Exception as e: logger.error(f"Failed to get settings: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/settings/debug', methods=['POST']) @login_required def toggle_debug(): """Toggle debug logging on/off.""" try: from app.config import get_settings, save_settings current_settings = get_settings() data = request.get_json() or {} debug_enabled = data.get('enabled', False) if 'logging' not in current_settings: current_settings['logging'] = {} current_settings['logging']['debug_enabled'] = debug_enabled save_settings(current_settings) # Apply the change to the running logger if debug_enabled: logging.getLogger().setLevel(logging.DEBUG) logger.info("Debug logging enabled via API") else: logging.getLogger().setLevel(logging.INFO) logger.info("Debug logging disabled via API") return jsonify({ 'success': True, 'debug_enabled': debug_enabled, 'message': f"Debug logging {'enabled' if debug_enabled else 'disabled'}" }) except Exception as e: logger.error(f"Failed to toggle debug: {e}") return jsonify({'success': False, 'error': str(e)}), 500 # ── Backup Endpoints ────────────────────────────────────────────── if backup_svc: @app.route('/api/backup/list') @auth_req def api_backup_list(): return jsonify({'success': True, 'backups': backup_svc.list_backups()}) @app.route('/api/backup/create', methods=['POST']) @auth_req def api_backup_create(): data = request.get_json() or {} password = data.get('password', '') result = backup_svc.create_backup(password=password) return jsonify(result) @app.route('/api/backup/info', methods=['POST']) @auth_req def api_backup_info(): data = request.get_json() or {} name = data.get('name', '') if not name: return jsonify({'success': False, 'error': 'Backup name required'}) path = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups', f'{name}.tar.gz') info = backup_svc.get_backup_info(path) return jsonify({'success': True, 'info': info}) @app.route('/api/backup/delete', methods=['POST']) @auth_req def api_backup_delete(): data = request.get_json() or {} name = data.get('name', '') if not name: return jsonify({'success': False, 'error': 'Backup name required'}) deleted = backup_svc.delete_backup(name) return jsonify({'success': deleted}) @app.route('/api/backup/verify', methods=['POST']) @auth_req def api_backup_verify(): data = request.get_json() or {} name = data.get('name', '') password = data.get('password', '') if not name: return jsonify({'success': False, 'error': 'Backup name required'}) result = backup_svc.verify_backup(name, password=password) return jsonify(result) @app.route('/api/backup/restore/preview', methods=['POST']) @auth_req def api_backup_restore_preview(): data = request.get_json() or {} name = data.get('name', '') if not name: return jsonify({'success': False, 'error': 'Backup name required'}) result = backup_svc.restore_preview(name) return jsonify(result) @app.route('/api/backup/restore/test-connection', methods=['POST']) @auth_req def api_backup_test_connection(): result = backup_svc.test_connection() return jsonify(result) @app.route('/api/backup/restore/start', methods=['POST']) @auth_req def api_backup_restore_start(): data = request.get_json() or {} name = data.get('name', '') options = data.get('options', {}) if not name: return jsonify({'success': False, 'error': 'Backup name required'}) result = backup_svc.start_restore(name, options) return jsonify(result) @app.route('/api/backup/restore/status', methods=['POST']) @auth_req def api_backup_restore_status(): data = request.get_json() or {} restore_id = data.get('restore_id', '') if not restore_id: return jsonify({'success': False, 'error': 'Restore ID required'}) result = backup_svc.get_restore_status(restore_id) return jsonify(result) @app.route('/api/backup/schedule', methods=['GET']) @auth_req def api_backup_schedule_get(): sched = backup_svc.get_schedule() sched.pop('password', None) # never send password to client return jsonify({'success': True, 'schedule': sched}) @app.route('/api/backup/schedule', methods=['POST']) @auth_req def api_backup_schedule_set(): data = request.get_json() or {} result = backup_svc.update_schedule(data) result.pop('password', None) # never send password to client return jsonify({'success': True, 'schedule': result}) @app.route('/api/backup/run-scheduled', methods=['POST']) @auth_req def api_backup_run_scheduled(): result = backup_svc.run_scheduled_backup() return jsonify(result) # ── Funcom ServiceAuthToken ──────────────────────────────────────── @app.route('/api/server/service-auth-token', methods=['POST']) @auth_req def api_set_service_auth_token(): data = request.get_json() or {} token = (data.get('token') or '').strip() if not token: return jsonify({'success': False, 'error': 'Token cannot be empty'}) if not token.startswith('eyJ'): return jsonify({'success': False, 'error': 'Token does not look like a valid JWT'}) ns = settings.get('kubernetes', {}).get('namespace', '') if not ns: return jsonify({'success': False, 'error': 'Kubernetes namespace not configured'}) resource_prefix = ns for prefix in ['funcom-seabass-']: if resource_prefix.startswith(prefix): resource_prefix = resource_prefix[len(prefix):] break secret_yaml = f'/home/dune/.dune/{resource_prefix}-fls-secret.yaml' main_yaml = f'/home/dune/.dune/{resource_prefix}.yaml' try: import base64 # Force fresh SSH connection to avoid stale client reuse ssh.close() # ── Step 1: Read & update secret YAML (small file, keep current approach) ── t0 = time.time() out, err, rc = ssh.run(f'cat {shlex.quote(secret_yaml)}', timeout=10) t1 = time.time() logger.info(f'[token] read secret YAML: {t1-t0:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to read secret file: {err}'}) fls_prefix = 'FuncomLiveServices__ServiceAuthToken: "' idx = out.find(fls_prefix) if idx == -1: # Never log matching lines: they contain the token itself. logger.error('Secret YAML has no FuncomLiveServices__ServiceAuthToken line') return jsonify({'success': False, 'error': 'Could not find FuncomLiveServices__ServiceAuthToken line in secret file'}) start = idx + len(fls_prefix) end = out.find('"', start) if end == -1: return jsonify({'success': False, 'error': 'Could not find closing quote for ServiceAuthToken'}) old_token = out[start:end] new_secret = out[:start] + token + out[end:] t2 = time.time() out, err, rc = ssh.write_file(secret_yaml, new_secret, timeout=10) t3 = time.time() logger.info(f'[token] write secret YAML: {t3-t2:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to write secret file: {err}'}) # ── Step 2: Update main battlegroup YAML via read-modify-write ── # Extract old token from the main YAML (may differ from secret YAML) t4 = time.time() out, err, rc = ssh.run(f'cat {shlex.quote(main_yaml)}', timeout=10) t5 = time.time() logger.info(f'[token] read main YAML: {t5-t4:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to read battlegroup file: {err}'}) ini_prefix = '-ini:engine:[FuncomLiveServices]:ServiceAuthToken=' idx = out.find(ini_prefix) if idx == -1: # Never log matching lines: they contain the token itself. logger.error('Main YAML has no ServiceAuthToken line') return jsonify({'success': False, 'error': 'Could not find ServiceAuthToken in battlegroup file'}) old_start = idx + len(ini_prefix) old_end = out.find('\n', old_start) old_token_main = out[old_start:old_end].strip() if old_end != -1 else out[old_start:].strip() count = out.count(old_token_main) new_main = out.replace(old_token_main, token) logger.info(f'[token] replaced {count} occurrences in main YAML') t6 = time.time() out, err, rc = ssh.write_file(main_yaml, new_main, timeout=15) t7 = time.time() logger.info(f'[token] write main YAML: {t7-t6:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to write battlegroup file: {err}'}) # Verify: count total ServiceAuthToken lines vs new-token lines out, err, rc = ssh.run(f"grep -c 'ServiceAuthToken' {shlex.quote(main_yaml)} || true", timeout=5) total_lines = int(out.strip() or 0) out, err, rc = ssh.run(f"grep -cF {shlex.quote(token)} {shlex.quote(main_yaml)} || true", timeout=5) new_count = int(out.strip() or 0) logger.info(f'[token] main YAML verify: {new_count}/{total_lines} tokens replaced') # ── Step 3: Update live K8s BattleGroup CR (may differ from disk YAML) ── bg_name = resource_prefix t8 = time.time() out, err, rc = ssh.run( f'sudo kubectl get battlegroup {shlex.quote(bg_name)} -n {shlex.quote(str(ns))} -o yaml', timeout=10 ) t9 = time.time() logger.info(f'[token] read BG CR: {t9-t8:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to read BattleGroup CR: {err}'}) old_start = out.find(ini_prefix) if old_start == -1: # Never log matching lines: they contain the token itself. logger.error('BattleGroup CR has no ServiceAuthToken line') return jsonify({'success': False, 'error': 'Could not find ServiceAuthToken in BattleGroup CR'}) old_start += len(ini_prefix) old_end = out.find('\n', old_start) old_token_cr = out[old_start:old_end].strip() if old_end != -1 else out[old_start:].strip() cr_count = out.count(old_token_cr) new_cr = out.replace(old_token_cr, token) logger.info(f'[token] replaced {cr_count} occurrences in BG CR') cr_temp = '/tmp/bg-cr-update.yaml' t10 = time.time() out, err, rc = ssh.write_file(cr_temp, new_cr, timeout=15) t11 = time.time() logger.info(f'[token] write BG CR temp: {t11-t10:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to write BG CR temp file: {err}'}) out, err, rc = ssh.run( f'sudo kubectl apply -f {shlex.quote(cr_temp)}', timeout=15 ) t12 = time.time() logger.info(f'[token] apply BG CR: {t12-t11:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to apply BattleGroup CR: {err}'}) # Verify new token count in live CR out, err, rc = ssh.run( f"sudo kubectl get battlegroup {shlex.quote(bg_name)} -n {shlex.quote(str(ns))} -o yaml | grep -cF {shlex.quote(token)} || true", timeout=5 ) live_count = int(out.strip() or 0) logger.info(f'[token] BG CR verify: {live_count}/{cr_count} tokens replaced') # Clean up temp file ssh.run(f'rm -f {shlex.quote(cr_temp)}', timeout=3) # ── Step 4: Update K8s secret via kubectl patch ── patch = json.dumps({'stringData': {'FuncomLiveServices__ServiceAuthToken': token}}) patch_encoded = base64.b64encode(patch.encode()).decode() t13 = time.time() out, err, rc = ssh.run( f"printf '%s' {shlex.quote(patch_encoded)} | base64 -d > /tmp/service-auth-token-patch.json; " f"sudo kubectl patch secret server-gateway-secret -n {shlex.quote(str(ns))} --patch-file /tmp/service-auth-token-patch.json", timeout=15 ) t14 = time.time() logger.info(f'[token] kubectl patch: {t14-t13:.2f}s rc={rc}') if rc != 0: return jsonify({'success': False, 'error': f'Failed to update K8s secret: {err}'}) total = t14 - t0 logger.info(f'[token] completed successfully in {total:.2f}s (disk={new_count}, live={live_count})') return jsonify({ 'success': True, 'message': f'Token updated in secret YAML, battlegroup YAML ({new_count} replacements), live BattleGroup CR ({live_count} replacements), and K8s secret. Consuming pods must be restarted for the change to take effect.' }) except Exception as e: logger.error(f'[token] exception: {e}') return jsonify({'success': False, 'error': str(e)})