Major refactor: unified launcher, paramiko SSH, DirectorService, diagnostics, and map warning banner

- Merge setup and start scripts into unified launcher (launcher.ps1 / start.sh)
  with menu: Start Dashboard, Run Setup, Run Diagnostics, Quit
- Migrate SSHService from subprocess to paramiko for connection reuse
- Extract Director API into dedicated DirectorService class
- Centralize SSH key resolution in app/utils/ssh_key.py
- Add pagination to player list (50 per page)
- Add comprehensive diagnostics with port-forward troubleshooting guide
- Add 17 new tests (43 total, all passing)
- Fix Director page loading (point to local port-forward instead of remote IP)
- Add experimental warning banner to map page with Dune-themed joke
- Remove dead Flask-Talisman dependency, upgrade cryptography to >=42.0.0
- Fix PowerShell launcher parsing errors (Unicode chars, variable delimiters)
- Update start.bat/setup.bat to point to unified launcher
This commit is contained in:
Reditus committed 2026-05-15 14:57:36 +01:00
1 parent 9ddaa5f667
commit 1959a013ab
19 files changed
+2200 -844

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
"""Director service - battlegroup director API and ConfigMap management."""
import json
import logging
import urllib.request
import configparser
import io
import base64
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
class DirectorService:
"""Service for interacting with the game server's battlegroup director.
Handles:
- Director API requests (battlegroup status, config updates, character transfers)
- Kubernetes ConfigMap patching for director.ini overrides
- INI section manipulation for map-specific config
"""
def __init__(self, host: str, node_port: int, k8s_service, ssh_service, namespace: str):
self.host = host
self.node_port = node_port
self.base_url = f"http://{host}:{node_port}"
self.k8s = k8s_service
self.ssh = ssh_service
self.namespace = namespace
self.cm_name = f"{namespace}-bgd-conf-cm"
def _request(self, path: str, method: str = 'GET', data: Any = None,
timeout: int = 15, raw_data: bool = False) -> str:
"""Execute HTTP request to director service via NodePort.
Args:
path: URL path (e.g., '/v0/battlegroup').
method: HTTP method.
data: Request body (dict for JSON, str for raw).
timeout: Request timeout in seconds.
raw_data: If True, send data as raw text instead of JSON.
Returns:
Response body as string.
"""
url = f"{self.base_url}{path}"
logger.debug("Director request: %s %s", method, url)
if method == 'GET':
req = urllib.request.Request(url)
else:
if raw_data and isinstance(data, str):
body = data.encode()
elif data is not None:
body = json.dumps(data).encode()
else:
body = None
req = urllib.request.Request(
url, data=body,
headers={'Content-Type': 'application/json'},
method=method
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode()
# ── Director API methods ──────────────────────────────────────────
def get_battlegroup(self) -> str:
"""Fetch current battlegroup status."""
return self._request('/v0/battlegroup')
def update_server_config(self, config: Dict) -> str:
"""Update server group configuration."""
return self._request(
'/v0/BattlegroupUpdateServerGroupConfig',
method='POST', data=config, timeout=30
)
def clear_map_config(self, map_name: str) -> str:
"""Clear map config overrides."""
return self._request(
'/v0/BattlegroupClearMapConfigOverrides',
method='POST', data=map_name, timeout=30, raw_data=True
)
def fetch_character_transfer_rules(self) -> str:
"""Fetch character transfer rules."""
return self._request('/v0/BattlegroupFetchCharacterTransferRules')
def update_character_transfer(self, config: Dict) -> str:
"""Update character transfer settings."""
return self._request(
'/v0/BattlegroupUpdateCharacterTransferSettings',
method='POST', data=config, timeout=30
)
def clear_character_transfer_overrides(self) -> str:
"""Clear character transfer overrides."""
return self._request(
'/v0/BattlegroupClearCharacterTransferOverrides',
method='POST', timeout=30
)
# ── ConfigMap management ─────────────────────────────────────────
def patch_configmap(self, new_ini_content: str) -> bool:
"""Patch the BGD ConfigMap with new director.ini content.
Args:
new_ini_content: The full director.ini content to write.
Returns:
True if the patch succeeded, False otherwise.
"""
cm_out, cm_err, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
if cm_rc != 0 or not cm_out:
logger.warning("Could not get ConfigMap: %s", 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 {self.namespace}'
out, err, rc = self.ssh.run(patch_cmd, timeout=15)
if rc != 0:
logger.warning("ConfigMap patch failed: %s", err)
return False
return True
def update_ini_section(self, map_name: str, key_values: Dict[str, Any],
remove_section: bool = False) -> bool:
"""Read ConfigMap INI, modify a section, write back.
Args:
map_name: The INI section name (e.g., map name).
key_values: Key-value pairs to set in the section.
remove_section: If True, remove the section instead.
Returns:
True if the update succeeded, False otherwise.
"""
cm_out, _, cm_rc = self.k8s.run(f'get configmap {self.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 self.patch_configmap(buf.getvalue())
# ── Helper: extract config values for INI update ─────────────────
@staticmethod
def extract_server_config_kv(config: Dict) -> Dict[str, str]:
"""Extract key-value pairs from a director config dict for INI update.
Handles DimensionServerGroupConfig, ClassicalInstancingGroupConfig,
and SingleServerConfig formats.
"""
kv = {}
cfg_keys = ('DimensionServerGroupConfig', 'ClassicalInstancingGroupConfig')
for cfg_key in cfg_keys:
if cfg_key in config:
dcfg = config[cfg_key]
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']
break
if not kv and 'SingleServerConfig' in config:
scfg = config['SingleServerConfig']
if scfg.get('playerHardCap') is not None:
kv['PlayerHardCap'] = scfg['playerHardCap']
return kv
@staticmethod
def extract_character_transfer_kv(config: Dict) -> Dict[str, str]:
"""Extract key-value pairs from character transfer config."""
kv = {}
if 'ForceIsWorldClosed' in config:
kv['ForceIsWorldClosed'] = str(config['ForceIsWorldClosed'])
if 'ForceIsWorldClosingSoon' in config:
kv['ForceIsWorldClosingSoon'] = str(config['ForceIsWorldClosingSoon'])
return kv
+37 -3
View File
@@ -7,6 +7,39 @@ logger = logging.getLogger(__name__)
LIKE_PC = '%DunePlayerCharacter_C'
def _build_player_filters(search='', faction_id='', guild_id='', map_filter='', online_filter=''):
"""Build WHERE clause and params for player queries.
Returns (where_clause, params) tuple.
"""
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'")
return ' AND '.join(where), params
class PlayerService:
def __init__(self, db_service):
self.db = db_service
@@ -60,7 +93,8 @@ class PlayerService:
ORDER BY ps.character_name
""")
def get_players_list(self, search='', faction_id='', guild_id='', map_filter='', online_filter='', limit=200):
def get_players_list(self, search='', faction_id='', guild_id='', map_filter='',
online_filter='', limit=200, offset=0):
where = ["a.class LIKE %s"]
params = [LIKE_PC]
@@ -110,8 +144,8 @@ class PlayerService:
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])
LIMIT %s OFFSET %s
""", params + [limit, offset])
if not players:
return []
+104 -57
View File
@@ -1,78 +1,125 @@
"""SSH service - remote command execution"""
"""SSH service - remote command execution via paramiko."""
import subprocess
import logging
import os
import threading
import paramiko
from app.utils.ssh_key import resolve_ssh_key
logger = logging.getLogger(__name__)
class SSHService:
"""SSH service using paramiko for connection reuse.
Replaces the previous subprocess-based implementation.
Benefits:
- Connection reuse (no SSH handshake per command)
- Better error handling
- No dependency on system ssh binary
- Thread-safe via lock
"""
def __init__(self, host, user, ssh_key=None):
self.host = host
self.user = user
self.ssh_key = self._resolve_ssh_key(ssh_key)
self.ssh_key = resolve_ssh_key(ssh_key)
self._client = None
self._lock = threading.Lock()
key_status = self.ssh_key if self.ssh_key else 'default ssh identity/agent'
logger.info(f"SSHService initialized: {user}@{host} using {key_status}")
logger.info("SSHService initialized: %s@%s using %s", user, host, key_status)
def _resolve_ssh_key(self, ssh_key):
if ssh_key:
key = str(ssh_key).strip("'\"")
if os.path.exists(key):
return key
def _get_client(self):
"""Get or create a paramiko SSH client. Thread-safe."""
with self._lock:
if self._client is not None:
transport = self._client.get_transport()
if transport and transport.is_active():
return self._client
self._client = None
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')
local_appdata = os.environ.get('LOCALAPPDATA', '')
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'),
]
if local_appdata:
potential_paths.insert(2, os.path.join(local_appdata, 'DuneAwakeningServer', 'sshKey'))
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
for path in potential_paths:
if os.path.exists(path):
return path
return None
connect_kwargs = {
'hostname': self.host,
'username': self.user,
'timeout': 15,
'allow_agent': True,
'look_for_keys': True,
}
if self.ssh_key:
connect_kwargs['key_filename'] = self.ssh_key
try:
client.connect(**connect_kwargs)
logger.debug("SSH connection established to %s@%s", self.user, self.host)
except paramiko.AuthenticationException:
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
raise
except paramiko.SSHException as e:
logger.error("SSH connection error: %s", e)
raise
except Exception as e:
logger.error("Unexpected SSH error: %s", e)
raise
self._client = client
return self._client
def run(self, command, timeout=30):
args = [
'ssh',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', 'ConnectTimeout=10',
'-o', 'BatchMode=yes',
]
if self.ssh_key:
args.extend(['-i', self.ssh_key])
args.extend([f'{self.user}@{self.host}', command])
logger.debug(f"SSH command: {command[:100]}...")
"""Execute a remote command via SSH.
Args:
command: The shell command to execute.
timeout: Maximum time in seconds to wait for the command.
Returns:
Tuple of (stdout, stderr, return_code).
"""
logger.debug("SSH command: %s...", command[:100] if len(command) > 100 else command)
try:
result = subprocess.run(
args,
capture_output=True,
text=True,
timeout=timeout
)
if result.returncode != 0:
logger.warning(f"SSH command failed (rc={result.returncode}): {result.stderr[:200]}")
return result.stdout, result.stderr, result.returncode
except FileNotFoundError:
logger.error("SSH command not found. Is OpenSSH installed?")
return '', 'ssh command not found', -1
except subprocess.TimeoutExpired:
logger.error(f"SSH command timed out after {timeout}s: {command[:100]}")
return '', 'SSH command timed out', -1
client = self._get_client()
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
out = stdout.read().decode('utf-8', errors='replace')
err = stderr.read().decode('utf-8', errors='replace')
rc = stdout.channel.recv_exit_status()
if rc != 0:
logger.warning("SSH command failed (rc=%d): %s", rc, err[:200])
return out, err, rc
except paramiko.SSHException as e:
logger.error("SSH command error: %s", e)
self._client = None
return '', str(e), -1
except Exception as ex:
logger.error(f"SSH command error: {ex}")
logger.error("Unexpected SSH command error: %s", ex)
self._client = None
return '', str(ex), -1
def check_connection(self):
out, err, rc = self.run('echo ok', timeout=5)
if rc == 0 and 'ok' in out:
logger.debug("SSH connection check passed")
else:
logger.warning("SSH connection check failed")
return rc == 0 and 'ok' in out
"""Test SSH connectivity with a simple echo command.
Returns:
True if the connection works, False otherwise.
"""
try:
out, err, rc = self.run('echo ok', timeout=10)
if rc == 0 and 'ok' in out:
logger.debug("SSH connection check passed")
return True
logger.warning("SSH connection check failed: rc=%d, out=%s", rc, out[:50])
return False
except Exception:
logger.warning("SSH connection check failed with exception")
return False
def close(self):
"""Close the SSH connection. Safe to call multiple times."""
with self._lock:
if self._client:
try:
self._client.close()
logger.debug("SSH connection closed")
except Exception as e:
logger.debug("Error closing SSH connection: %s", e)
self._client = None