fix: SSH keepalive, director fallback, Ctrl+C handler, namespace ordering
- SSH transport keepalive (15s) + stale client cleanup for reliable reconnection - Ctrl+C signal handler (os._exit) to bypass stuck daemon threads - Director API fallback: SSH + wget to BGD service cluster IP (no tunnel needed) - Namespace auto-detection moved before DirectorService creation - Director host defaults to 127.0.0.1 (configurable via director.host) - Connection monitor: 60s -> 30s interval - Backup scheduler: skip if SSH unreachable instead of blocking 300s
This commit is contained in:
1 parent
65a1948fd1
commit
42eec81081
5 files changed
+99
-13
No files matched your search
@@ -46,6 +46,7 @@ DEFAULTS = {
|
|||||||
'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
|
'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
|
||||||
},
|
},
|
||||||
'director': {
|
'director': {
|
||||||
|
'host': '',
|
||||||
'port': 32479,
|
'port': 32479,
|
||||||
},
|
},
|
||||||
'filebrowser': {
|
'filebrowser': {
|
||||||
|
|||||||
+16
-10
@@ -238,6 +238,16 @@ def create_app(settings_path=None):
|
|||||||
)
|
)
|
||||||
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
|
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
|
||||||
|
|
||||||
|
# Auto-detect namespace if not set in config — must run before
|
||||||
|
# services that consume the namespace (director, backup, etc.).
|
||||||
|
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}")
|
||||||
|
|
||||||
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
||||||
|
|
||||||
player_svc = PlayerService(db_service, dash_db=dash_db_service)
|
player_svc = PlayerService(db_service, dash_db=dash_db_service)
|
||||||
@@ -249,7 +259,7 @@ def create_app(settings_path=None):
|
|||||||
updater_svc = UpdateService(base_dir)
|
updater_svc = UpdateService(base_dir)
|
||||||
logging.debug("UpdateService initialized")
|
logging.debug("UpdateService initialized")
|
||||||
director_svc = DirectorService(
|
director_svc = DirectorService(
|
||||||
host='127.0.0.1',
|
host=settings.get('director', {}).get('host') or '127.0.0.1',
|
||||||
node_port=settings.get('director', {}).get('port', 32479),
|
node_port=settings.get('director', {}).get('port', 32479),
|
||||||
k8s_service=k8s_service,
|
k8s_service=k8s_service,
|
||||||
ssh_service=ssh_service,
|
ssh_service=ssh_service,
|
||||||
@@ -319,14 +329,6 @@ def create_app(settings_path=None):
|
|||||||
def cleanup_db(exc):
|
def cleanup_db(exc):
|
||||||
pass
|
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}")
|
|
||||||
|
|
||||||
# Check SSL certificate expiry and start background monitor
|
# Check SSL certificate expiry and start background monitor
|
||||||
if ssl_enabled:
|
if ssl_enabled:
|
||||||
try:
|
try:
|
||||||
@@ -428,7 +430,7 @@ def create_app(settings_path=None):
|
|||||||
def _connection_monitor():
|
def _connection_monitor():
|
||||||
"""Background thread that monitors and auto-reconnects services."""
|
"""Background thread that monitors and auto-reconnects services."""
|
||||||
import time
|
import time
|
||||||
check_interval = 60 # Check every 60 seconds
|
check_interval = 30 # Check every 30 seconds
|
||||||
consecutive_failures = 0
|
consecutive_failures = 0
|
||||||
max_consecutive_failures = 5
|
max_consecutive_failures = 5
|
||||||
last_ssh_ok = True # Track SSH state to detect reconnection
|
last_ssh_ok = True # Track SSH state to detect reconnection
|
||||||
@@ -521,6 +523,10 @@ def create_app(settings_path=None):
|
|||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
if time.time() >= next_ts:
|
if time.time() >= next_ts:
|
||||||
|
ssh_svc = services.get('ssh')
|
||||||
|
if ssh_svc and not ssh_svc.check_connection():
|
||||||
|
logging.warning('Backup scheduler: SSH unavailable, skipping backup')
|
||||||
|
continue
|
||||||
logging.info('Backup scheduler: Triggering scheduled backup')
|
logging.info('Backup scheduler: Triggering scheduled backup')
|
||||||
backup_svc.run_scheduled_backup()
|
backup_svc.run_scheduled_backup()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import configparser
|
import configparser
|
||||||
import io
|
import io
|
||||||
@@ -10,6 +11,9 @@ from typing import Any, Dict, Optional
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Internal port the BGD container listens on (used with service cluster IP)
|
||||||
|
_BGD_CONTAINER_PORT = 11717
|
||||||
|
|
||||||
|
|
||||||
class DirectorService:
|
class DirectorService:
|
||||||
"""Service for interacting with the game server's battlegroup director.
|
"""Service for interacting with the game server's battlegroup director.
|
||||||
@@ -27,6 +31,7 @@ class DirectorService:
|
|||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
self._bgd_svc_url = None # cached cluster URL for SSH fallback
|
||||||
resource_prefix = namespace
|
resource_prefix = namespace
|
||||||
for prefix in ['funcom-seabass-']:
|
for prefix in ['funcom-seabass-']:
|
||||||
if resource_prefix.startswith(prefix):
|
if resource_prefix.startswith(prefix):
|
||||||
@@ -35,9 +40,31 @@ class DirectorService:
|
|||||||
self.resource_prefix = resource_prefix
|
self.resource_prefix = resource_prefix
|
||||||
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
||||||
|
|
||||||
|
def _resolve_bgd_svc_url(self):
|
||||||
|
"""Find the BGD Service cluster IP via kubectl (stable across pod restarts)."""
|
||||||
|
out, err, rc = self.k8s.run('get svc -o name', timeout=10)
|
||||||
|
if rc != 0:
|
||||||
|
return None
|
||||||
|
for line in (out or '').split('\n'):
|
||||||
|
line = line.strip()
|
||||||
|
if 'bgd-svc' in line:
|
||||||
|
svc_name = line.split('/')[-1]
|
||||||
|
ip_out, ip_err, ip_rc = self.k8s.run(
|
||||||
|
f'get svc {svc_name} -o jsonpath={{.spec.clusterIP}}', timeout=10)
|
||||||
|
if ip_rc == 0 and ip_out:
|
||||||
|
ip = ip_out.strip()
|
||||||
|
logger.info("Director: resolved BGD svc cluster IP %s", ip)
|
||||||
|
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
|
||||||
|
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
|
||||||
|
return None
|
||||||
|
|
||||||
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
||||||
timeout: int = 15, raw_data: bool = False) -> str:
|
timeout: int = 15, raw_data: bool = False) -> str:
|
||||||
"""Execute HTTP request to director service via NodePort.
|
"""Execute HTTP request to director service.
|
||||||
|
|
||||||
|
Tries local HTTP first (SSH tunnel + kubectl port-forward).
|
||||||
|
Falls back to SSH + wget directly to the BGD service cluster IP,
|
||||||
|
which survives server restarts without needing a port-forward.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
path: URL path (e.g., '/v0/battlegroup').
|
path: URL path (e.g., '/v0/battlegroup').
|
||||||
@@ -67,8 +94,44 @@ class DirectorService:
|
|||||||
method=method
|
method=method
|
||||||
)
|
)
|
||||||
|
|
||||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
# Try local HTTP first (SSH tunnel + kubectl port-forward on VM)
|
||||||
return resp.read().decode()
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
return resp.read().decode()
|
||||||
|
except (urllib.error.URLError, ConnectionError, OSError) as e:
|
||||||
|
logger.debug("Director local HTTP failed, trying SSH fallback: %s", e)
|
||||||
|
|
||||||
|
# Fallback: SSH to BGD service cluster IP (always works, no tunnel needed)
|
||||||
|
if not self._bgd_svc_url:
|
||||||
|
self._bgd_svc_url = self._resolve_bgd_svc_url()
|
||||||
|
if self._bgd_svc_url:
|
||||||
|
svc_url = f"{self._bgd_svc_url}{path}"
|
||||||
|
logger.debug("Director SSH fallback: %s %s", method, svc_url)
|
||||||
|
if method == 'GET':
|
||||||
|
out, err, rc = self.ssh.run(f'wget -qO- {svc_url}', timeout=timeout)
|
||||||
|
else:
|
||||||
|
body_bytes = None
|
||||||
|
if raw_data and isinstance(data, str):
|
||||||
|
body_bytes = data.encode()
|
||||||
|
elif data is not None:
|
||||||
|
body_bytes = json.dumps(data).encode()
|
||||||
|
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
|
||||||
|
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
|
||||||
|
self.ssh.run(f'echo {body_b64} | base64 -d > {tmp}', timeout=5)
|
||||||
|
try:
|
||||||
|
out, err, rc = self.ssh.run(
|
||||||
|
f'wget -qO- --post-file={tmp} '
|
||||||
|
f'--header="Content-Type: application/json" {svc_url}',
|
||||||
|
timeout=timeout)
|
||||||
|
finally:
|
||||||
|
self.ssh.run(f'rm -f {tmp}', timeout=5)
|
||||||
|
if rc == 0 and out:
|
||||||
|
return out
|
||||||
|
logger.warning("Director SSH fallback failed (rc=%d): %s",
|
||||||
|
rc, err[:100] if err else 'none')
|
||||||
|
self._bgd_svc_url = None # stale cache, re-resolve next time
|
||||||
|
|
||||||
|
raise ConnectionError("Connection refused: Director unreachable via local HTTP or SSH fallback")
|
||||||
|
|
||||||
# ── Director API methods ──────────────────────────────────────────
|
# ── Director API methods ──────────────────────────────────────────
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import paramiko
|
|||||||
from app.utils.ssh_key import resolve_ssh_key
|
from app.utils.ssh_key import resolve_ssh_key
|
||||||
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
|
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
|
||||||
|
|
||||||
|
KEEPALIVE_INTERVAL = 15
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -37,6 +39,11 @@ class SSHService:
|
|||||||
transport = self._client.get_transport()
|
transport = self._client.get_transport()
|
||||||
if transport and transport.is_active():
|
if transport and transport.is_active():
|
||||||
return self._client
|
return self._client
|
||||||
|
logger.debug("SSH: closing stale client before reconnect")
|
||||||
|
try:
|
||||||
|
self._client.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
self._client = None
|
self._client = None
|
||||||
|
|
||||||
client = paramiko.SSHClient()
|
client = paramiko.SSHClient()
|
||||||
@@ -56,6 +63,9 @@ class SSHService:
|
|||||||
try:
|
try:
|
||||||
client.connect(**connect_kwargs)
|
client.connect(**connect_kwargs)
|
||||||
logger.debug("SSH connection established to %s@%s", self.user, self.host)
|
logger.debug("SSH connection established to %s@%s", self.user, self.host)
|
||||||
|
transport = client.get_transport()
|
||||||
|
if transport:
|
||||||
|
transport.set_keepalive(KEEPALIVE_INTERVAL)
|
||||||
except paramiko.AuthenticationException:
|
except paramiko.AuthenticationException:
|
||||||
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -67,6 +67,12 @@ if __name__ == '__main__':
|
|||||||
print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.")
|
print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.")
|
||||||
print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n")
|
print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n")
|
||||||
|
|
||||||
|
import signal
|
||||||
|
def _shutdown(sig, frame):
|
||||||
|
logging.getLogger(__name__).info("Shutdown signal received, exiting...")
|
||||||
|
os._exit(0)
|
||||||
|
signal.signal(signal.SIGINT, _shutdown)
|
||||||
|
|
||||||
# Start optional HTTP -> HTTPS redirect server when SSL is enabled.
|
# Start optional HTTP -> HTTPS redirect server when SSL is enabled.
|
||||||
# This is convenience only; the dashboard works without port 80 if users visit https://host:port.
|
# This is convenience only; the dashboard works without port 80 if users visit https://host:port.
|
||||||
if ssl_context and settings['dashboard'].get('http_redirect', False):
|
if ssl_context and settings['dashboard'].get('http_redirect', False):
|
||||||
|
|||||||
Reference in new issue
Block a user