Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b0bffe464 | ||
|
|
ce241a283d | ||
|
|
91944a0213 | ||
|
|
421b37e854 |
No files matched your search
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
||||||
|
|
||||||
> “A comprehensive web-based management dashboard for Dune: Awakening private servers.”
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
@@ -26,26 +24,18 @@ chmod +x start.sh
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
||||||
|
- **In-Game Notifications** — instant broadcasts plus scheduled one-shot/daily/weekly/monthly messages
|
||||||
|
- **Graceful Shutdown / Restart** — in-game countdown warnings with cancel notices, plus scheduled restarts
|
||||||
|
- **Battlegroup Control** — start/stop/restart/update, with update blocked while players are online
|
||||||
- **Chat Logs** with channel filtering and auto-refresh
|
- **Chat Logs** with channel filtering and auto-refresh
|
||||||
- **Director Tools** (battlegroups, world state, transfers)
|
- **Director Tools** (battlegroups, world state, transfers)
|
||||||
- **SSH File Browser** + **in-browser shell**
|
- **SSH File Browser** (jailed to allowed directories) + **in-browser shell**
|
||||||
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
|
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
|
||||||
- **Nav Layout** — switch between horizontal and vertical sidebar; persists preference; auto-enables sidebar on mobile
|
- **Backup & Restore** — encrypted full-server snapshots with scheduled backups and retention cleanup
|
||||||
|
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources with verification
|
||||||
- **Firewall Hardening** via iptables
|
- **Firewall Hardening** via iptables
|
||||||
- **Auto‑Update** with safe file replacement
|
- **HTTPS + Remote Access** (self-signed or Let's Encrypt)
|
||||||
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
|
- **Cross-Platform Launchers** (Windows + Linux/macOS, incl. debug mode and SSH key rotation)
|
||||||
- **Cross‑Platform Launchers**
|
|
||||||
- **Organized Logging** with automatic cleanup and redaction
|
|
||||||
- **Debug Mode** with full SSH/K8s tracing
|
|
||||||
- **SSH Key Rotation** — scan all key locations and sync the newest key
|
|
||||||
- **Backup & Restore** — full server snapshots (game DB, K8s resources, RMQ config, dashboard schema) with optional AES-256 encryption and password protection
|
|
||||||
- **Scheduled Backups** — configurable interval or day/time-based scheduling with automatic retention cleanup
|
|
||||||
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources (secret, YAML, BattleGroup CR) with verification
|
|
||||||
- **Graceful Shutdown / Restart** — in-game countdown warnings, then `battlegroup stop` / `restart`, with cancel notices
|
|
||||||
- **Custom Notifications** — instant in-game broadcasts, plus scheduled one-shot/daily/weekly/monthly messages
|
|
||||||
- **Scheduled Restarts** — daily/weekly/monthly/one-shot with the same countdown, enable/disable/clear without losing settings
|
|
||||||
- **Battlegroup Update Guard** — update refuses while game servers are online
|
|
||||||
- **Jailed File Browser** — restricted to configured directories with symlink-aware checks
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -70,36 +60,12 @@ DuneDashboard/
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Security
|
|
||||||
|
|
||||||
- `settings.yaml` is never committed
|
|
||||||
- SSH keys stored with restricted permissions
|
|
||||||
- All DB queries parameterized
|
|
||||||
- No raw SQL console — the old experimental query/execute endpoints were removed entirely
|
|
||||||
- Shell parameters validated and quoted throughout
|
|
||||||
- File browser jailed to allowed directories
|
|
||||||
- All mutations audited
|
|
||||||
- CSP, HSTS, X‑Frame‑Options enforced in production
|
|
||||||
|
|
||||||
> Because letting users run `DROP TABLE` from a web UI is how horror stories begin — so that UI no longer exists.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Branching Strategy
|
|
||||||
|
|
||||||
- **main** — stable-ish beta
|
|
||||||
- **experimental** — where chaos becomes innovation
|
|
||||||
|
|
||||||
> “This seemed like a great idea at 3am.” — every experimental commit ever
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Source Available under the **Dune Dashboard Source License (DDSL)**
|
Source Available under the **Dune Dashboard Source License (DDSL)**
|
||||||
|
|||||||
+6
-3
@@ -174,9 +174,12 @@ def create_app(settings_path=None):
|
|||||||
log_response_details(logging.getLogger(), response, duration * 1000)
|
log_response_details(logging.getLogger(), response, duration * 1000)
|
||||||
logging.getLogger().debug("=" * 60)
|
logging.getLogger().debug("=" * 60)
|
||||||
else:
|
else:
|
||||||
# Only log API requests to avoid noise
|
# Quiet console in normal mode: routine requests (including
|
||||||
if request.path.startswith('/api') or request.path.startswith('/server'):
|
# scanner 404s) are not logged. Turn on debug logging
|
||||||
logging.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
# (launcher option 4) to see every request. Server errors
|
||||||
|
# still surface so real problems are never silent.
|
||||||
|
if response.status_code >= 500:
|
||||||
|
logging.error(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
||||||
|
|
||||||
# Add timing header
|
# Add timing header
|
||||||
response.headers['X-Response-Time'] = f"{duration:.3f}s"
|
response.headers['X-Response-Time'] = f"{duration:.3f}s"
|
||||||
|
|||||||
+33
-11
@@ -43,6 +43,27 @@ def fb_within_roots(canonical, roots):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def fb_resolve_canonical(raw, lexical, run_fn, timeout=10):
|
||||||
|
"""Pick a canonical path using the best realpath the target supports.
|
||||||
|
|
||||||
|
- GNU coreutils: ``realpath -m`` works, even for not-yet-existing paths.
|
||||||
|
- BusyBox (e.g. Alpine): no ``-m`` flag, so it is retried as plain
|
||||||
|
``realpath`` (works for existing paths, resolves symlinks).
|
||||||
|
- Otherwise the lexical path is used (``..`` already collapsed, but
|
||||||
|
symlinks stay unresolved).
|
||||||
|
|
||||||
|
``run_fn(command, timeout)`` executes in the target context and returns
|
||||||
|
``(stdout, stderr, returncode)``. Returns the canonical path string.
|
||||||
|
"""
|
||||||
|
out, err, rc = run_fn(f'realpath -m -- {quote_remote(raw)}', timeout)
|
||||||
|
if rc == 0 and (out or '').strip():
|
||||||
|
return (out or '').strip().split('\n')[0].strip()
|
||||||
|
out, err, rc = run_fn(f'realpath -- {quote_remote(raw)}', timeout)
|
||||||
|
if rc == 0 and (out or '').strip():
|
||||||
|
return (out or '').strip().split('\n')[0].strip()
|
||||||
|
return lexical
|
||||||
|
|
||||||
|
|
||||||
def register_api_routes(app, services, settings):
|
def register_api_routes(app, services, settings):
|
||||||
db = services['db']
|
db = services['db']
|
||||||
ssh = services['ssh']
|
ssh = services['ssh']
|
||||||
@@ -1041,14 +1062,15 @@ def register_api_routes(app, services, settings):
|
|||||||
import posixpath
|
import posixpath
|
||||||
roots = _fb_allowed_roots()
|
roots = _fb_allowed_roots()
|
||||||
lexical = posixpath.normpath(raw)
|
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():
|
def _run(command, timeout):
|
||||||
canonical = (out or '').strip().split('\n')[0].strip()
|
# Probe commands are expected to fail on minimal toolchains
|
||||||
else:
|
# (e.g. BusyBox realpath without -m): keep them out of the logs.
|
||||||
# realpath unavailable in this context: fall back to the lexical
|
return _fb_exec(command, pod_name, timeout=timeout, quiet=True)
|
||||||
# path (still blocks '..' escapes; symlinks stay unresolved).
|
|
||||||
logger.warning('File browser: realpath unavailable, using lexical path check')
|
canonical = fb_resolve_canonical(raw, lexical, _run, timeout)
|
||||||
canonical = lexical
|
if canonical == lexical:
|
||||||
|
logger.debug('File browser: using lexical path check (no realpath -m support)')
|
||||||
if not fb_within_roots(canonical, roots):
|
if not fb_within_roots(canonical, roots):
|
||||||
return '', 'Invalid path: outside allowed directories'
|
return '', 'Invalid path: outside allowed directories'
|
||||||
return canonical, ''
|
return canonical, ''
|
||||||
@@ -1083,10 +1105,10 @@ def register_api_routes(app, services, settings):
|
|||||||
return str(e)
|
return str(e)
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
def _fb_exec(command, pod_name=None, timeout=10):
|
def _fb_exec(command, pod_name=None, timeout=10, quiet=False):
|
||||||
"""Execute a command on the VM host or in a K8s pod."""
|
"""Execute a command on the VM host or in a K8s pod."""
|
||||||
if pod_name in _FB_VM_PODS:
|
if pod_name in _FB_VM_PODS:
|
||||||
return k8s.ssh.run(command, timeout=timeout)
|
return k8s.ssh.run(command, timeout=timeout, quiet=quiet)
|
||||||
pod = pod_name or _get_fb_pod()
|
pod = pod_name or _get_fb_pod()
|
||||||
if not pod:
|
if not pod:
|
||||||
return '', 'No pod specified or found', 1
|
return '', 'No pod specified or found', 1
|
||||||
@@ -1094,7 +1116,7 @@ def register_api_routes(app, services, settings):
|
|||||||
if err:
|
if err:
|
||||||
return '', f'Invalid pod name: {err}', 1
|
return '', f'Invalid pod name: {err}', 1
|
||||||
full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}'
|
full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}'
|
||||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
return k8s.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
|
||||||
|
|
||||||
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
||||||
"""Write a file to the pod filesystem."""
|
"""Write a file to the pod filesystem."""
|
||||||
|
|||||||
@@ -388,7 +388,7 @@ class BackupService:
|
|||||||
with open(meta_path) as f:
|
with open(meta_path) as f:
|
||||||
return json.load(f)
|
return json.load(f)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f'Could not read sidecar meta from {meta_path}: {e}')
|
logger.debug(f'Could not read sidecar meta from {meta_path}: {e}')
|
||||||
try:
|
try:
|
||||||
with tarfile.open(path, 'r:gz') as tar:
|
with tarfile.open(path, 'r:gz') as tar:
|
||||||
for m in tar.getmembers():
|
for m in tar.getmembers():
|
||||||
@@ -396,7 +396,9 @@ class BackupService:
|
|||||||
with tar.extractfile(m) as f:
|
with tar.extractfile(m) as f:
|
||||||
return json.loads(f.read().decode('utf-8'))
|
return json.loads(f.read().decode('utf-8'))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f'Could not read metadata from {path}: {e}')
|
# Expected for encrypted archives (handled by verify with a
|
||||||
|
# password) and pre-sidecar backups; not worth a warning.
|
||||||
|
logger.debug(f'Could not read metadata from {path}: {e}')
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def delete_backup(self, name):
|
def delete_backup(self, name):
|
||||||
|
|||||||
@@ -256,8 +256,15 @@ class DirectorService:
|
|||||||
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||||
name = self._map_to_scale_name(map_name)
|
name = self._map_to_scale_name(map_name)
|
||||||
cm_out, cm_err, cm_rc = self.k8s.run(
|
cm_out, cm_err, cm_rc = self.k8s.run(
|
||||||
f'get serversetscale {name} -o json')
|
f'get serversetscale {name} -o json', quiet=True)
|
||||||
if cm_rc != 0 or not cm_out:
|
if cm_rc != 0 or not cm_out:
|
||||||
|
# A missing ServerSetScale just means the map has none; only
|
||||||
|
# unexpected failures deserve a warning.
|
||||||
|
if cm_rc != 0 and 'not found' not in (cm_err or '').lower():
|
||||||
|
logger.warning("ServerSetScale lookup failed for %s: %s",
|
||||||
|
map_name, (cm_err or '')[:150])
|
||||||
|
else:
|
||||||
|
logger.debug("No ServerSetScale for %s", map_name)
|
||||||
return None
|
return None
|
||||||
return json.loads(cm_out)
|
return json.loads(cm_out)
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -11,10 +11,10 @@ class K8sService:
|
|||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
|
||||||
def run(self, kubectl_command, timeout=30):
|
def run(self, kubectl_command, timeout=30, quiet=False):
|
||||||
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
|
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
|
||||||
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
|
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
|
||||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
result = self.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
|
||||||
out, err, rc = result
|
out, err, rc = result
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
||||||
|
|||||||
+12
-3
@@ -79,12 +79,15 @@ class SSHService:
|
|||||||
self._client = client
|
self._client = client
|
||||||
return self._client
|
return self._client
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
"""Execute a remote command via SSH.
|
"""Execute a remote command via SSH.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
command: The shell command to execute.
|
command: The shell command to execute.
|
||||||
timeout: Maximum time in seconds to wait for the command.
|
timeout: Maximum time in seconds to wait for the command.
|
||||||
|
quiet: When True, expected non-zero results (e.g. probing for
|
||||||
|
an optional resource) are logged at debug level instead of
|
||||||
|
warning. Return values are unchanged.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Tuple of (stdout, stderr, return_code).
|
Tuple of (stdout, stderr, return_code).
|
||||||
@@ -103,13 +106,19 @@ class SSHService:
|
|||||||
# Debug logging for result
|
# Debug logging for result
|
||||||
logger.debug(f"SSH result: host={self.host}, user={self.user}, rc={rc}, stdout_len={len(out)}, stderr_len={len(err)}")
|
logger.debug(f"SSH result: host={self.host}, user={self.user}, rc={rc}, stdout_len={len(out)}, stderr_len={len(err)}")
|
||||||
if err and rc != 0:
|
if err and rc != 0:
|
||||||
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
if quiet:
|
||||||
|
logger.debug(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||||
if out:
|
if out:
|
||||||
logger.debug(f"SSH stdout preview: {out[:200]}")
|
logger.debug(f"SSH stdout preview: {out[:200]}")
|
||||||
|
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
cmd_short = command[:80] + '...' if len(command) > 80 else command
|
cmd_short = command[:80] + '...' if len(command) > 80 else command
|
||||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
if quiet:
|
||||||
|
logger.debug("SSH command rc=%d (quiet): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||||
|
else:
|
||||||
|
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||||
return out, err, rc
|
return out, err, rc
|
||||||
except paramiko.SSHException as e:
|
except paramiko.SSHException as e:
|
||||||
logger.error(f"SSH command error ({self.host}): {e}")
|
logger.error(f"SSH command error ({self.host}): {e}")
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Production HTTP server builder (cheroot) with noise filtering.
|
||||||
|
|
||||||
|
Cheroot writes server-level errors (e.g. scanners dropping TLS handshakes)
|
||||||
|
straight to stderr, bypassing the dashboard's log levels. The filter below
|
||||||
|
sends the known-benign handshake noise to the debug log and lets everything
|
||||||
|
else through untouched.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Fragments identifying a peer that vanished mid-handshake (typically an
|
||||||
|
# internet scanner hitting the public HTTPS port). Never real failures.
|
||||||
|
_HANDSHAKE_NOISE = (
|
||||||
|
'during handshake',
|
||||||
|
'SSLV3_ALERT',
|
||||||
|
'UNEXPECTED_EOF',
|
||||||
|
'TLSV1_ALERT',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def cheroot_error_filter(original_error_log, msg='', level=20, traceback=False):
|
||||||
|
"""Drop-in replacement for ``server.error_log``.
|
||||||
|
|
||||||
|
Handshake noise -> debug log. Everything else -> original handler.
|
||||||
|
"""
|
||||||
|
text = str(msg)
|
||||||
|
lowered = text.lower()
|
||||||
|
if any(fragment.lower() in lowered for fragment in _HANDSHAKE_NOISE):
|
||||||
|
logger.debug('TLS handshake dropped by peer: %s', text[:200])
|
||||||
|
return
|
||||||
|
original_error_log(msg, level=level, traceback=traceback)
|
||||||
|
|
||||||
|
|
||||||
|
def build_server(host, port, wsgi_app, cert_path=None, key_path=None,
|
||||||
|
numthreads=16, socket_timeout=60):
|
||||||
|
"""Build a cheroot server with timeouts, bounded queues and TLS support."""
|
||||||
|
from cheroot import wsgi as cheroot_wsgi
|
||||||
|
|
||||||
|
server = cheroot_wsgi.Server(
|
||||||
|
(host, port), wsgi_app,
|
||||||
|
numthreads=numthreads,
|
||||||
|
request_queue_size=128,
|
||||||
|
timeout=socket_timeout,
|
||||||
|
accepted_queue_size=128,
|
||||||
|
accepted_queue_timeout=10,
|
||||||
|
)
|
||||||
|
if cert_path and key_path:
|
||||||
|
from cheroot.ssl.builtin import BuiltinSSLAdapter
|
||||||
|
server.ssl_adapter = BuiltinSSLAdapter(cert_path, key_path)
|
||||||
|
original = server.error_log
|
||||||
|
server.error_log = lambda msg='', level=20, traceback=False: \
|
||||||
|
cheroot_error_filter(original, msg, level=level, traceback=traceback)
|
||||||
|
return server
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Self-watchdog - exits the process when the dashboard stops responding.
|
||||||
|
|
||||||
|
The dashboard is exposed to the public internet, where scanners constantly
|
||||||
|
open connections that never complete. If the WSGI server ever wedges again
|
||||||
|
(accepts TCP but never answers HTTP), this thread is the backstop: after a
|
||||||
|
grace period it probes a light local endpoint, and if the probes keep
|
||||||
|
failing it exits with a dedicated exit code so the launcher restarts us.
|
||||||
|
|
||||||
|
Exit code 42 = watchdog trip (launcher auto-restarts, tunnels stay up).
|
||||||
|
Any other exit (e.g. Ctrl+C -> 0) shuts down normally.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import ssl as sslmod
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
WATCHDOG_EXIT_CODE = 42
|
||||||
|
|
||||||
|
|
||||||
|
def probe(host, port, use_ssl, path='/login', timeout=10):
|
||||||
|
"""Single liveness probe. True when the server answers HTTP."""
|
||||||
|
conn = None
|
||||||
|
try:
|
||||||
|
if use_ssl:
|
||||||
|
ctx = sslmod._create_unverified_context()
|
||||||
|
conn = http.client.HTTPSConnection(host, port, timeout=timeout, context=ctx)
|
||||||
|
else:
|
||||||
|
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||||
|
conn.request('GET', path)
|
||||||
|
resp = conn.getresponse()
|
||||||
|
# Any HTTP response (even 4xx/5xx) proves the server is alive.
|
||||||
|
return 200 <= resp.status < 600
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
if conn:
|
||||||
|
conn.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def start_watchdog(host, port, use_ssl):
|
||||||
|
"""Start the watchdog thread. Returns the thread (daemon)."""
|
||||||
|
interval = int(os.environ.get('DUNE_WATCHDOG_INTERVAL', '30'))
|
||||||
|
grace = int(os.environ.get('DUNE_WATCHDOG_GRACE', '180'))
|
||||||
|
failures_needed = int(os.environ.get('DUNE_WATCHDOG_FAILURES', '3'))
|
||||||
|
if os.environ.get('DUNE_WATCHDOG', '1') == '0':
|
||||||
|
logger.info('Watchdog: disabled via DUNE_WATCHDOG=0')
|
||||||
|
return None
|
||||||
|
|
||||||
|
# The server may bind all interfaces or a specific IP; always probe
|
||||||
|
# loopback when possible so the check never depends on the network.
|
||||||
|
probe_host = '127.0.0.1' if host in ('0.0.0.0', '127.0.0.1', 'localhost') else host
|
||||||
|
started = time.time()
|
||||||
|
|
||||||
|
def _watch():
|
||||||
|
failures = 0
|
||||||
|
while True:
|
||||||
|
time.sleep(interval)
|
||||||
|
if time.time() - started < grace:
|
||||||
|
continue
|
||||||
|
if probe(probe_host, port, use_ssl):
|
||||||
|
failures = 0
|
||||||
|
continue
|
||||||
|
failures += 1
|
||||||
|
logger.warning(f'Watchdog: self-check failed ({failures}/{failures_needed})')
|
||||||
|
if failures >= failures_needed:
|
||||||
|
logger.critical(
|
||||||
|
'Watchdog: dashboard unresponsive - exiting '
|
||||||
|
f'with code {WATCHDOG_EXIT_CODE} for launcher restart')
|
||||||
|
print(' [WATCHDOG] Dashboard unresponsive - exiting for launcher restart',
|
||||||
|
flush=True)
|
||||||
|
os._exit(WATCHDOG_EXIT_CODE)
|
||||||
|
|
||||||
|
thread = threading.Thread(target=_watch, daemon=True, name='watchdog')
|
||||||
|
thread.start()
|
||||||
|
logger.info(
|
||||||
|
f'Watchdog: probing {probe_host}:{port} every {interval}s '
|
||||||
|
f'(grace {grace}s, {failures_needed} failures to trip)')
|
||||||
|
return thread
|
||||||
+30
-67
@@ -149,17 +149,6 @@ function Write-LogNoConsole {
|
|||||||
Add-Content -Path $logFile -Value $sanitizedEntry -Encoding UTF8
|
Add-Content -Path $logFile -Value $sanitizedEntry -Encoding UTF8
|
||||||
}
|
}
|
||||||
|
|
||||||
function Start-LogSession {
|
|
||||||
param([string]$SessionName = "Launcher Session")
|
|
||||||
$sessionFile = Join-Path $LauncherLogDir "$LogDate-$LogTime-session.log"
|
|
||||||
$header = "=" * 60
|
|
||||||
$sanitizedName = Sanitize-LogMessage -Message $SessionName
|
|
||||||
Add-Content -Path $sessionFile -Value (Sanitize-LogMessage -Message $header) -Encoding UTF8
|
|
||||||
Add-Content -Path $sessionFile -Value "$sanitizedName - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -Encoding UTF8
|
|
||||||
Add-Content -Path $sessionFile -Value (Sanitize-LogMessage -Message $header) -Encoding UTF8
|
|
||||||
return $sessionFile
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-Step {
|
function Write-Step {
|
||||||
param([string]$Name, [string]$Category = "general")
|
param([string]$Name, [string]$Category = "general")
|
||||||
if (-not $global:StepCounter) { $global:StepCounter = @{} }
|
if (-not $global:StepCounter) { $global:StepCounter = @{} }
|
||||||
@@ -169,16 +158,6 @@ function Write-Step {
|
|||||||
Write-Log -Message "[$num] $Name" -Level "INFO" -Category $Category
|
Write-Log -Message "[$num] $Name" -Level "INFO" -Category $Category
|
||||||
}
|
}
|
||||||
|
|
||||||
function Write-Success {
|
|
||||||
param([string]$Message, [string]$Category = "general")
|
|
||||||
Write-Log -Message $Message -Level "INFO" -Category $Category
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-DebugLog {
|
|
||||||
param([string]$Message, [string]$Category = "general")
|
|
||||||
Write-Log -Message $Message -Level "DEBUG" -Category $Category
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-Sep {
|
function Write-Sep {
|
||||||
param([string]$Title, [string]$Category = "general")
|
param([string]$Title, [string]$Category = "general")
|
||||||
$sep = "-" * 55
|
$sep = "-" * 55
|
||||||
@@ -191,26 +170,6 @@ function Write-Sep {
|
|||||||
Write-Host $msg -ForegroundColor DarkGray
|
Write-Host $msg -ForegroundColor DarkGray
|
||||||
}
|
}
|
||||||
|
|
||||||
$Script:LogIndent = 0
|
|
||||||
|
|
||||||
function Push-Indent {
|
|
||||||
$Script:LogIndent++
|
|
||||||
}
|
|
||||||
|
|
||||||
function Pop-Indent {
|
|
||||||
$Script:LogIndent = [Math]::Max(0, $Script:LogIndent - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-LogStyled {
|
|
||||||
param(
|
|
||||||
[string]$Message,
|
|
||||||
[string]$Level = "INFO",
|
|
||||||
[string]$Category = "general"
|
|
||||||
)
|
|
||||||
$prefix = if ($Script:LogIndent -gt 0) { " " * $Script:LogIndent } else { "" }
|
|
||||||
Write-Log -Message "$prefix$Message" -Level $Level -Category $Category
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Log Rotation & Cleanup ────────────────────────────────────────────
|
# ── Log Rotation & Cleanup ────────────────────────────────────────────
|
||||||
# Prevents logs from growing unbounded.
|
# Prevents logs from growing unbounded.
|
||||||
# - Deletes log files older than $LogRetentionDays
|
# - Deletes log files older than $LogRetentionDays
|
||||||
@@ -790,22 +749,6 @@ function Run-Diagnostics {
|
|||||||
}
|
}
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
# Backend dependencies check
|
|
||||||
Write-Host "[CHECK] New Dashboard Backend Dependencies..." -ForegroundColor Yellow
|
|
||||||
$backendReqs = Join-Path $ProjectRoot "backend\requirements.txt"
|
|
||||||
if (Test-Path $backendReqs) {
|
|
||||||
python -c "import pydantic, httpx, uvicorn" 2>$null
|
|
||||||
if ($LASTEXITCODE -eq 0) {
|
|
||||||
Write-Host " Backend deps: INSTALLED" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host " Backend deps: MISSING (run: pip install -r backend\requirements.txt)" -ForegroundColor Yellow
|
|
||||||
$issues++
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Write-Host " Backend deps: SKIPPED (no backend/requirements.txt)" -ForegroundColor DarkGray
|
|
||||||
}
|
|
||||||
Write-Host ""
|
|
||||||
|
|
||||||
# Offer port forward guide
|
# Offer port forward guide
|
||||||
Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan
|
Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan
|
||||||
$showGuide = Read-Host " "
|
$showGuide = Read-Host " "
|
||||||
@@ -939,11 +882,10 @@ function Reset-ToFactoryDefaults {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " [WARNING] This will permanently delete the following:" -ForegroundColor Red
|
Write-Host " [WARNING] This will permanently delete the following:" -ForegroundColor Red
|
||||||
Write-Host " - settings.yaml (all configuration)" -ForegroundColor Yellow
|
Write-Host " - settings.yaml (all configuration)" -ForegroundColor Yellow
|
||||||
Write-Host " - logs/, app/logs/, backend/logs/ (log files)" -ForegroundColor Yellow
|
Write-Host " - logs/, app/logs/ (log files)" -ForegroundColor Yellow
|
||||||
Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow
|
Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow
|
||||||
Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow
|
Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow
|
||||||
Write-Host " - __pycache__/ (Python cache in app/, backend/)" -ForegroundColor Yellow
|
Write-Host " - __pycache__/ (Python cache in app/)" -ForegroundColor Yellow
|
||||||
Write-Host " - frontend/node_modules/ (npm dependencies)" -ForegroundColor Yellow
|
|
||||||
Write-Host " - internal-scripts/ssh/ (copied SSH key)" -ForegroundColor Yellow
|
Write-Host " - internal-scripts/ssh/ (copied SSH key)" -ForegroundColor Yellow
|
||||||
Write-Host " - Temp scripts (read_settings*, hash_pw*, ssh_*, etc.)" -ForegroundColor Yellow
|
Write-Host " - Temp scripts (read_settings*, hash_pw*, ssh_*, etc.)" -ForegroundColor Yellow
|
||||||
Write-Host " - Test & build artifacts" -ForegroundColor Yellow
|
Write-Host " - Test & build artifacts" -ForegroundColor Yellow
|
||||||
@@ -985,7 +927,7 @@ function Reset-ToFactoryDefaults {
|
|||||||
if (Test-Path $sshKeyDir) { Remove-Item $sshKeyDir -Recurse -Force; Write-Host " Deleted internal-scripts/ssh/" -ForegroundColor Green; $count++ }
|
if (Test-Path $sshKeyDir) { Remove-Item $sshKeyDir -Recurse -Force; Write-Host " Deleted internal-scripts/ssh/" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- Python __pycache__ directories --
|
# -- Python __pycache__ directories --
|
||||||
$cacheSearchPaths = @("app", "backend")
|
$cacheSearchPaths = @("app")
|
||||||
$totalCacheDirs = 0
|
$totalCacheDirs = 0
|
||||||
foreach ($csp in $cacheSearchPaths) {
|
foreach ($csp in $cacheSearchPaths) {
|
||||||
$cspPath = Join-Path $ProjectRoot $csp
|
$cspPath = Join-Path $ProjectRoot $csp
|
||||||
@@ -997,10 +939,6 @@ function Reset-ToFactoryDefaults {
|
|||||||
if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force; $totalCacheDirs++ }
|
if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force; $totalCacheDirs++ }
|
||||||
if ($totalCacheDirs -gt 0) { Write-Host " Deleted $totalCacheDirs __pycache__ folder(s)" -ForegroundColor Green; $count++ }
|
if ($totalCacheDirs -gt 0) { Write-Host " Deleted $totalCacheDirs __pycache__ folder(s)" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- frontend/node_modules --
|
|
||||||
if (Test-Path (Join-Path $ProjectRoot "frontend\node_modules")) { Remove-Item (Join-Path $ProjectRoot "frontend\node_modules") -Recurse -Force; Write-Host " Deleted frontend/node_modules/" -ForegroundColor Green; $count++ }
|
|
||||||
if (Test-Path (Join-Path $ProjectRoot "frontend\package-lock.json")) { Remove-Item (Join-Path $ProjectRoot "frontend\package-lock.json") -Force; Write-Host " Deleted frontend/package-lock.json" -ForegroundColor Green; $count++ }
|
|
||||||
|
|
||||||
# -- Temp scripts generated during setup --
|
# -- Temp scripts generated during setup --
|
||||||
$tempPatterns = @("read_settings*.py", "hash_pw*.py", "ssh_cmd.bat", "ssh_pf_*.bat", "certbot-out.txt", "temp_*.py", "temp_*.ps1", "temp_*.sh", "check_*.py", "fix_*.py", "parse_*.ps1", "find_*.py")
|
$tempPatterns = @("read_settings*.py", "hash_pw*.py", "ssh_cmd.bat", "ssh_pf_*.bat", "certbot-out.txt", "temp_*.py", "temp_*.ps1", "temp_*.sh", "check_*.py", "fix_*.py", "parse_*.ps1", "find_*.py")
|
||||||
$tempDeleted = 0
|
$tempDeleted = 0
|
||||||
@@ -1011,7 +949,7 @@ function Reset-ToFactoryDefaults {
|
|||||||
if ($tempDeleted -gt 0) { Write-Host " Deleted $tempDeleted temp script(s)" -ForegroundColor Green; $count++ }
|
if ($tempDeleted -gt 0) { Write-Host " Deleted $tempDeleted temp script(s)" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- Test & build artifacts --
|
# -- Test & build artifacts --
|
||||||
$artifactDirs = @(".pytest_cache", "htmlcov", "build", "backups", "frontend\.vite")
|
$artifactDirs = @(".pytest_cache", "htmlcov", "build", "backups")
|
||||||
foreach ($ad in $artifactDirs) {
|
foreach ($ad in $artifactDirs) {
|
||||||
$ap = Join-Path $ProjectRoot $ad
|
$ap = Join-Path $ProjectRoot $ad
|
||||||
if (Test-Path $ap) { Remove-Item $ap -Recurse -Force; Write-Host " Deleted $ad/" -ForegroundColor Green; $count++ }
|
if (Test-Path $ap) { Remove-Item $ap -Recurse -Force; Write-Host " Deleted $ad/" -ForegroundColor Green; $count++ }
|
||||||
@@ -2461,7 +2399,32 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
Set-Location -LiteralPath $ProjectRoot
|
Set-Location -LiteralPath $ProjectRoot
|
||||||
python run.py
|
# Exit code 42 = watchdog tripped (dashboard wedged) - restart it
|
||||||
|
# automatically, tunnels stay up. Anything else shuts down normally.
|
||||||
|
# The python check pins down $LASTEXITCODE so a failed launch can never
|
||||||
|
# inherit a stale 42 from an earlier command.
|
||||||
|
if (-not (Get-Command python -ErrorAction SilentlyContinue)) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [ERROR] Python not found on PATH. Cannot start dashboard." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
$watchdogRestarts = 0
|
||||||
|
while ($true) {
|
||||||
|
python run.py
|
||||||
|
$exitCode = $LASTEXITCODE
|
||||||
|
if ($exitCode -eq 42 -and $watchdogRestarts -lt 5) {
|
||||||
|
$watchdogRestarts++
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [WARN] Dashboard stopped responding (watchdog) - restarting ($watchdogRestarts/5)..." -ForegroundColor Yellow
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ($exitCode -eq 42) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [ERROR] Dashboard keeps freezing - giving up auto-restart. Check the setup and start manually." -ForegroundColor Red
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
|
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ Flask-WTF==1.2.2
|
|||||||
Flask-Limiter==3.5.0
|
Flask-Limiter==3.5.0
|
||||||
cryptography>=42.0.0
|
cryptography>=42.0.0
|
||||||
argon2-cffi==23.1.0
|
argon2-cffi==23.1.0
|
||||||
|
cheroot==10.0.1
|
||||||
@@ -30,6 +30,23 @@ if __name__ == '__main__':
|
|||||||
cert_path = str(ssl_cert).strip("'\"")
|
cert_path = str(ssl_cert).strip("'\"")
|
||||||
key_path = str(ssl_key).strip("'\"")
|
key_path = str(ssl_key).strip("'\"")
|
||||||
if os.path.exists(cert_path) and os.path.exists(key_path):
|
if os.path.exists(cert_path) and os.path.exists(key_path):
|
||||||
|
try:
|
||||||
|
with open(cert_path, 'rb'):
|
||||||
|
pass
|
||||||
|
with open(key_path, 'rb'):
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
print(f"\n [ERROR] Cannot read SSL files (permission denied):")
|
||||||
|
print(f" [ERROR] {cert_path}")
|
||||||
|
print(f" [ERROR] {key_path}")
|
||||||
|
print(f" [ERROR] The dashboard runs as '{os.environ.get('USERNAME', 'unknown')}'")
|
||||||
|
print(" [ERROR] but these files are only readable by an Administrator.")
|
||||||
|
print(" [ERROR] Fix with ONE of:")
|
||||||
|
print(" [ERROR] 1. Run the launcher as Administrator (right-click -> Run as administrator)")
|
||||||
|
print(" [ERROR] 2. Grant yourself read access, e.g. in an elevated terminal:")
|
||||||
|
print(f' [ERROR] icacls "{cert_path}" /grant "%USERNAME%:(R)"')
|
||||||
|
print(f' [ERROR] icacls "{key_path}" /grant "%USERNAME%:(R)"\n')
|
||||||
|
sys.exit(1)
|
||||||
ssl_context = (cert_path, key_path)
|
ssl_context = (cert_path, key_path)
|
||||||
protocol = "https"
|
protocol = "https"
|
||||||
else:
|
else:
|
||||||
@@ -136,4 +153,35 @@ if __name__ == '__main__':
|
|||||||
elif ssl_context:
|
elif ssl_context:
|
||||||
print(" HTTP redirect: Disabled (visit the HTTPS URL directly)\n")
|
print(" HTTP redirect: Disabled (visit the HTTPS URL directly)\n")
|
||||||
|
|
||||||
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
# Self-watchdog: exits with code 42 if the server stops answering,
|
||||||
|
# so the launcher can restart it (tunnels stay up).
|
||||||
|
from app.utils.watchdog import start_watchdog
|
||||||
|
start_watchdog(host, port, use_ssl=bool(ssl_context))
|
||||||
|
|
||||||
|
# Serve with cheroot (production WSGI) instead of the Flask dev server:
|
||||||
|
# per-connection socket timeouts plus bounded queues mean half-open
|
||||||
|
# scanner connections are reaped instead of wedging the dashboard.
|
||||||
|
# Socket.IO keeps working (threading mode = HTTP long-polling, which
|
||||||
|
# runs on any WSGI server).
|
||||||
|
try:
|
||||||
|
import cheroot
|
||||||
|
from app.utils.http_server import build_server
|
||||||
|
except ImportError:
|
||||||
|
logging.getLogger(__name__).warning(
|
||||||
|
"cheroot not installed - falling back to dev server "
|
||||||
|
"(no connection timeouts)")
|
||||||
|
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
if ssl_context:
|
||||||
|
server = build_server(host, port, app, cert_path, key_path)
|
||||||
|
print(f" Server: cheroot (16 threads, 60s socket timeout, TLS on)")
|
||||||
|
else:
|
||||||
|
server = build_server(host, port, app)
|
||||||
|
print(f" Server: cheroot (16 threads, 60s socket timeout)")
|
||||||
|
except OSError as e:
|
||||||
|
print(f"\n [ERROR] Could not start TLS server: {e}")
|
||||||
|
print(" [ERROR] If this is a permission error, run the launcher as Administrator once,\n")
|
||||||
|
sys.exit(1)
|
||||||
|
print(f" Watchdog: enabled (exit code 42 triggers launcher restart)\n")
|
||||||
|
server.start()
|
||||||
@@ -192,6 +192,78 @@ AUTH_USER="${AUTH_USER:-admin}"
|
|||||||
read -rsp " Admin Password: " AUTH_PASS
|
read -rsp " Admin Password: " AUTH_PASS
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
|
# RMQ tunnel ports
|
||||||
|
echo ""
|
||||||
|
echo " RabbitMQ tunnel ports (local forwards to the game server)"
|
||||||
|
read -rp " RMQ Admin Port [30325]: " RMQ_ADMIN_PORT
|
||||||
|
RMQ_ADMIN_PORT="${RMQ_ADMIN_PORT:-30325}"
|
||||||
|
read -rp " RMQ Game Port [32716]: " RMQ_GAME_PORT
|
||||||
|
RMQ_GAME_PORT="${RMQ_GAME_PORT:-32716}"
|
||||||
|
|
||||||
|
# Remote access
|
||||||
|
echo ""
|
||||||
|
echo " Remote access:"
|
||||||
|
echo " Local only (n) - access from this machine only (recommended)"
|
||||||
|
echo " Remote (y) - access from other devices on your network"
|
||||||
|
read -rp " Enable remote access? (y/N): " ENABLE_REMOTE
|
||||||
|
DASH_HOST="127.0.0.1"
|
||||||
|
SSL_CERT="null"
|
||||||
|
SSL_KEY="null"
|
||||||
|
SSL_DOMAIN="null"
|
||||||
|
SSL_EMAIL="null"
|
||||||
|
HTTP_REDIRECT="false"
|
||||||
|
if [ "$ENABLE_REMOTE" = "y" ] || [ "$ENABLE_REMOTE" = "Y" ]; then
|
||||||
|
DASH_HOST="0.0.0.0"
|
||||||
|
echo ""
|
||||||
|
echo " Remote access needs HTTPS. You can use a domain with Let's Encrypt"
|
||||||
|
echo " or fall back to a self-signed certificate (browser warning)."
|
||||||
|
read -rp " Domain name (leave blank to use a self-signed certificate): " SSL_DOMAIN_IN
|
||||||
|
if [ -n "$SSL_DOMAIN_IN" ]; then
|
||||||
|
read -rp " Email address (required by Let's Encrypt): " SSL_EMAIL_IN
|
||||||
|
if command -v certbot &>/dev/null && [ -n "$SSL_EMAIL_IN" ]; then
|
||||||
|
echo " Requesting Let's Encrypt certificate for $SSL_DOMAIN_IN..."
|
||||||
|
if sudo certbot certonly --standalone --non-interactive --agree-tos -m "$SSL_EMAIL_IN" -d "$SSL_DOMAIN_IN" 2>/dev/null; then
|
||||||
|
SSL_CERT="/etc/letsencrypt/live/${SSL_DOMAIN_IN}/fullchain.pem"
|
||||||
|
SSL_KEY="/etc/letsencrypt/live/${SSL_DOMAIN_IN}/privkey.pem"
|
||||||
|
SSL_DOMAIN="$SSL_DOMAIN_IN"
|
||||||
|
SSL_EMAIL="$SSL_EMAIL_IN"
|
||||||
|
echo " Let's Encrypt certificate issued."
|
||||||
|
else
|
||||||
|
echo " [WARN] Let's Encrypt failed (port 80 must be reachable). Falling back to self-signed."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " [WARN] certbot not found or no email given. Falling back to self-signed."
|
||||||
|
echo " Install with: sudo apt install certbot (Ubuntu/Debian)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$SSL_CERT" = "null" ]; then
|
||||||
|
echo ""
|
||||||
|
read -rp " This machine's IP for the certificate [127.0.0.1]: " HOST_IP
|
||||||
|
HOST_IP="${HOST_IP:-127.0.0.1}"
|
||||||
|
mkdir -p "$PROJECT_ROOT/ssl"
|
||||||
|
if $PYTHON -c "
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, '$PROJECT_ROOT')
|
||||||
|
from app.utils.ssl import generate_cert
|
||||||
|
generate_cert('$PROJECT_ROOT/ssl/cert.pem', '$PROJECT_ROOT/ssl/key.pem', common_name='$HOST_IP', san_ips=['$HOST_IP', '127.0.0.1'], san_dns=['localhost'])
|
||||||
|
" 2>/dev/null; then
|
||||||
|
SSL_CERT="$PROJECT_ROOT/ssl/cert.pem"
|
||||||
|
SSL_KEY="$PROJECT_ROOT/ssl/key.pem"
|
||||||
|
else
|
||||||
|
echo " [WARN] Could not generate a certificate. Remote access will be HTTP only."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$SSL_CERT" != "null" ]; then
|
||||||
|
echo ""
|
||||||
|
echo " Optional: redirect plain http://HOST to https automatically."
|
||||||
|
echo " Requires TCP port 80 to be free."
|
||||||
|
read -rp " Enable HTTP redirect on port 80? (y/N): " HTTP_REDIRECT_IN
|
||||||
|
if [ "$HTTP_REDIRECT_IN" = "y" ] || [ "$HTTP_REDIRECT_IN" = "Y" ]; then
|
||||||
|
HTTP_REDIRECT="true"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# [5/5] Generate settings
|
# [5/5] Generate settings
|
||||||
echo ""
|
echo ""
|
||||||
echo "[5/5] Generating settings.yaml..."
|
echo "[5/5] Generating settings.yaml..."
|
||||||
@@ -227,15 +299,15 @@ server:
|
|||||||
ssh_key: ${SSH_KEY_YAML}
|
ssh_key: ${SSH_KEY_YAML}
|
||||||
|
|
||||||
dashboard:
|
dashboard:
|
||||||
host: 127.0.0.1
|
host: ${DASH_HOST}
|
||||||
port: ${DASH_PORT}
|
port: ${DASH_PORT}
|
||||||
debug: false
|
debug: false
|
||||||
secret_key: ${SECRET_KEY}
|
secret_key: ${SECRET_KEY}
|
||||||
ssl_cert: null
|
ssl_cert: ${SSL_CERT}
|
||||||
ssl_key: null
|
ssl_key: ${SSL_KEY}
|
||||||
ssl_domain: null
|
ssl_domain: ${SSL_DOMAIN}
|
||||||
ssl_email: null
|
ssl_email: ${SSL_EMAIL}
|
||||||
http_redirect: false
|
http_redirect: ${HTTP_REDIRECT}
|
||||||
http_redirect_port: 80
|
http_redirect_port: 80
|
||||||
|
|
||||||
database:
|
database:
|
||||||
@@ -276,14 +348,11 @@ logging:
|
|||||||
max_bytes: 10485760
|
max_bytes: 10485760
|
||||||
backup_count: 5
|
backup_count: 5
|
||||||
|
|
||||||
rmq:
|
rabbitmq:
|
||||||
admin_host: 127.0.0.1
|
admin_port: ${RMQ_ADMIN_PORT}
|
||||||
admin_port: 32686
|
game_port: ${RMQ_GAME_PORT}
|
||||||
game_host: 127.0.0.1
|
username: dashboard_admin
|
||||||
game_port: 32021
|
|
||||||
username: admin
|
|
||||||
password: null
|
password: null
|
||||||
ttl: 15
|
|
||||||
YAML_EOF
|
YAML_EOF
|
||||||
|
|
||||||
echo " settings.yaml created!"
|
echo " settings.yaml created!"
|
||||||
@@ -298,16 +367,30 @@ if [ -n "$SSH_KEY" ] && [ "$VM_HOST" != "YOUR_SERVER_IP" ]; then
|
|||||||
echo " (Start the dashboard with option 1 or 7 first to set up tunnels)"
|
echo " (Start the dashboard with option 1 or 7 first to set up tunnels)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$DASH_HOST" = "0.0.0.0" ] && command -v ufw &>/dev/null; then
|
||||||
|
echo ""
|
||||||
|
echo " Remote access is on. This machine's firewall may block port ${DASH_PORT}."
|
||||||
|
read -rp " Allow TCP port ${DASH_PORT} through ufw now? (requires sudo) (y/N): " UFW_ALLOW
|
||||||
|
if [ "$UFW_ALLOW" = "y" ] || [ "$UFW_ALLOW" = "Y" ]; then
|
||||||
|
sudo ufw allow "${DASH_PORT}/tcp" 2>/dev/null && echo " Firewall rule added." || echo " [WARN] Could not add firewall rule."
|
||||||
|
else
|
||||||
|
echo " Skipped. If remote access fails, run: sudo ufw allow ${DASH_PORT}/tcp"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo " Setup Complete!"
|
echo " Setup Complete!"
|
||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo ""
|
echo ""
|
||||||
echo " Next steps:"
|
echo " Next steps:"
|
||||||
echo " 1. Start the dashboard: bash start.sh -> option 1 (classic)"
|
echo " 1. Start the dashboard: bash start.sh -> option 1"
|
||||||
echo " Or try the new UI: bash start.sh -> option 7 (React)"
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " 2. Open http://localhost:${DASH_PORT} in your browser"
|
if [ "$SSL_CERT" != "null" ]; then
|
||||||
|
echo " 2. Open https://localhost:${DASH_PORT} in your browser (or your domain/IP)"
|
||||||
|
else
|
||||||
|
echo " 2. Open http://localhost:${DASH_PORT} in your browser"
|
||||||
|
fi
|
||||||
echo ""
|
echo ""
|
||||||
echo " Username: ${AUTH_USER}"
|
echo " Username: ${AUTH_USER}"
|
||||||
echo " Password: (what you entered)"
|
echo " Password: (what you entered)"
|
||||||
|
|||||||
@@ -31,9 +31,23 @@ show_menu() {
|
|||||||
echo " [3] Run Diagnostics"
|
echo " [3] Run Diagnostics"
|
||||||
echo " Check your system for common issues that could block the dashboard."
|
echo " Check your system for common issues that could block the dashboard."
|
||||||
echo ""
|
echo ""
|
||||||
echo " [7] Start New Dashboard (React + ChakraUI)"
|
echo " [4] Start Dashboard (Debug Mode)"
|
||||||
echo " Launch the modern React dashboard with auto-install."
|
echo " Start with verbose debug logging. Only use when troubleshooting."
|
||||||
echo " Backend API + frontend dev server (http://localhost:5173)"
|
echo ""
|
||||||
|
echo " [5] Reset to Factory Defaults"
|
||||||
|
echo " Wipe settings, logs, SSL files and cached keys. You must run setup again."
|
||||||
|
echo ""
|
||||||
|
echo " [6] Repair Game Database"
|
||||||
|
echo " Fix dashboard schema ownership (fixes game servers not starting)."
|
||||||
|
echo ""
|
||||||
|
echo " [7] Clean Up Old Dashboard Schema"
|
||||||
|
echo " Drop the legacy dashboard schema from the game database."
|
||||||
|
echo ""
|
||||||
|
echo " [8] Rotate SSH Key"
|
||||||
|
echo " Find the newest SSH key on this machine and sync it into the project."
|
||||||
|
echo ""
|
||||||
|
echo " [9] Trust Server Certificate"
|
||||||
|
echo " Install/remove the dashboard's self-signed cert in the system store."
|
||||||
echo ""
|
echo ""
|
||||||
echo " [Q] Quit"
|
echo " [Q] Quit"
|
||||||
echo ""
|
echo ""
|
||||||
@@ -63,7 +77,7 @@ determine_python() {
|
|||||||
|
|
||||||
test_dependencies() {
|
test_dependencies() {
|
||||||
echo " Checking Python dependencies..."
|
echo " Checking Python dependencies..."
|
||||||
$PYTHON -c "import flask, flask_socketio, yaml, flask_login, flask_wtf, flask_limiter, paramiko, argon2, cryptography" 2>/dev/null
|
$PYTHON -c "import flask, flask_socketio, yaml, flask_login, flask_wtf, flask_limiter, paramiko, argon2, cryptography, cheroot" 2>/dev/null
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo " Installing dependencies..."
|
echo " Installing dependencies..."
|
||||||
$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null && echo " Dependencies installed." || echo " [WARN] Some packages may have failed."
|
$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null && echo " Dependencies installed." || echo " [WARN] Some packages may have failed."
|
||||||
@@ -98,7 +112,8 @@ if k and k != 'null':
|
|||||||
|
|
||||||
for kp in "${key_paths[@]}"; do
|
for kp in "${key_paths[@]}"; do
|
||||||
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
||||||
echo " SSH Key: Found at $kp"
|
# Status goes to stderr so command substitution callers get a clean path on stdout.
|
||||||
|
echo " SSH Key: Found at $kp" >&2
|
||||||
echo "$kp"
|
echo "$kp"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
@@ -262,7 +277,7 @@ run_diagnostics() {
|
|||||||
|
|
||||||
# Python
|
# Python
|
||||||
echo "[1/6] Checking Python..."
|
echo "[1/6] Checking Python..."
|
||||||
if ! determine_python; then ((issues++)); fi
|
if ! determine_python; then ((++issues)); fi
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Dependencies
|
# Dependencies
|
||||||
@@ -285,7 +300,7 @@ print(s.get('server', {}).get('host', 'NOT SET'))
|
|||||||
echo " Server Host: $server_host"
|
echo " Server Host: $server_host"
|
||||||
else
|
else
|
||||||
echo " Server Host: NOT CONFIGURED (edit settings.yaml)"
|
echo " Server Host: NOT CONFIGURED (edit settings.yaml)"
|
||||||
((issues++))
|
((++issues))
|
||||||
fi
|
fi
|
||||||
dash_info=$($PYTHON -c "
|
dash_info=$($PYTHON -c "
|
||||||
import yaml
|
import yaml
|
||||||
@@ -297,7 +312,7 @@ print(f\"{d.get('host', 'N/A')}:{d.get('port', 'N/A')}\")
|
|||||||
echo " Dashboard: $dash_info"
|
echo " Dashboard: $dash_info"
|
||||||
else
|
else
|
||||||
echo " settings.yaml: NOT FOUND - Run setup first"
|
echo " settings.yaml: NOT FOUND - Run setup first"
|
||||||
((issues++))
|
((++issues))
|
||||||
fi
|
fi
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
@@ -306,7 +321,8 @@ print(f\"{d.get('host', 'N/A')}:{d.get('port', 'N/A')}\")
|
|||||||
ssh_key=$(test_ssh_key) || ((issues++))
|
ssh_key=$(test_ssh_key) || ((issues++))
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# SSH Connection
|
# SSH Connection (only when a key file was actually found, otherwise the
|
||||||
|
# missing key above is the single issue worth reporting).
|
||||||
echo "[5/6] Checking SSH Connection..."
|
echo "[5/6] Checking SSH Connection..."
|
||||||
if [ -f "$settings_file" ]; then
|
if [ -f "$settings_file" ]; then
|
||||||
server_user=$($PYTHON -c "
|
server_user=$($PYTHON -c "
|
||||||
@@ -315,7 +331,11 @@ with open('$settings_file') as f:
|
|||||||
s = yaml.safe_load(f) or {}
|
s = yaml.safe_load(f) or {}
|
||||||
print(s.get('server', {}).get('user', 'dune'))
|
print(s.get('server', {}).get('user', 'dune'))
|
||||||
" 2>/dev/null)
|
" 2>/dev/null)
|
||||||
test_ssh_connection "$ssh_key" "$server_host" "$server_user" || ((issues++))
|
if [ -f "$ssh_key" ]; then
|
||||||
|
test_ssh_connection "$ssh_key" "$server_host" "$server_user" || ((issues++))
|
||||||
|
else
|
||||||
|
echo " SSH Connection: SKIPPED (no working key)"
|
||||||
|
fi
|
||||||
else
|
else
|
||||||
echo " SSH Connection: SKIPPED (settings not available)"
|
echo " SSH Connection: SKIPPED (settings not available)"
|
||||||
fi
|
fi
|
||||||
@@ -363,13 +383,13 @@ print(s.get('server', {}).get('host', 'NOT SET'))
|
|||||||
|
|
||||||
# Offer port forward guide
|
# Offer port forward guide
|
||||||
echo " Would you like to see the Port Forwarding & Firewall guide? (y/N)"
|
echo " Would you like to see the Port Forwarding & Firewall guide? (y/N)"
|
||||||
read -r show_guide
|
read -r show_guide || true
|
||||||
if [ "$show_guide" = "y" ] || [ "$show_guide" = "Y" ]; then
|
if [ "$show_guide" = "y" ] || [ "$show_guide" = "Y" ]; then
|
||||||
show_port_forward_guide
|
show_port_forward_guide
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo " Press Enter to return to the main menu..."
|
echo " Press Enter to return to the main menu..."
|
||||||
read -r
|
read -r || true
|
||||||
}
|
}
|
||||||
|
|
||||||
run_setup() {
|
run_setup() {
|
||||||
@@ -386,7 +406,7 @@ run_setup() {
|
|||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " Press Enter to return to the main menu..."
|
echo " Press Enter to return to the main menu..."
|
||||||
read -r
|
read -r || true
|
||||||
}
|
}
|
||||||
|
|
||||||
start_dashboard() {
|
start_dashboard() {
|
||||||
@@ -413,6 +433,21 @@ start_dashboard() {
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Normal start runs with debug logging off (debug entry point sets PRESERVE_DEBUG).
|
||||||
|
if [ -z "$PRESERVE_DEBUG" ]; then
|
||||||
|
$PYTHON -c "
|
||||||
|
import yaml
|
||||||
|
p = '$settings_file'
|
||||||
|
s = yaml.safe_load(open(p)) or {}
|
||||||
|
lg = s.setdefault('logging', {})
|
||||||
|
if lg.get('debug_enabled') is True:
|
||||||
|
lg['debug_enabled'] = False
|
||||||
|
lg['level'] = 'INFO'
|
||||||
|
yaml.safe_dump(s, open(p, 'w'), default_flow_style=False, sort_keys=False)
|
||||||
|
print(' Debug logging: disabled for normal start')
|
||||||
|
" 2>/dev/null
|
||||||
|
fi
|
||||||
|
|
||||||
# Read settings
|
# Read settings
|
||||||
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 2>/dev/null)
|
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 2>/dev/null)
|
||||||
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 2>/dev/null)
|
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 2>/dev/null)
|
||||||
@@ -420,6 +455,10 @@ start_dashboard() {
|
|||||||
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['kubernetes']['namespace'])" 2>/dev/null)
|
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['kubernetes']['namespace'])" 2>/dev/null)
|
||||||
dashboard_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['dashboard']['port'])" 2>/dev/null)
|
dashboard_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['dashboard']['port'])" 2>/dev/null)
|
||||||
director_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['director']['port'])" 2>/dev/null)
|
director_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['director']['port'])" 2>/dev/null)
|
||||||
|
rmq_admin_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s.get('rabbitmq',{}).get('admin_port',30325))" 2>/dev/null)
|
||||||
|
rmq_game_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s.get('rabbitmq',{}).get('game_port',32716))" 2>/dev/null)
|
||||||
|
[ -z "$rmq_admin_port" ] && rmq_admin_port=30325
|
||||||
|
[ -z "$rmq_game_port" ] && rmq_game_port=32716
|
||||||
|
|
||||||
# Find SSH key
|
# Find SSH key
|
||||||
ssh_key_src=$($PYTHON -c "
|
ssh_key_src=$($PYTHON -c "
|
||||||
@@ -476,14 +515,18 @@ if k and k != 'null':
|
|||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Kill existing SSH tunnels on the DB/Director ports
|
# Kill existing SSH tunnels on the DB/Director/RMQ ports.
|
||||||
pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
# Each kill is guarded so an empty port can never widen the pattern
|
||||||
pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
|
# into matching unrelated SSH processes.
|
||||||
|
[ -n "$local_port" ] && pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
||||||
|
[ -n "$director_port" ] && pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
|
||||||
|
[ -n "$rmq_admin_port" ] && pkill -f "ssh.*-L.*${rmq_admin_port}" 2>/dev/null || true
|
||||||
|
[ -n "$rmq_game_port" ] && pkill -f "ssh.*-L.*${rmq_game_port}" 2>/dev/null || true
|
||||||
sleep 1
|
sleep 1
|
||||||
|
|
||||||
# [1/4] SSH Tunnel
|
# [1/4] SSH Tunnel
|
||||||
echo "[1/4] Starting SSH tunnel (localhost:$local_port -> VM)..."
|
echo "[1/4] Starting SSH tunnel (localhost:$local_port -> VM)..."
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -N "${ssh_user}@${server_host}" &
|
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -L "${rmq_admin_port}:localhost:${rmq_admin_port}" -L "${rmq_game_port}:localhost:${rmq_game_port}" -N "${ssh_user}@${server_host}" &
|
||||||
ssh_tunnel_pid=$!
|
ssh_tunnel_pid=$!
|
||||||
|
|
||||||
connected=false
|
connected=false
|
||||||
@@ -518,7 +561,7 @@ if k and k != 'null':
|
|||||||
kill $ssh_tunnel_pid 2>/dev/null
|
kill $ssh_tunnel_pid 2>/dev/null
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
echo "[OK] SSH tunnel up on localhost:$local_port"
|
echo "[OK] SSH tunnel up on localhost:$local_port (DB), localhost:$director_port (Director), localhost:$rmq_admin_port (RMQ Admin), localhost:$rmq_game_port (RMQ Game)"
|
||||||
|
|
||||||
# [2/4] DB Port-Forward
|
# [2/4] DB Port-Forward
|
||||||
echo "[2/4] Starting DB port-forward on VM..."
|
echo "[2/4] Starting DB port-forward on VM..."
|
||||||
@@ -620,7 +663,25 @@ if k and k != 'null':
|
|||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
cd "$PROJECT_ROOT"
|
cd "$PROJECT_ROOT"
|
||||||
$PYTHON run.py
|
# Exit code 42 = watchdog tripped (dashboard wedged) - restart it
|
||||||
|
# automatically, tunnels stay up. Anything else shuts down normally.
|
||||||
|
watchdog_restarts=0
|
||||||
|
while true; do
|
||||||
|
$PYTHON run.py
|
||||||
|
code=$?
|
||||||
|
if [ "$code" -eq 42 ] && [ "$watchdog_restarts" -lt 5 ]; then
|
||||||
|
watchdog_restarts=$((watchdog_restarts + 1))
|
||||||
|
echo ""
|
||||||
|
echo " [WARN] Dashboard stopped responding (watchdog) - restarting ($watchdog_restarts/5)..."
|
||||||
|
sleep 5
|
||||||
|
else
|
||||||
|
if [ "$code" -eq 42 ]; then
|
||||||
|
echo ""
|
||||||
|
echo " [ERROR] Dashboard keeps freezing - giving up auto-restart. Check the setup and start manually."
|
||||||
|
fi
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "Stopping tunnels..."
|
echo "Stopping tunnels..."
|
||||||
@@ -628,250 +689,353 @@ if k and k != 'null':
|
|||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
|
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
|
||||||
}
|
}
|
||||||
|
|
||||||
start_new_dashboard() {
|
|
||||||
echo ""
|
|
||||||
echo " Starting NEW dashboard (React + ChakraUI)..."
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Check Python
|
# ── Shared Server Helpers ───────────────────────────────────────────────
|
||||||
if ! determine_python; then
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check Node.js
|
# Load server connection details from settings.yaml.
|
||||||
if ! command -v node &>/dev/null; then
|
# Sets: server_host ssh_user namespace ssh_key. Returns non-zero on error.
|
||||||
echo " Node.js: NOT FOUND"
|
load_server_settings() {
|
||||||
echo ""
|
|
||||||
echo " Node.js 18+ is required for the new frontend."
|
|
||||||
echo " Install: https://nodejs.org/ or use nvm"
|
|
||||||
echo ""
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
echo " Node.js: $(node --version)"
|
|
||||||
|
|
||||||
# Check dependencies
|
|
||||||
test_dependencies
|
|
||||||
|
|
||||||
# Check settings
|
|
||||||
settings_file="$PROJECT_ROOT/settings.yaml"
|
settings_file="$PROJECT_ROOT/settings.yaml"
|
||||||
if [ ! -f "$settings_file" ]; then
|
if [ ! -f "$settings_file" ]; then
|
||||||
echo ""
|
echo " [ERROR] settings.yaml not found. Run setup first."
|
||||||
echo " [ERROR] settings.yaml not found. You need to run setup first."
|
return 1
|
||||||
echo ""
|
fi
|
||||||
|
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; print(s.get('server',{}).get('host',''))" 2>/dev/null)
|
||||||
|
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; print(s.get('server',{}).get('user','dune'))" 2>/dev/null)
|
||||||
|
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; print(s.get('kubernetes',{}).get('namespace',''))" 2>/dev/null)
|
||||||
|
ssh_key=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; k=s.get('server',{}).get('ssh_key',''); print(k if k and k!='null' else '')" 2>/dev/null)
|
||||||
|
if [ -z "$ssh_key" ] || [ ! -f "$ssh_key" ]; then
|
||||||
|
ssh_key=""
|
||||||
|
for kp in "$HOME/.ssh/dune-dashboard-key" "$PROJECT_ROOT/internal-scripts/ssh/sshKey" "$HOME/.ssh/id_ed25519" "$HOME/.ssh/id_rsa"; do
|
||||||
|
if [ -f "$kp" ]; then ssh_key="$kp"; break; fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [ -z "$server_host" ] || [ "$server_host" = "YOUR_SERVER_IP" ]; then
|
||||||
|
echo " [ERROR] Server IP not configured in settings.yaml."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if [ -z "$namespace" ]; then
|
||||||
|
echo " [ERROR] Kubernetes namespace not configured."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if [ ! -f "$ssh_key" ]; then
|
||||||
|
echo " [ERROR] SSH key not found."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
start_dashboard_debug() {
|
||||||
|
echo ""
|
||||||
|
echo " ============================================================"
|
||||||
|
echo " Starting Dashboard with DEBUG LOGGING enabled"
|
||||||
|
echo " ============================================================"
|
||||||
|
echo ""
|
||||||
|
echo " WARNING: Debug logging can significantly impact performance!"
|
||||||
|
echo " - Logs every HTTP request/response"
|
||||||
|
echo " - Logs all SSH commands and results"
|
||||||
|
echo " - Logs all database queries"
|
||||||
|
echo " - Only use this when troubleshooting, not for regular use"
|
||||||
|
echo ""
|
||||||
|
read -rp " Continue with debug mode? (y/N) " confirm
|
||||||
|
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
|
||||||
|
echo " Cancelled."
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
settings_file="$PROJECT_ROOT/settings.yaml"
|
||||||
# Read settings
|
if [ ! -f "$settings_file" ]; then
|
||||||
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 2>/dev/null)
|
echo " [ERROR] settings.yaml not found. Run setup first."
|
||||||
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 2>/dev/null)
|
return
|
||||||
local_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['database']['port'])" 2>/dev/null)
|
fi
|
||||||
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['kubernetes']['namespace'])" 2>/dev/null)
|
$PYTHON -c "
|
||||||
dashboard_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['dashboard']['port'])" 2>/dev/null)
|
|
||||||
director_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['director']['port'])" 2>/dev/null)
|
|
||||||
|
|
||||||
# Find SSH key (same logic as start_dashboard)
|
|
||||||
ssh_key_src=$($PYTHON -c "
|
|
||||||
import yaml
|
import yaml
|
||||||
with open('$settings_file') as f:
|
p = '$settings_file'
|
||||||
s = yaml.safe_load(f) or {}
|
s = yaml.safe_load(open(p)) or {}
|
||||||
k = s.get('server', {}).get('ssh_key', '')
|
s.setdefault('logging', {})['debug_enabled'] = True
|
||||||
if k and k != 'null':
|
yaml.safe_dump(s, open(p, 'w'), default_flow_style=False, sort_keys=False)
|
||||||
print(k)
|
" 2>/dev/null
|
||||||
" 2>/dev/null)
|
echo " Debug logging enabled for this run."
|
||||||
|
echo ""
|
||||||
|
PRESERVE_DEBUG=1 start_dashboard
|
||||||
|
}
|
||||||
|
|
||||||
ssh_key=""
|
reset_to_factory() {
|
||||||
key_paths=(
|
echo ""
|
||||||
"$ssh_key_src"
|
echo " Reset to Factory Defaults"
|
||||||
"$HOME/.ssh/dune-dashboard-key"
|
echo ""
|
||||||
"$PROJECT_ROOT/internal-scripts/ssh/sshKey"
|
echo " WARNING: This will permanently delete the following:"
|
||||||
"/tmp/dune-tunnel-key"
|
echo " - settings.yaml (all configuration)"
|
||||||
"$HOME/.ssh/id_ed25519"
|
echo " - logs/, app/logs/ (log files)"
|
||||||
"$HOME/.ssh/id_rsa"
|
echo " - instance/ (local data)"
|
||||||
)
|
echo " - ssl/ (SSL certificates)"
|
||||||
|
echo " - internal-scripts/ssh/ (copied SSH key)"
|
||||||
|
echo " - Python __pycache__ directories"
|
||||||
|
echo ""
|
||||||
|
echo " This cannot be undone. You will need to run setup again."
|
||||||
|
echo ""
|
||||||
|
read -rp " Type 'yes' to confirm: " confirmation
|
||||||
|
if [ "$confirmation" != "yes" ]; then
|
||||||
|
echo ""
|
||||||
|
echo " Reset cancelled. No changes made."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo ""
|
||||||
|
echo " Wiping all dashboard data..."
|
||||||
|
echo ""
|
||||||
|
count=0
|
||||||
|
[ -f "$PROJECT_ROOT/settings.yaml" ] && rm -f "$PROJECT_ROOT/settings.yaml" && echo " Deleted settings.yaml" && count=$((count + 1))
|
||||||
|
[ -d "$PROJECT_ROOT/instance" ] && rm -rf "$PROJECT_ROOT/instance" && echo " Deleted instance/" && count=$((count + 1))
|
||||||
|
[ -d "$PROJECT_ROOT/ssl" ] && rm -rf "$PROJECT_ROOT/ssl" && echo " Deleted ssl/" && count=$((count + 1))
|
||||||
|
[ -d "$PROJECT_ROOT/logs" ] && rm -rf "$PROJECT_ROOT/logs" && echo " Deleted logs/" && count=$((count + 1))
|
||||||
|
[ -d "$PROJECT_ROOT/app/logs" ] && rm -rf "$PROJECT_ROOT/app/logs" && echo " Deleted app/logs/" && count=$((count + 1))
|
||||||
|
[ -d "$PROJECT_ROOT/internal-scripts/ssh" ] && rm -rf "$PROJECT_ROOT/internal-scripts/ssh" && echo " Deleted internal-scripts/ssh/" && count=$((count + 1))
|
||||||
|
find "$PROJECT_ROOT/app" -type d -name "__pycache__" -prune -exec rm -rf {} + 2>/dev/null
|
||||||
|
echo " Cleaned Python caches"
|
||||||
|
echo ""
|
||||||
|
echo " Reset complete ($count items removed). Run setup (option 2) to start over."
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return to the main menu..." || true
|
||||||
|
}
|
||||||
|
|
||||||
for kp in "${key_paths[@]}"; do
|
repair_game_database() {
|
||||||
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
echo ""
|
||||||
if ssh -i "$kp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes "${ssh_user}@${server_host}" "echo ok" &>/dev/null; then
|
echo " Game Database Repair"
|
||||||
ssh_key="$kp"
|
echo " ====================="
|
||||||
echo " SSH Key: Found working key at $kp"
|
echo ""
|
||||||
break
|
if ! load_server_settings; then
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo " Server: $server_host"
|
||||||
|
echo " Namespace: $namespace"
|
||||||
|
echo ""
|
||||||
|
read -rp " This will transfer dashboard schema ownership to the dune user. Continue? (y/N) " confirm
|
||||||
|
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
|
||||||
|
echo " Cancelled."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo ""
|
||||||
|
echo "[1/4] Finding database pod..."
|
||||||
|
db_pod=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl get pods -n $namespace -l app=${namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>/dev/null)
|
||||||
|
if [ -z "$db_pod" ]; then
|
||||||
|
echo "[ERROR] Could not find database pod."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo " [OK] Database pod: $db_pod"
|
||||||
|
echo "[2/4] Running ownership fix..."
|
||||||
|
ssh -i "$ssh_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "cat > /tmp/repair.sql <<'REPAIR_EOF'
|
||||||
|
ALTER SCHEMA dashboard OWNER TO dune;
|
||||||
|
DO \$\$DECLARE r RECORD; BEGIN FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'dashboard' LOOP EXECUTE 'ALTER TABLE dashboard.' || quote_ident(r.tablename) || ' OWNER TO dune'; END LOOP; END\$\$;
|
||||||
|
DO \$\$DECLARE r RECORD; BEGIN FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'dashboard' LOOP EXECUTE 'ALTER SEQUENCE dashboard.' || quote_ident(r.sequencename) || ' OWNER TO dune'; END LOOP; END\$\$;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON TABLES TO dune;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON SEQUENCES TO dune;
|
||||||
|
REPAIR_EOF
|
||||||
|
cat /tmp/repair.sql | sudo kubectl exec -n $namespace -i $db_pod -- psql -U postgres -p 15432 -d dune
|
||||||
|
printf 'CREATE SCHEMA IF NOT EXISTS dashboard;\nGRANT ALL PRIVILEGES ON SCHEMA dashboard TO dune;\n' | sudo kubectl exec -n $namespace -i $db_pod -- psql -U postgres -p 15432 -d template1" 2>&1
|
||||||
|
echo " [OK] Ownership fix applied"
|
||||||
|
echo "[3/4] Cleaning up failed utility pods..."
|
||||||
|
deleted=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl get pods -n $namespace | grep 'db.*util' | grep -v Running | awk '{print \$1}' | xargs -r sudo kubectl delete pod -n $namespace --wait=false" 2>/dev/null)
|
||||||
|
if [ -n "$deleted" ]; then
|
||||||
|
echo "$deleted"
|
||||||
|
echo " [OK] Failed util pods deleted"
|
||||||
|
else
|
||||||
|
echo " [OK] No failed util pods found"
|
||||||
|
fi
|
||||||
|
echo "[4/4] Done!"
|
||||||
|
echo ""
|
||||||
|
echo " If game servers still show errors, restart the battlegroup,"
|
||||||
|
echo " wait for all pods to come back healthy, then start the dashboard."
|
||||||
|
echo " The dashboard also auto-fixes ownership on every startup."
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return to the menu..." || true
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup_old_dashboard_schema() {
|
||||||
|
echo ""
|
||||||
|
echo " Clean Up Old Dashboard Schema"
|
||||||
|
echo " ==============================="
|
||||||
|
echo ""
|
||||||
|
if ! load_server_settings; then
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
db_pod=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl get pods -n $namespace -l app=${namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>/dev/null)
|
||||||
|
if [ -z "$db_pod" ]; then
|
||||||
|
echo "[ERROR] Could not find database pod."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
has_old=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl exec -n $namespace -i $db_pod -- psql -U postgres -p 15432 -d dune -t -c \"SELECT count(*) FROM information_schema.schemata WHERE schema_name = 'dashboard'\" 2>&1" 2>/dev/null | tr -d '[:space:]')
|
||||||
|
if [ "$has_old" = "0" ] || [ -z "$has_old" ]; then
|
||||||
|
echo " [OK] No old dashboard schema found - nothing to clean up."
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo " [WARN] Old dashboard schema found in the game database."
|
||||||
|
echo ""
|
||||||
|
echo " This drops: dashboard.audit_log, dashboard.bans, dashboard.player_ips,"
|
||||||
|
echo " dashboard.player_actions, dashboard.chat_history, dashboard.settings"
|
||||||
|
echo ""
|
||||||
|
echo " Make sure the dashboard has migrated this data first"
|
||||||
|
echo " (it does this automatically on next startup)."
|
||||||
|
echo ""
|
||||||
|
read -rp " Type 'yes' to drop the old dashboard schema: " confirm
|
||||||
|
if [ "$confirm" != "yes" ]; then
|
||||||
|
echo " Cancelled."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
read -rp " REALLY drop? This cannot be undone. Type 'yes' again: " confirm2
|
||||||
|
if [ "$confirm2" != "yes" ]; then
|
||||||
|
echo " Cancelled."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo ""
|
||||||
|
echo " Dropping old dashboard schema..."
|
||||||
|
ssh -i "$ssh_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl exec -n $namespace -i $db_pod -- psql -U postgres -p 15432 -d dune -c \"DROP SCHEMA IF EXISTS dashboard CASCADE\" 2>&1" 2>&1
|
||||||
|
echo " [OK] Old dashboard schema dropped."
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
|
}
|
||||||
|
|
||||||
|
trust_server_cert() {
|
||||||
|
echo ""
|
||||||
|
echo " Trust Server Certificate"
|
||||||
|
echo " ========================"
|
||||||
|
echo ""
|
||||||
|
echo " Installs the dashboard's self-signed certificate into this"
|
||||||
|
echo " machine's system trust store so browsers stop warning about it."
|
||||||
|
echo " Only do this on machines you own, for your own dashboard."
|
||||||
|
echo ""
|
||||||
|
settings_file="$PROJECT_ROOT/settings.yaml"
|
||||||
|
cert=""
|
||||||
|
if [ -f "$settings_file" ]; then
|
||||||
|
cert=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; c=s.get('dashboard',{}).get('ssl_cert',''); print(c if c and c!='null' else '')" 2>/dev/null)
|
||||||
|
fi
|
||||||
|
if { [ -z "$cert" ] || [ ! -f "$cert" ]; } && [ -f "$PROJECT_ROOT/ssl/cert.pem" ]; then
|
||||||
|
cert="$PROJECT_ROOT/ssl/cert.pem"
|
||||||
|
fi
|
||||||
|
if [ -z "$cert" ] || [ ! -f "$cert" ]; then
|
||||||
|
echo " [ERROR] No server certificate found."
|
||||||
|
echo " Run setup with remote access enabled to generate one (ssl/cert.pem)."
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo " Certificate: $cert"
|
||||||
|
echo ""
|
||||||
|
if command -v update-ca-certificates &>/dev/null; then
|
||||||
|
# Debian / Ubuntu
|
||||||
|
dest="/usr/local/share/ca-certificates/dune-dashboard.crt"
|
||||||
|
if [ -f "$dest" ]; then
|
||||||
|
read -rp " Already trusted. Remove it instead? (y/N): " remove
|
||||||
|
if [ "$remove" = "y" ] || [ "$remove" = "Y" ]; then
|
||||||
|
sudo rm -f "$dest" && sudo update-ca-certificates --fresh >/dev/null 2>&1
|
||||||
|
echo " [OK] Certificate removed from system store."
|
||||||
|
else
|
||||||
|
echo " Cancelled."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
read -rp " Install into system store? (requires sudo) (y/N): " confirm
|
||||||
|
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
|
||||||
|
if sudo cp "$cert" "$dest" && sudo update-ca-certificates >/dev/null 2>&1; then
|
||||||
|
echo " [OK] Certificate trusted. Restart your browser."
|
||||||
|
else
|
||||||
|
echo " [ERROR] Install failed."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " Cancelled."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
elif command -v update-ca-trust &>/dev/null; then
|
||||||
|
# Fedora / RHEL
|
||||||
|
dest="/etc/pki/ca-trust/source/anchors/dune-dashboard.crt"
|
||||||
|
if [ -f "$dest" ]; then
|
||||||
|
read -rp " Already trusted. Remove it instead? (y/N): " remove
|
||||||
|
if [ "$remove" = "y" ] || [ "$remove" = "Y" ]; then
|
||||||
|
sudo rm -f "$dest" && sudo update-ca-trust >/dev/null 2>&1
|
||||||
|
echo " [OK] Certificate removed from system store."
|
||||||
|
else
|
||||||
|
echo " Cancelled."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
read -rp " Install into system store? (requires sudo) (y/N): " confirm
|
||||||
|
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
|
||||||
|
if sudo cp "$cert" "$dest" && sudo update-ca-trust >/dev/null 2>&1; then
|
||||||
|
echo " [OK] Certificate trusted. Restart your browser."
|
||||||
|
else
|
||||||
|
echo " [ERROR] Install failed."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " Cancelled."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
elif [ "$(uname)" = "Darwin" ]; then
|
||||||
|
# macOS: install only; removal via Keychain Access.
|
||||||
|
read -rp " Install into System keychain? (requires sudo) (y/N): " confirm
|
||||||
|
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
|
||||||
|
if sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$cert" 2>/dev/null; then
|
||||||
|
echo " [OK] Certificate trusted. Restart your browser."
|
||||||
|
echo " To remove later, delete it from Keychain Access (System keychain)."
|
||||||
|
else
|
||||||
|
echo " [ERROR] Install failed."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " Cancelled."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " [ERROR] No supported trust store tool found."
|
||||||
|
echo " Need one of: update-ca-certificates (Debian/Ubuntu),"
|
||||||
|
echo " update-ca-trust (Fedora/RHEL), or macOS security."
|
||||||
|
fi
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
|
}
|
||||||
|
|
||||||
|
rotate_ssh_key() {
|
||||||
|
echo ""
|
||||||
|
echo " Rotate SSH Key"
|
||||||
|
echo " ==============="
|
||||||
|
echo ""
|
||||||
|
target_key="$PROJECT_ROOT/internal-scripts/ssh/sshKey"
|
||||||
|
parent_key="$(dirname "$PROJECT_ROOT")/internal-scripts/ssh/sshKey"
|
||||||
|
echo " Scanning for SSH keys..."
|
||||||
|
if [ -f "$target_key" ]; then
|
||||||
|
echo " Current: $target_key (modified $(stat -c '%y' "$target_key" 2>/dev/null || stat -f '%Sm' "$target_key" 2>/dev/null))"
|
||||||
|
fi
|
||||||
|
newest=""
|
||||||
|
newest_mtime=0
|
||||||
|
for kp in "$HOME/.ssh/dune-dashboard-key" "/tmp/dune-tunnel-key" "$parent_key" "$HOME/.ssh/id_ed25519" "$HOME/.ssh/id_rsa" "$HOME/.ssh/id_ecdsa"; do
|
||||||
|
if [ -f "$kp" ]; then
|
||||||
|
mtime=$(stat -c '%Y' "$kp" 2>/dev/null || stat -f '%m' "$kp" 2>/dev/null || echo 0)
|
||||||
|
echo " Found: $kp"
|
||||||
|
if [ "$mtime" -gt "$newest_mtime" ] 2>/dev/null; then
|
||||||
|
newest_mtime=$mtime
|
||||||
|
newest=$kp
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
if [ -z "$newest" ]; then
|
||||||
if [ -z "$ssh_key" ]; then
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " [ERROR] No working SSH key found."
|
echo " No SSH keys found in any search location."
|
||||||
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
mkdir -p "$(dirname "$target_key")"
|
||||||
ssh_key_tmp="/tmp/dune-tunnel-key"
|
if [ "$newest" = "$target_key" ]; then
|
||||||
cp "$ssh_key" "$ssh_key_tmp" 2>/dev/null
|
echo ""
|
||||||
chmod 600 "$ssh_key_tmp"
|
echo " The newest key is already at the target location."
|
||||||
|
echo " No rotation needed."
|
||||||
echo ""
|
|
||||||
echo "============================================================"
|
|
||||||
echo " Dune Awakening Dashboard (React Edition)"
|
|
||||||
echo "============================================================"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Kill existing SSH tunnels
|
|
||||||
pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
|
||||||
pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
# [1/5] SSH Tunnel
|
|
||||||
echo "[1/5] Starting SSH tunnel (localhost:$local_port -> VM)..."
|
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -N "${ssh_user}@${server_host}" &
|
|
||||||
ssh_tunnel_pid=$!
|
|
||||||
|
|
||||||
connected=false
|
|
||||||
for i in $(seq 1 30); do
|
|
||||||
sleep 1
|
|
||||||
if ! kill -0 $ssh_tunnel_pid 2>/dev/null; then
|
|
||||||
echo "[ERROR] SSH tunnel exited unexpectedly."
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
if ($PYTHON -c "import socket; s=socket.socket(); s.settimeout(1); s.connect(('127.0.0.1', $local_port)); s.close()" 2>/dev/null); then
|
|
||||||
connected=true
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$connected" = false ]; then
|
|
||||||
echo "[ERROR] SSH tunnel did not connect within 30 seconds"
|
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
echo "[OK] SSH tunnel up on localhost:$local_port"
|
|
||||||
|
|
||||||
# [2/5] DB Port-Forward
|
|
||||||
echo "[2/5] Starting DB port-forward on VM..."
|
|
||||||
|
|
||||||
if [ -z "$namespace" ] || [ "$namespace" = "" ]; then
|
|
||||||
echo "[ERROR] Kubernetes namespace is empty."
|
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
db_svc="${namespace}-db-dbdepl-svc"
|
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "sudo pkill -9 -f port-forward 2>/dev/null; sleep 2" 2>/dev/null
|
|
||||||
sleep 2
|
|
||||||
|
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "nohup sudo kubectl port-forward -n ${namespace} svc/${db_svc} ${local_port}:${local_port} > /tmp/pf.log 2>&1 &" 2>/dev/null
|
|
||||||
|
|
||||||
bgd_svc="${namespace}-bgd-svc"
|
|
||||||
bgd_deploy="${namespace}-bgd-deploy"
|
|
||||||
bgd_ready=$(ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl get deployment $bgd_deploy -n $namespace -o jsonpath='{.status.readyReplicas}'" 2>/dev/null)
|
|
||||||
if [ -z "$bgd_ready" ] || [ "$bgd_ready" = "0" ]; then
|
|
||||||
echo " BGD deployment is scaled down, starting..."
|
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 "${ssh_user}@${server_host}" "sudo kubectl scale deployment $bgd_deploy -n $namespace --replicas=1" 2>/dev/null
|
|
||||||
sleep 15
|
|
||||||
fi
|
|
||||||
|
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "nohup sudo kubectl port-forward -n ${namespace} svc/${bgd_svc} ${director_port}:11717 > /tmp/director_pf.log 2>&1 &" 2>/dev/null
|
|
||||||
sleep 3
|
|
||||||
|
|
||||||
# [3/5] Database Check
|
|
||||||
echo "[3/5] Checking database..."
|
|
||||||
db_test=false
|
|
||||||
for i in $(seq 1 15); do
|
|
||||||
if $PYTHON "$PROJECT_ROOT/scripts/db_check.py" "$local_port" 2>/dev/null | grep -q "ok"; then
|
|
||||||
db_test=true
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$db_test" = false ]; then
|
|
||||||
echo "[ERROR] Database connection failed."
|
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
echo "[OK] Database connected"
|
|
||||||
|
|
||||||
# [4/5] Install Dependencies
|
|
||||||
echo "[4/5] Installing dependencies..."
|
|
||||||
|
|
||||||
# Backend Python deps
|
|
||||||
if [ -f "$PROJECT_ROOT/requirements.txt" ]; then
|
|
||||||
echo " Installing backend Python dependencies..."
|
|
||||||
$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null
|
|
||||||
$PYTHON -m pip install "psycopg[binary]" --quiet 2>/dev/null
|
|
||||||
echo " Backend dependencies OK"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Frontend npm deps
|
|
||||||
frontend_dir="$PROJECT_ROOT/frontend"
|
|
||||||
if [ -f "$frontend_dir/package.json" ]; then
|
|
||||||
if [ ! -d "$frontend_dir/node_modules" ]; then
|
|
||||||
echo " Installing frontend npm dependencies..."
|
|
||||||
(cd "$frontend_dir" && npm install --silent 2>/dev/null)
|
|
||||||
echo " Frontend dependencies installed"
|
|
||||||
else
|
|
||||||
echo " Frontend dependencies OK"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# [5/5] Start Backend + Frontend
|
|
||||||
echo "[5/5] Starting dashboard..."
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Start backend in background
|
|
||||||
echo " Starting backend API (port $dashboard_port)..."
|
|
||||||
backend_dir="$PROJECT_ROOT/backend"
|
|
||||||
(cd "$backend_dir" && $PYTHON run.py) &
|
|
||||||
backend_pid=$!
|
|
||||||
sleep 3
|
|
||||||
|
|
||||||
# Verify backend started
|
|
||||||
backend_alive=false
|
|
||||||
for i in $(seq 1 10); do
|
|
||||||
if curl -s "http://127.0.0.1:${dashboard_port}/api/health" &>/dev/null; then
|
|
||||||
backend_alive=true
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$backend_alive" = true ]; then
|
|
||||||
echo " [OK] Backend API running on port $dashboard_port"
|
|
||||||
else
|
else
|
||||||
echo " [WARN] Backend may not have started yet"
|
cp "$newest" "$target_key"
|
||||||
|
chmod 600 "$target_key"
|
||||||
|
echo ""
|
||||||
|
echo " [OK] Synced newest key ($newest) to $target_key"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Start frontend in background
|
|
||||||
echo " Starting frontend dev server (port 5173)..."
|
|
||||||
(cd "$frontend_dir" && npm run dev -- --host 0.0.0.0) &
|
|
||||||
frontend_pid=$!
|
|
||||||
sleep 5
|
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "============================================================"
|
read -rp " Press Enter to return..." || true
|
||||||
echo " New Dashboard Started!"
|
|
||||||
echo "============================================================"
|
|
||||||
echo ""
|
|
||||||
echo " Frontend: http://localhost:5173"
|
|
||||||
echo " Backend: http://localhost:${dashboard_port}"
|
|
||||||
echo ""
|
|
||||||
echo " Press Ctrl+C to stop all services."
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Cleanup on exit
|
|
||||||
cleanup() {
|
|
||||||
echo ""
|
|
||||||
echo " Stopping services..."
|
|
||||||
kill $frontend_pid 2>/dev/null
|
|
||||||
kill $backend_pid 2>/dev/null
|
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
|
|
||||||
echo " All services stopped."
|
|
||||||
echo ""
|
|
||||||
}
|
|
||||||
trap cleanup EXIT INT TERM
|
|
||||||
|
|
||||||
# Wait for any process to exit
|
|
||||||
wait $ssh_tunnel_pid $backend_pid $frontend_pid 2>/dev/null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Main Loop ───────────────────────────────────────────────────────────
|
# ── Main Loop ───────────────────────────────────────────────────────────
|
||||||
@@ -880,15 +1044,20 @@ show_banner
|
|||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
show_menu
|
show_menu
|
||||||
read -rp " Enter your choice: " choice
|
read -rp " Enter your choice: " choice || { echo ""; echo " Goodbye!"; echo ""; exit 0; }
|
||||||
|
|
||||||
case "$choice" in
|
case "$choice" in
|
||||||
1) start_dashboard ;;
|
1) start_dashboard ;;
|
||||||
2) run_setup ;;
|
2) run_setup ;;
|
||||||
3) run_diagnostics ;;
|
3) run_diagnostics ;;
|
||||||
7) start_new_dashboard ;;
|
4) start_dashboard_debug ;;
|
||||||
|
5) reset_to_factory ;;
|
||||||
|
6) repair_game_database ;;
|
||||||
|
7) cleanup_old_dashboard_schema ;;
|
||||||
|
8) rotate_ssh_key ;;
|
||||||
|
9) trust_server_cert ;;
|
||||||
[Qq]) echo ""; echo " Goodbye!"; echo ""; exit 0 ;;
|
[Qq]) echo ""; echo " Goodbye!"; echo ""; exit 0 ;;
|
||||||
*) echo ""; echo " Invalid choice. Please enter 1, 2, 3, 7, or Q."; echo "" ;;
|
*) echo ""; echo " Invalid choice. Please enter 1-9 or Q."; echo "" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
|
|||||||
@@ -116,7 +116,10 @@
|
|||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
||||||
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
const socket = io();
|
// Polling only: the server runs in threading mode, which has no true
|
||||||
|
// websocket support. Letting the client attempt a websocket upgrade only
|
||||||
|
// produces "Cannot obtain socket from WSGI environment" tracebacks.
|
||||||
|
const socket = io({ transports: ['polling'] });
|
||||||
|
|
||||||
let termVM = null;
|
let termVM = null;
|
||||||
let termPod = null;
|
let termPod = null;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ class FakeSSH:
|
|||||||
self.rc = rc
|
self.rc = rc
|
||||||
self.commands = []
|
self.commands = []
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
self.commands.append(command)
|
self.commands.append(command)
|
||||||
return self.out, '', self.rc
|
return self.out, '', self.rc
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Tests for the cheroot server builder + handshake-noise filter."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.utils.http_server import build_server, cheroot_error_filter
|
||||||
|
|
||||||
|
|
||||||
|
class TestHandshakeFilter:
|
||||||
|
def test_handshake_drops_go_to_debug_only(self, caplog):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def orig(msg='', level=20, traceback=False):
|
||||||
|
calls.append((msg, level))
|
||||||
|
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.utils.http_server'):
|
||||||
|
cheroot_error_filter(orig, 'Client (\'1.2.3.4\', 123) lost - peer '
|
||||||
|
'dropped the TLS connection suddenly, during '
|
||||||
|
'handshake: (8, \'[SSL: SSLV3_ALERT_CERTIFICATE_UNKNOWN] \')')
|
||||||
|
assert calls == []
|
||||||
|
assert any('handshake dropped' in r.message for r in caplog.records)
|
||||||
|
assert all(r.levelno == logging.DEBUG for r in caplog.records)
|
||||||
|
|
||||||
|
def test_real_errors_pass_through(self):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def orig(msg='', level=20, traceback=False):
|
||||||
|
calls.append((msg, level, traceback))
|
||||||
|
|
||||||
|
cheroot_error_filter(orig, 'socket.error 104', level=30, traceback=True)
|
||||||
|
assert calls == [('socket.error 104', 30, True)]
|
||||||
|
|
||||||
|
|
||||||
|
def _self_signed_pair(tmp_path):
|
||||||
|
import datetime
|
||||||
|
from cryptography import x509
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||||
|
from cryptography.x509.oid import NameOID
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'localhost')])
|
||||||
|
now = datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||||
|
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now).not_valid_after(now + datetime.timedelta(days=1))
|
||||||
|
.sign(key, hashes.SHA256()))
|
||||||
|
cert_path = tmp_path / 'c.pem'
|
||||||
|
key_path = tmp_path / 'k.pem'
|
||||||
|
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||||
|
key_path.write_bytes(key.private_bytes(
|
||||||
|
serialization.Encoding.PEM,
|
||||||
|
serialization.PrivateFormat.TraditionalOpenSSL,
|
||||||
|
serialization.NoEncryption()))
|
||||||
|
return str(cert_path), str(key_path)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBuildServer:
|
||||||
|
def test_timeouts_and_queues(self):
|
||||||
|
server = build_server('127.0.0.1', 0, None)
|
||||||
|
try:
|
||||||
|
assert server.numthreads == 16
|
||||||
|
assert server.timeout == 60
|
||||||
|
assert server.request_queue_size == 128
|
||||||
|
finally:
|
||||||
|
server.stop()
|
||||||
|
|
||||||
|
def test_tls_adapter(self, tmp_path):
|
||||||
|
cert, key = _self_signed_pair(tmp_path)
|
||||||
|
server = build_server('127.0.0.1', 0, None, cert, key)
|
||||||
|
try:
|
||||||
|
assert server.ssl_adapter is not None
|
||||||
|
finally:
|
||||||
|
server.stop()
|
||||||
@@ -16,7 +16,7 @@ class FakeSSH:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.commands = []
|
self.commands = []
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
self.commands.append(command)
|
self.commands.append(command)
|
||||||
return ('ok', '', 0)
|
return ('ok', '', 0)
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,47 @@
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.routes.api import fb_within_roots
|
from app.routes.api import fb_resolve_canonical, fb_within_roots
|
||||||
from app.services.backup import is_valid_backup_name
|
from app.services.backup import is_valid_backup_name
|
||||||
|
|
||||||
|
|
||||||
|
class TestCanonicalResolution:
|
||||||
|
def test_gnu_realpath_m(self):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def run(cmd, timeout):
|
||||||
|
calls.append(cmd)
|
||||||
|
return '/srv/sub/../file.txt\n', '', 0
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/file.txt', '/srv/file.txt', run) == \
|
||||||
|
'/srv/sub/../file.txt'
|
||||||
|
assert calls[0].startswith('realpath -m -- ')
|
||||||
|
|
||||||
|
def test_busybox_falls_back_to_plain_realpath(self):
|
||||||
|
def run(cmd, timeout):
|
||||||
|
if cmd.startswith('realpath -m -- '):
|
||||||
|
return '', 'realpath: -m: No such file or directory', 1
|
||||||
|
assert cmd.startswith('realpath -- ')
|
||||||
|
return '/srv/file.txt\n', '', 0
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/file.txt', '/srv/file.txt', run) == \
|
||||||
|
'/srv/file.txt'
|
||||||
|
|
||||||
|
def test_missing_binary_falls_back_to_lexical(self):
|
||||||
|
def run(cmd, timeout):
|
||||||
|
return '', 'realpath: command not found', 127
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/a/../b', '/srv/b', run) == '/srv/b'
|
||||||
|
|
||||||
|
def test_missing_file_without_m_support(self):
|
||||||
|
# New file on BusyBox: plain realpath fails too, lexical wins.
|
||||||
|
def run(cmd, timeout):
|
||||||
|
return '', 'No such file or directory', 1
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/new.txt', '/srv/new.txt', run) == \
|
||||||
|
'/srv/new.txt'
|
||||||
|
|
||||||
|
|
||||||
class TestFileBrowserJail:
|
class TestFileBrowserJail:
|
||||||
ROOTS = ['/srv', '/home/dune/.dune']
|
ROOTS = ['/srv', '/home/dune/.dune']
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Tests for SSHService.run(quiet=...) - log level only, same results."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.services.ssh import SSHService
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeChannel:
|
||||||
|
def __init__(self, rc):
|
||||||
|
self._rc = rc
|
||||||
|
|
||||||
|
def settimeout(self, timeout):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def recv_exit_status(self):
|
||||||
|
return self._rc
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeStream:
|
||||||
|
def __init__(self, data, rc):
|
||||||
|
self._data = data
|
||||||
|
self.channel = _FakeChannel(rc)
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return self._data
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self, out=b'', err=b'Error from server (NotFound)', rc=1):
|
||||||
|
self._out = _FakeStream(out, rc)
|
||||||
|
self._err = _FakeStream(err, rc)
|
||||||
|
|
||||||
|
def get_transport(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def exec_command(self, command, timeout=None):
|
||||||
|
return None, self._out, self._err
|
||||||
|
|
||||||
|
|
||||||
|
def _service_with_fake_client():
|
||||||
|
svc = SSHService.__new__(SSHService)
|
||||||
|
import threading
|
||||||
|
svc.host = 'h'
|
||||||
|
svc.user = 'u'
|
||||||
|
svc.ssh_key = None
|
||||||
|
svc._client = _FakeClient()
|
||||||
|
svc._lock = threading.Lock()
|
||||||
|
# Bypass reconnect logic: _get_client returns the fake directly when
|
||||||
|
# its transport check is skipped. Patch at instance level.
|
||||||
|
svc._get_client = lambda: svc._client
|
||||||
|
return svc
|
||||||
|
|
||||||
|
|
||||||
|
class TestQuietFlag:
|
||||||
|
def test_results_identical_quiet_or_not(self, caplog):
|
||||||
|
svc = _service_with_fake_client()
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
out1, err1, rc1 = svc.run('kubectl get x', quiet=False)
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
out2, err2, rc2 = svc.run('kubectl get x', quiet=True)
|
||||||
|
assert (out1, err1, rc1) == (out2, err2, rc2) == ('', 'Error from server (NotFound)', 1)
|
||||||
|
|
||||||
|
def test_loud_logs_warning_quiet_logs_debug(self, caplog):
|
||||||
|
svc = _service_with_fake_client()
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
caplog.clear()
|
||||||
|
svc.run('kubectl get x', quiet=False)
|
||||||
|
loud_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
caplog.clear()
|
||||||
|
svc.run('kubectl get x', quiet=True)
|
||||||
|
quiet_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||||
|
assert logging.WARNING in loud_levels
|
||||||
|
assert logging.WARNING not in quiet_levels
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Tests for the self-watchdog liveness probe."""
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
|
||||||
|
from app.utils.watchdog import probe
|
||||||
|
|
||||||
|
|
||||||
|
class _Handler(BaseHTTPRequestHandler):
|
||||||
|
def do_GET(self):
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(b'ok')
|
||||||
|
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _serve_on_free_port():
|
||||||
|
server = HTTPServer(('127.0.0.1', 0), _Handler)
|
||||||
|
port = server.server_address[1]
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
return server, port
|
||||||
|
|
||||||
|
|
||||||
|
class TestProbe:
|
||||||
|
def test_healthy_server_answers(self):
|
||||||
|
server, port = _serve_on_free_port()
|
||||||
|
try:
|
||||||
|
assert probe('127.0.0.1', port, use_ssl=False) is True
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
|
||||||
|
def test_dead_port_fails(self):
|
||||||
|
# Port 1 is never listening.
|
||||||
|
assert probe('127.0.0.1', 1, use_ssl=False, timeout=2) is False
|
||||||
|
|
||||||
|
def test_ssl_mismatch_fails_plain(self):
|
||||||
|
server, port = _serve_on_free_port()
|
||||||
|
try:
|
||||||
|
# Plain HTTP server probed as HTTPS must fail, not hang.
|
||||||
|
assert probe('127.0.0.1', port, use_ssl=True, timeout=5) is False
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
Reference in new issue
Block a user