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',
|
||||
},
|
||||
'director': {
|
||||
'host': '',
|
||||
'port': 32479,
|
||||
},
|
||||
'filebrowser': {
|
||||
|
||||
+16
-10
@@ -238,6 +238,16 @@ def create_app(settings_path=None):
|
||||
)
|
||||
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'])
|
||||
|
||||
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)
|
||||
logging.debug("UpdateService initialized")
|
||||
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),
|
||||
k8s_service=k8s_service,
|
||||
ssh_service=ssh_service,
|
||||
@@ -319,14 +329,6 @@ def create_app(settings_path=None):
|
||||
def cleanup_db(exc):
|
||||
pass
|
||||
|
||||
if settings['kubernetes']['namespace'] == '':
|
||||
try:
|
||||
k8s_service.auto_detect_namespace()
|
||||
if k8s_service.namespace:
|
||||
settings['kubernetes']['namespace'] = k8s_service.namespace
|
||||
except Exception as e:
|
||||
logging.warning(f"Could not auto-detect K8s namespace: {e}")
|
||||
|
||||
# Check SSL certificate expiry and start background monitor
|
||||
if ssl_enabled:
|
||||
try:
|
||||
@@ -428,7 +430,7 @@ def create_app(settings_path=None):
|
||||
def _connection_monitor():
|
||||
"""Background thread that monitors and auto-reconnects services."""
|
||||
import time
|
||||
check_interval = 60 # Check every 60 seconds
|
||||
check_interval = 30 # Check every 30 seconds
|
||||
consecutive_failures = 0
|
||||
max_consecutive_failures = 5
|
||||
last_ssh_ok = True # Track SSH state to detect reconnection
|
||||
@@ -521,6 +523,10 @@ def create_app(settings_path=None):
|
||||
except Exception:
|
||||
continue
|
||||
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')
|
||||
backup_svc.run_scheduled_backup()
|
||||
except Exception as e:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
import logging
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import configparser
|
||||
import io
|
||||
@@ -10,6 +11,9 @@ from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Internal port the BGD container listens on (used with service cluster IP)
|
||||
_BGD_CONTAINER_PORT = 11717
|
||||
|
||||
|
||||
class DirectorService:
|
||||
"""Service for interacting with the game server's battlegroup director.
|
||||
@@ -27,6 +31,7 @@ class DirectorService:
|
||||
self.k8s = k8s_service
|
||||
self.ssh = ssh_service
|
||||
self.namespace = namespace
|
||||
self._bgd_svc_url = None # cached cluster URL for SSH fallback
|
||||
resource_prefix = namespace
|
||||
for prefix in ['funcom-seabass-']:
|
||||
if resource_prefix.startswith(prefix):
|
||||
@@ -35,9 +40,31 @@ class DirectorService:
|
||||
self.resource_prefix = resource_prefix
|
||||
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,
|
||||
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:
|
||||
path: URL path (e.g., '/v0/battlegroup').
|
||||
@@ -67,8 +94,44 @@ class DirectorService:
|
||||
method=method
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return resp.read().decode()
|
||||
# Try local HTTP first (SSH tunnel + kubectl port-forward on VM)
|
||||
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 ──────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import paramiko
|
||||
from app.utils.ssh_key import resolve_ssh_key
|
||||
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
|
||||
|
||||
KEEPALIVE_INTERVAL = 15
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -37,6 +39,11 @@ class SSHService:
|
||||
transport = self._client.get_transport()
|
||||
if transport and transport.is_active():
|
||||
return self._client
|
||||
logger.debug("SSH: closing stale client before reconnect")
|
||||
try:
|
||||
self._client.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._client = None
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
@@ -56,6 +63,9 @@ class SSHService:
|
||||
try:
|
||||
client.connect(**connect_kwargs)
|
||||
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:
|
||||
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
||||
raise
|
||||
|
||||
Reference in new issue
Block a user