Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac67c674cc |
No files matched your search
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
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
|
||||||
@@ -24,18 +26,20 @@ 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** (jailed to allowed directories) + **in-browser shell**
|
- **SSH File Browser** + **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)
|
||||||
- **Backup & Restore** — encrypted full-server snapshots with scheduled backups and retention cleanup
|
- **Nav Layout** — switch between horizontal and vertical sidebar; persists preference; auto-enables sidebar on mobile
|
||||||
- **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
|
||||||
- **HTTPS + Remote Access** (self-signed or Let's Encrypt)
|
- **Auto‑Update** with safe file replacement
|
||||||
- **Cross-Platform Launchers** (Windows + Linux/macOS, incl. debug mode and SSH key rotation)
|
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
|
||||||
|
- **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
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -60,12 +64,36 @@ DuneDashboard/
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- `settings.yaml` is never committed
|
||||||
|
- SSH keys stored with restricted permissions
|
||||||
|
- All DB queries parameterized
|
||||||
|
- Raw SQL endpoint is **read‑only SELECT**
|
||||||
|
- All mutations audited
|
||||||
|
- CSP, HSTS, X‑Frame‑Options enforced in production
|
||||||
|
|
||||||
|
> “Raw SQL query endpoint is read‑only SELECT — INSERT/UPDATE/DELETE… are blocked.”
|
||||||
|
> Because letting users run `DROP TABLE` from a web UI is how horror stories begin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 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
|
||||||
|
- **nightly** — latest features
|
||||||
|
- **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)**
|
||||||
|
|||||||
@@ -51,8 +51,6 @@ DEFAULTS = {
|
|||||||
},
|
},
|
||||||
'filebrowser': {
|
'filebrowser': {
|
||||||
'port': 18888,
|
'port': 18888,
|
||||||
# Empty = built-in defaults (/srv, /home/dune/.dune).
|
|
||||||
'allowed_roots': [],
|
|
||||||
},
|
},
|
||||||
'firewall': {
|
'firewall': {
|
||||||
'block_filebrowser': True,
|
'block_filebrowser': True,
|
||||||
|
|||||||
+3
-41
@@ -27,8 +27,6 @@ from app.services.updater import UpdateService
|
|||||||
from app.services.director import DirectorService
|
from app.services.director import DirectorService
|
||||||
from app.services.rmq import RmqService
|
from app.services.rmq import RmqService
|
||||||
from app.services.backup import BackupService
|
from app.services.backup import BackupService
|
||||||
from app.services.lifecycle import LifecycleService
|
|
||||||
from app.services.scheduled_broadcast import ScheduledBroadcastService
|
|
||||||
from app.utils.cache import MultiCache
|
from app.utils.cache import MultiCache
|
||||||
from app.routes.main import register_routes
|
from app.routes.main import register_routes
|
||||||
from app.routes.api import register_api_routes
|
from app.routes.api import register_api_routes
|
||||||
@@ -174,12 +172,9 @@ 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:
|
||||||
# Quiet console in normal mode: routine requests (including
|
# Only log API requests to avoid noise
|
||||||
# scanner 404s) are not logged. Turn on debug logging
|
if request.path.startswith('/api') or request.path.startswith('/server'):
|
||||||
# (launcher option 4) to see every request. Server errors
|
logging.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
||||||
# 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"
|
||||||
@@ -282,12 +277,6 @@ def create_app(settings_path=None):
|
|||||||
backup_svc = BackupService(ssh_service, k8s_service, rmq_svc, settings)
|
backup_svc = BackupService(ssh_service, k8s_service, rmq_svc, settings)
|
||||||
logging.debug("BackupService initialized")
|
logging.debug("BackupService initialized")
|
||||||
|
|
||||||
lifecycle_svc = LifecycleService(ssh_service, admin_svc, settings)
|
|
||||||
logging.debug("LifecycleService initialized")
|
|
||||||
|
|
||||||
sched_broadcast_svc = ScheduledBroadcastService(admin_svc)
|
|
||||||
logging.debug("ScheduledBroadcastService initialized")
|
|
||||||
|
|
||||||
services = {
|
services = {
|
||||||
'db': db_service,
|
'db': db_service,
|
||||||
'dash_db': dash_db_service,
|
'dash_db': dash_db_service,
|
||||||
@@ -302,8 +291,6 @@ def create_app(settings_path=None):
|
|||||||
'director': director_svc,
|
'director': director_svc,
|
||||||
'rmq': rmq_svc,
|
'rmq': rmq_svc,
|
||||||
'backup': backup_svc,
|
'backup': backup_svc,
|
||||||
'lifecycle': lifecycle_svc,
|
|
||||||
'broadcasts': sched_broadcast_svc,
|
|
||||||
}
|
}
|
||||||
logging.debug(f"All services registered: {list(services.keys())}")
|
logging.debug(f"All services registered: {list(services.keys())}")
|
||||||
|
|
||||||
@@ -551,31 +538,6 @@ def create_app(settings_path=None):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.debug(f'Could not start backup scheduler: {e}')
|
logging.debug(f'Could not start backup scheduler: {e}')
|
||||||
|
|
||||||
# ── Lifecycle Scheduler (scheduled restarts + notifications) ────────
|
|
||||||
try:
|
|
||||||
lifecycle_svc = services.get('lifecycle')
|
|
||||||
broadcasts_svc = services.get('broadcasts')
|
|
||||||
if lifecycle_svc or broadcasts_svc:
|
|
||||||
def _lifecycle_scheduler():
|
|
||||||
while True:
|
|
||||||
time.sleep(30)
|
|
||||||
try:
|
|
||||||
if lifecycle_svc:
|
|
||||||
lifecycle_svc.check_and_fire()
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(f'Lifecycle scheduler: {e}')
|
|
||||||
try:
|
|
||||||
if broadcasts_svc:
|
|
||||||
broadcasts_svc.check_and_fire()
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(f'Broadcast scheduler: {e}')
|
|
||||||
|
|
||||||
lifecycle_thread = threading.Thread(target=_lifecycle_scheduler, daemon=True)
|
|
||||||
lifecycle_thread.start()
|
|
||||||
logging.info('Lifecycle scheduler: Background thread started')
|
|
||||||
except Exception as e:
|
|
||||||
logging.debug(f'Could not start lifecycle scheduler: {e}')
|
|
||||||
|
|
||||||
app.dune_settings = settings
|
app.dune_settings = settings
|
||||||
app.dune_services = services
|
app.dune_services = services
|
||||||
|
|
||||||
|
|||||||
+687
-534
File diff suppressed because it is too large.
Load diff
@@ -530,6 +530,12 @@ def register_routes(app, services, settings):
|
|||||||
logger.exception("Error in server_status route")
|
logger.exception("Error in server_status route")
|
||||||
return render_template('server.html', db_error=f"{type(e).__name__}: {e}")
|
return render_template('server.html', db_error=f"{type(e).__name__}: {e}")
|
||||||
|
|
||||||
|
# Admin Experimental
|
||||||
|
@app.route('/admin-experimental')
|
||||||
|
@login_required
|
||||||
|
def admin_experimental():
|
||||||
|
return render_template('admin_experimental.html')
|
||||||
|
|
||||||
# Backup / Restore
|
# Backup / Restore
|
||||||
@app.route('/backup')
|
@app.route('/backup')
|
||||||
@login_required
|
@login_required
|
||||||
|
|||||||
@@ -802,13 +802,6 @@ class AdminService:
|
|||||||
|
|
||||||
token = os.environ.get('DUNE_BROADCAST_TOKEN',
|
token = os.environ.get('DUNE_BROADCAST_TOKEN',
|
||||||
getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr')
|
getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr')
|
||||||
# Duration is interpolated into Erlang code: force an int in range.
|
|
||||||
try:
|
|
||||||
duration = max(5, min(300, int(duration)))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
duration = 30
|
|
||||||
# Escape the token for the Erlang double-quoted binary literal.
|
|
||||||
token_esc = str(token).replace('\\', '\\\\').replace('"', '\\"')
|
|
||||||
title_b64 = base64.b64encode(title.encode('utf-8')).decode()
|
title_b64 = base64.b64encode(title.encode('utf-8')).decode()
|
||||||
message_b64 = base64.b64encode(message.encode('utf-8')).decode()
|
message_b64 = base64.b64encode(message.encode('utf-8')).decode()
|
||||||
|
|
||||||
@@ -816,7 +809,7 @@ class AdminService:
|
|||||||
f'Title = base64:decode(<<"{title_b64}">>), '
|
f'Title = base64:decode(<<"{title_b64}">>), '
|
||||||
f'Body = base64:decode(<<"{message_b64}">>), '
|
f'Body = base64:decode(<<"{message_b64}">>), '
|
||||||
f'Duration = {duration}, '
|
f'Duration = {duration}, '
|
||||||
f'Token = <<"{token_esc}">>, '
|
f'Token = <<"{token}">>, '
|
||||||
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
||||||
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
||||||
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
|
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
|
||||||
|
|||||||
+24
-60
@@ -1,11 +1,9 @@
|
|||||||
"""Backup service - backup creation, restore orchestration, backup management"""
|
"""Backup service - backup creation, restore orchestration, backup management"""
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
import ipaddress
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
import shlex
|
import shlex
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -26,16 +24,6 @@ class BackupError(Exception):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
# Backup names are always created as backup-DD-MM-YYYY_HHMMSS. Anything else
|
|
||||||
# (e.g. '../../...') is rejected so names can never escape the backup dir
|
|
||||||
# or break out of remote shell commands.
|
|
||||||
BACKUP_NAME_RE = re.compile(r"^backup-\d{2}-\d{2}-\d{4}_\d{6}$")
|
|
||||||
|
|
||||||
|
|
||||||
def is_valid_backup_name(name):
|
|
||||||
return bool(name and BACKUP_NAME_RE.fullmatch(str(name)))
|
|
||||||
|
|
||||||
|
|
||||||
class BackupService:
|
class BackupService:
|
||||||
BACKUP_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
|
BACKUP_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
|
||||||
|
|
||||||
@@ -388,7 +376,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.debug(f'Could not read sidecar meta from {meta_path}: {e}')
|
logger.warning(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,15 +384,10 @@ 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:
|
||||||
# Expected for encrypted archives (handled by verify with a
|
logger.warning(f'Could not read metadata from {path}: {e}')
|
||||||
# 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):
|
||||||
if not is_valid_backup_name(name):
|
|
||||||
logger.warning(f'Backup: rejected invalid backup name: {name!r}')
|
|
||||||
return False
|
|
||||||
path = self._backup_path(f'{name}.tar.gz')
|
path = self._backup_path(f'{name}.tar.gz')
|
||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
@@ -414,8 +397,6 @@ class BackupService:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def verify_backup(self, name, password=''):
|
def verify_backup(self, name, password=''):
|
||||||
if not is_valid_backup_name(name):
|
|
||||||
return {'success': False, 'error': 'Invalid backup name'}
|
|
||||||
path = self._backup_path(f'{name}.tar.gz')
|
path = self._backup_path(f'{name}.tar.gz')
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
return {'success': False, 'error': 'Backup not found'}
|
return {'success': False, 'error': 'Backup not found'}
|
||||||
@@ -463,8 +444,6 @@ class BackupService:
|
|||||||
# ── Restore Orchestration ─────────────────────────────────────────
|
# ── Restore Orchestration ─────────────────────────────────────────
|
||||||
|
|
||||||
def restore_preview(self, name):
|
def restore_preview(self, name):
|
||||||
if not is_valid_backup_name(name):
|
|
||||||
return {'success': False, 'error': 'Invalid backup name'}
|
|
||||||
path = self._backup_path(f'{name}.tar.gz')
|
path = self._backup_path(f'{name}.tar.gz')
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
return {'success': False, 'error': 'Backup not found'}
|
return {'success': False, 'error': 'Backup not found'}
|
||||||
@@ -514,8 +493,6 @@ class BackupService:
|
|||||||
return {'success': False, 'error': str(e)}
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
def start_restore(self, backup_name, options):
|
def start_restore(self, backup_name, options):
|
||||||
if not is_valid_backup_name(backup_name):
|
|
||||||
return {'success': False, 'error': 'Invalid backup name'}
|
|
||||||
ssh_user = self.settings.get('server', {}).get('user', 'dune')
|
ssh_user = self.settings.get('server', {}).get('user', 'dune')
|
||||||
ssh_key = self.settings.get('server', {}).get('ssh_key', '')
|
ssh_key = self.settings.get('server', {}).get('ssh_key', '')
|
||||||
vm_ip = self.settings.get('server', {}).get('host', '')
|
vm_ip = self.settings.get('server', {}).get('host', '')
|
||||||
@@ -612,8 +589,7 @@ class BackupService:
|
|||||||
try:
|
try:
|
||||||
with open(upload_path, 'rb') as f:
|
with open(upload_path, 'rb') as f:
|
||||||
b64_data = base64.b64encode(f.read()).decode()
|
b64_data = base64.b64encode(f.read()).decode()
|
||||||
remote_archive = f'/tmp/restore-{backup_name}.tar.gz'
|
r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > /tmp/restore-{backup_name}.tar.gz', timeout=300)
|
||||||
r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > {shlex.quote(remote_archive)}', timeout=300)
|
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
raise BackupError(f'Upload failed: {r.stderr}')
|
raise BackupError(f'Upload failed: {r.stderr}')
|
||||||
complete_step('Uploading backup archive to new VM', True)
|
complete_step('Uploading backup archive to new VM', True)
|
||||||
@@ -631,11 +607,10 @@ class BackupService:
|
|||||||
# Step 2: Extract archive on VM
|
# Step 2: Extract archive on VM
|
||||||
add_step('Extracting backup archive on VM')
|
add_step('Extracting backup archive on VM')
|
||||||
try:
|
try:
|
||||||
restore_dir = f'/tmp/restore-{backup_name}'
|
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'mkdir -p {shlex.quote(restore_dir)} && '
|
f'mkdir -p /tmp/restore-{backup_name} && '
|
||||||
f'cd {shlex.quote(restore_dir)} && '
|
f'cd /tmp/restore-{backup_name} && '
|
||||||
f'tar xzf {shlex.quote(remote_archive)} --strip-components=1',
|
f'tar xzf /tmp/restore-{backup_name}.tar.gz --strip-components=1',
|
||||||
timeout=60)
|
timeout=60)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
raise BackupError(f'Extract failed: {r.stderr}')
|
raise BackupError(f'Extract failed: {r.stderr}')
|
||||||
@@ -649,9 +624,8 @@ class BackupService:
|
|||||||
try:
|
try:
|
||||||
d = f'/tmp/restore-{backup_name}'
|
d = f'/tmp/restore-{backup_name}'
|
||||||
for fname in ['secrets.yaml', 'configmaps.yaml']:
|
for fname in ['secrets.yaml', 'configmaps.yaml']:
|
||||||
manifest = f'{d}/k8s-manifests/{fname}'
|
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'sudo kubectl apply -n {shlex.quote(str(ns))} -f {shlex.quote(manifest)} 2>/dev/null || true',
|
f'sudo kubectl apply -n {ns} -f {d}/k8s-manifests/{fname} 2>/dev/null || true',
|
||||||
timeout=30)
|
timeout=30)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
logger.warning(f'Could not apply {fname}: {r.stderr}')
|
logger.warning(f'Could not apply {fname}: {r.stderr}')
|
||||||
@@ -664,9 +638,8 @@ class BackupService:
|
|||||||
add_step('Applying battlegroup CRD')
|
add_step('Applying battlegroup CRD')
|
||||||
try:
|
try:
|
||||||
d = f'/tmp/restore-{backup_name}'
|
d = f'/tmp/restore-{backup_name}'
|
||||||
crd = f'{d}/k8s-manifests/battlegroup-crd.yaml'
|
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'sudo kubectl apply -f {shlex.quote(crd)}', timeout=60)
|
f'sudo kubectl apply -f {d}/k8s-manifests/battlegroup-crd.yaml', timeout=60)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
raise BackupError(r.stderr)
|
raise BackupError(r.stderr)
|
||||||
complete_step('Applying battlegroup CRD', True)
|
complete_step('Applying battlegroup CRD', True)
|
||||||
@@ -677,7 +650,7 @@ class BackupService:
|
|||||||
try:
|
try:
|
||||||
for i in range(30):
|
for i in range(30):
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'sudo kubectl get pods -n {shlex.quote(str(ns))} --no-headers 2>/dev/null | '
|
f'sudo kubectl get pods -n {ns} --no-headers 2>/dev/null | '
|
||||||
f'grep -c -E "(dbdepl|mq-.*-sts)" || true', timeout=15)
|
f'grep -c -E "(dbdepl|mq-.*-sts)" || true', timeout=15)
|
||||||
if r.returncode == 0 and r.stdout.strip():
|
if r.returncode == 0 and r.stdout.strip():
|
||||||
count = int(r.stdout.strip())
|
count = int(r.stdout.strip())
|
||||||
@@ -694,7 +667,7 @@ class BackupService:
|
|||||||
try:
|
try:
|
||||||
for i in range(30):
|
for i in range(30):
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db --no-headers '
|
f'sudo kubectl get pods -n {ns} -l role=db --no-headers '
|
||||||
f'-o custom-columns=STATUS:.status.phase 2>/dev/null | head -1',
|
f'-o custom-columns=STATUS:.status.phase 2>/dev/null | head -1',
|
||||||
timeout=15)
|
timeout=15)
|
||||||
if 'Running' in r.stdout:
|
if 'Running' in r.stdout:
|
||||||
@@ -711,7 +684,7 @@ class BackupService:
|
|||||||
add_step('Importing game database')
|
add_step('Importing game database')
|
||||||
try:
|
try:
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'cd {shlex.quote(restore_dir)} && '
|
f'cd /tmp/restore-{backup_name} && '
|
||||||
f'/home/dune/.dune/bin/battlegroup import',
|
f'/home/dune/.dune/bin/battlegroup import',
|
||||||
timeout=600)
|
timeout=600)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
@@ -735,9 +708,9 @@ class BackupService:
|
|||||||
if dash_sql_content:
|
if dash_sql_content:
|
||||||
b64_sql = base64.b64encode(dash_sql_content).decode()
|
b64_sql = base64.b64encode(dash_sql_content).decode()
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && '
|
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
|
||||||
f'echo {shlex.quote(b64_sql)} | base64 -d | '
|
f'echo {shlex.quote(b64_sql)} | base64 -d | '
|
||||||
f'sudo kubectl exec -n {shlex.quote(str(ns))} -i $dbpod -- psql -U postgres -d dune',
|
f'sudo kubectl exec -n {ns} -i $dbpod -- psql -U postgres -d dune',
|
||||||
timeout=120)
|
timeout=120)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
logger.warning(f'Dashboard DB restore warning: {r.stderr}')
|
logger.warning(f'Dashboard DB restore warning: {r.stderr}')
|
||||||
@@ -755,8 +728,8 @@ class BackupService:
|
|||||||
"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA dashboard TO dune;"
|
"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA dashboard TO dune;"
|
||||||
"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA dashboard TO dune;")
|
"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA dashboard TO dune;")
|
||||||
r = ssh_cmd(
|
r = ssh_cmd(
|
||||||
f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && '
|
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
|
||||||
f'sudo kubectl exec -n {shlex.quote(str(ns))} $dbpod -- psql -U postgres -d dune '
|
f'sudo kubectl exec -n {ns} $dbpod -- psql -U postgres -d dune '
|
||||||
f'-c {shlex.quote(sql)}', timeout=30)
|
f'-c {shlex.quote(sql)}', timeout=30)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
logger.warning(f'Dashboard schema ownership warning: {r.stderr}')
|
logger.warning(f'Dashboard schema ownership warning: {r.stderr}')
|
||||||
@@ -768,20 +741,15 @@ class BackupService:
|
|||||||
if opts.get('restore_ping_fix', True) and opts.get('new_ip'):
|
if opts.get('restore_ping_fix', True) and opts.get('new_ip'):
|
||||||
add_step('Applying HOST_DATACENTER ping fix')
|
add_step('Applying HOST_DATACENTER ping fix')
|
||||||
try:
|
try:
|
||||||
try:
|
|
||||||
new_ip = str(ipaddress.ip_address(str(opts['new_ip']).strip()))
|
|
||||||
except ValueError:
|
|
||||||
raise BackupError(f'Invalid IP address: {opts.get("new_ip")!r}')
|
|
||||||
r = ssh_cmd('hostname', timeout=10)
|
r = ssh_cmd('hostname', timeout=10)
|
||||||
hostname = r.stdout.strip()
|
hostname = r.stdout.strip()
|
||||||
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,253}', hostname):
|
new_ip = opts['new_ip']
|
||||||
raise BackupError(f'Unexpected hostname: {hostname!r}')
|
|
||||||
for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']:
|
for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']:
|
||||||
full_name = f'{ns}-{deploy_suffix}'
|
full_name = f'{ns}-{deploy_suffix}'
|
||||||
ssh_cmd(
|
ssh_cmd(
|
||||||
f'sudo kubectl set env deploy/{shlex.quote(full_name)} -n {shlex.quote(str(ns))} '
|
f'sudo kubectl set env deploy/{full_name} -n {ns} '
|
||||||
f'HOST_DATACENTER_ID={shlex.quote(hostname)} '
|
f'HOST_DATACENTER_ID={hostname} '
|
||||||
f'HOST_DATACENTER_IP_ADDRESS={shlex.quote(new_ip)}',
|
f'HOST_DATACENTER_IP_ADDRESS={new_ip}',
|
||||||
timeout=30)
|
timeout=30)
|
||||||
complete_step('Applying HOST_DATACENTER ping fix', True)
|
complete_step('Applying HOST_DATACENTER ping fix', True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -794,24 +762,21 @@ class BackupService:
|
|||||||
pw = self.settings.get('rabbitmq', {}).get('password', '')
|
pw = self.settings.get('rabbitmq', {}).get('password', '')
|
||||||
for side in ['admin', 'game']:
|
for side in ['admin', 'game']:
|
||||||
pod_r = ssh_cmd(
|
pod_r = ssh_cmd(
|
||||||
f'sudo kubectl get pods -n {shlex.quote(str(ns))} -o name | grep mq-{side}-sts | head -1',
|
f'sudo kubectl get pods -n {ns} -o name | grep mq-{side}-sts | head -1',
|
||||||
timeout=15)
|
timeout=15)
|
||||||
if pod_r.returncode != 0 or not pod_r.stdout.strip():
|
if pod_r.returncode != 0 or not pod_r.stdout.strip():
|
||||||
logger.warning(f'No mq-{side} pod found')
|
logger.warning(f'No mq-{side} pod found')
|
||||||
continue
|
continue
|
||||||
pod = pod_r.stdout.strip()
|
pod = pod_r.stdout.strip()
|
||||||
if not re.fullmatch(r'[a-z0-9]([-a-z0-9]*[a-z0-9])?', pod):
|
|
||||||
logger.warning(f'Skipping unexpected pod name: {pod!r}')
|
|
||||||
continue
|
|
||||||
for cmd in [
|
for cmd in [
|
||||||
f'rabbitmqctl add_user dashboard_admin {shlex.quote(str(pw))}',
|
f'rabbitmqctl add_user dashboard_admin {pw}',
|
||||||
f'rabbitmqctl set_user_tags dashboard_admin administrator',
|
f'rabbitmqctl set_user_tags dashboard_admin administrator',
|
||||||
f'rabbitmqctl set_permissions -p / dashboard_admin ".*" ".*" ".*"',
|
f'rabbitmqctl set_permissions -p / dashboard_admin ".*" ".*" ".*"',
|
||||||
f'rabbitmqctl eval '
|
f'rabbitmqctl eval '
|
||||||
f'\'application:set_env(rabbit, auth_backends, '
|
f'\'application:set_env(rabbit, auth_backends, '
|
||||||
f'[rabbit_auth_backend_cache, rabbit_auth_backend_internal]).\'',
|
f'[rabbit_auth_backend_cache, rabbit_auth_backend_internal]).\'',
|
||||||
]:
|
]:
|
||||||
ssh_cmd(f'sudo kubectl exec -n {shlex.quote(str(ns))} {shlex.quote(pod)} -- {cmd}', timeout=15)
|
ssh_cmd(f'sudo kubectl exec -n {ns} {pod} -- {cmd}', timeout=15)
|
||||||
complete_step('Re-creating RMQ dashboard_admin user on both instances', True)
|
complete_step('Re-creating RMQ dashboard_admin user on both instances', True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
complete_step('Re-creating RMQ dashboard_admin user on both instances', False, str(e))
|
complete_step('Re-creating RMQ dashboard_admin user on both instances', False, str(e))
|
||||||
@@ -821,8 +786,7 @@ class BackupService:
|
|||||||
add_step('Restoring dashboard settings.yaml locally')
|
add_step('Restoring dashboard settings.yaml locally')
|
||||||
try:
|
try:
|
||||||
d = f'/tmp/restore-{backup_name}'
|
d = f'/tmp/restore-{backup_name}'
|
||||||
settings_file = f'{d}/settings.yaml'
|
r = ssh_cmd(f'cat {d}/settings.yaml', timeout=15)
|
||||||
r = ssh_cmd(f'cat {shlex.quote(settings_file)}', timeout=15)
|
|
||||||
if r.returncode == 0 and r.stdout.strip():
|
if r.returncode == 0 and r.stdout.strip():
|
||||||
local_settings = os.path.join(
|
local_settings = os.path.join(
|
||||||
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
||||||
@@ -838,7 +802,7 @@ class BackupService:
|
|||||||
# Step 10: Cleanup
|
# Step 10: Cleanup
|
||||||
add_step('Cleaning up temporary files on VM')
|
add_step('Cleaning up temporary files on VM')
|
||||||
try:
|
try:
|
||||||
ssh_cmd(f'rm -rf {shlex.quote(restore_dir)} {shlex.quote(remote_archive)}',
|
ssh_cmd(f'rm -rf /tmp/restore-{backup_name} /tmp/restore-{backup_name}.tar.gz',
|
||||||
timeout=15)
|
timeout=15)
|
||||||
complete_step('Cleaning up temporary files on VM', True)
|
complete_step('Cleaning up temporary files on VM', True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
"""Director service - battlegroup director API and ConfigMap management."""
|
"""Director service - battlegroup director API and ConfigMap management."""
|
||||||
|
|
||||||
import ipaddress
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import shlex
|
|
||||||
import time
|
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import configparser
|
import configparser
|
||||||
import io
|
import io
|
||||||
import base64
|
import base64
|
||||||
import re
|
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -52,19 +48,11 @@ class DirectorService:
|
|||||||
for line in (out or '').split('\n'):
|
for line in (out or '').split('\n'):
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if 'bgd-svc' in line:
|
if 'bgd-svc' in line:
|
||||||
svc_name = line.split('/')[-1].strip()
|
svc_name = line.split('/')[-1]
|
||||||
if not re.fullmatch(r'[a-z0-9]([-a-z0-9]*[a-z0-9])?', svc_name or ''):
|
|
||||||
logger.warning("Director: unexpected svc name %r", svc_name)
|
|
||||||
continue
|
|
||||||
ip_out, ip_err, ip_rc = self.k8s.run(
|
ip_out, ip_err, ip_rc = self.k8s.run(
|
||||||
f'get svc {shlex.quote(svc_name)} -o jsonpath={{.spec.clusterIP}}', timeout=10)
|
f'get svc {svc_name} -o jsonpath={{.spec.clusterIP}}', timeout=10)
|
||||||
if ip_rc == 0 and ip_out:
|
if ip_rc == 0 and ip_out:
|
||||||
ip = ip_out.strip()
|
ip = ip_out.strip()
|
||||||
try:
|
|
||||||
ipaddress.ip_address(ip)
|
|
||||||
except ValueError:
|
|
||||||
logger.warning("Director: unexpected cluster IP %r", ip)
|
|
||||||
continue
|
|
||||||
logger.info("Director: resolved BGD svc cluster IP %s", ip)
|
logger.info("Director: resolved BGD svc cluster IP %s", ip)
|
||||||
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
|
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
|
||||||
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
|
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
|
||||||
@@ -120,7 +108,7 @@ class DirectorService:
|
|||||||
svc_url = f"{self._bgd_svc_url}{path}"
|
svc_url = f"{self._bgd_svc_url}{path}"
|
||||||
logger.debug("Director SSH fallback: %s %s", method, svc_url)
|
logger.debug("Director SSH fallback: %s %s", method, svc_url)
|
||||||
if method == 'GET':
|
if method == 'GET':
|
||||||
out, err, rc = self.ssh.run(f'wget -qO- {shlex.quote(svc_url)}', timeout=timeout)
|
out, err, rc = self.ssh.run(f'wget -qO- {svc_url}', timeout=timeout)
|
||||||
else:
|
else:
|
||||||
body_bytes = None
|
body_bytes = None
|
||||||
if raw_data and isinstance(data, str):
|
if raw_data and isinstance(data, str):
|
||||||
@@ -129,14 +117,14 @@ class DirectorService:
|
|||||||
body_bytes = json.dumps(data).encode()
|
body_bytes = json.dumps(data).encode()
|
||||||
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
|
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
|
||||||
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
|
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
|
||||||
self.ssh.run(f'echo {shlex.quote(body_b64)} | base64 -d > {shlex.quote(tmp)}', timeout=5)
|
self.ssh.run(f'echo {body_b64} | base64 -d > {tmp}', timeout=5)
|
||||||
try:
|
try:
|
||||||
out, err, rc = self.ssh.run(
|
out, err, rc = self.ssh.run(
|
||||||
f'wget -qO- --post-file={shlex.quote(tmp)} '
|
f'wget -qO- --post-file={tmp} '
|
||||||
f'--header="Content-Type: application/json" {shlex.quote(svc_url)}',
|
f'--header="Content-Type: application/json" {svc_url}',
|
||||||
timeout=timeout)
|
timeout=timeout)
|
||||||
finally:
|
finally:
|
||||||
self.ssh.run(f'rm -f {shlex.quote(tmp)}', timeout=5)
|
self.ssh.run(f'rm -f {tmp}', timeout=5)
|
||||||
if rc == 0 and out:
|
if rc == 0 and out:
|
||||||
return out
|
return out
|
||||||
logger.warning("Director SSH fallback failed (rc=%d): %s",
|
logger.warning("Director SSH fallback failed (rc=%d): %s",
|
||||||
@@ -256,15 +244,8 @@ 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', quiet=True)
|
f'get serversetscale {name} -o json')
|
||||||
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)
|
||||||
|
|
||||||
|
|||||||
+3
-30
@@ -1,7 +1,6 @@
|
|||||||
"""Kubernetes service - kubectl operations via SSH"""
|
"""Kubernetes service - kubectl operations via SSH"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import shlex
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -11,10 +10,10 @@ class K8sService:
|
|||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
|
||||||
def run(self, kubectl_command, timeout=30, quiet=False):
|
def run(self, kubectl_command, timeout=30):
|
||||||
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
|
full_cmd = f'sudo kubectl {kubectl_command} -n {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, quiet=quiet)
|
result = self.ssh.run(full_cmd, timeout=timeout)
|
||||||
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'}")
|
||||||
@@ -31,32 +30,6 @@ class K8sService:
|
|||||||
logger.debug(f"Found {len(pods)} pods in namespace {self.namespace}")
|
logger.debug(f"Found {len(pods)} pods in namespace {self.namespace}")
|
||||||
return pods
|
return pods
|
||||||
|
|
||||||
def get_running_game_pods(self):
|
|
||||||
"""List game server pods (sg-*-pod-*) currently in Running phase.
|
|
||||||
|
|
||||||
Used as the "server is online" signal, e.g. to block battlegroup
|
|
||||||
updates while players could be connected.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of running game pod names, [] when none running,
|
|
||||||
or None when pod status could not be determined.
|
|
||||||
"""
|
|
||||||
out, err, rc = self.run(
|
|
||||||
'get pods --no-headers -o custom-columns=NAME:.metadata.name,STATUS:.status.phase')
|
|
||||||
if rc != 0:
|
|
||||||
logger.warning(f"Could not get pod statuses: {err[:100] if err else 'no error'}")
|
|
||||||
return None
|
|
||||||
running = []
|
|
||||||
for line in (out or '').strip().split('\n'):
|
|
||||||
parts = line.strip().split()
|
|
||||||
if len(parts) < 2:
|
|
||||||
continue
|
|
||||||
name, phase = parts[0], parts[1]
|
|
||||||
if phase == 'Running' and '-sg-' in name and '-pod-' in name:
|
|
||||||
running.append(name)
|
|
||||||
logger.debug(f"Found {len(running)} running game pods in namespace {self.namespace}")
|
|
||||||
return running
|
|
||||||
|
|
||||||
def find_pod_by_pattern(self, pattern):
|
def find_pod_by_pattern(self, pattern):
|
||||||
pods = self.get_pods()
|
pods = self.get_pods()
|
||||||
for pod in pods:
|
for pod in pods:
|
||||||
|
|||||||
@@ -1,497 +0,0 @@
|
|||||||
"""Lifecycle service - graceful shutdown/start/restart with in-game countdown.
|
|
||||||
|
|
||||||
Notification path reuses the Experimental In-Game Broadcast
|
|
||||||
(AdminService.send_global_broadcast) - no duplicate RMQ code.
|
|
||||||
|
|
||||||
Countdown (seconds before action -> spoken label -> broadcast duration):
|
|
||||||
15m, 10m, 5m, 3m, 2m, 1m, 30s -> duration 10
|
|
||||||
10s -> duration 5 (so it does not overlap the final 1s notice)
|
|
||||||
1s -> final "now" notice, duration 10
|
|
||||||
|
|
||||||
Scheduled restarts use the same marks but say "Scheduled restart in X ...".
|
|
||||||
"""
|
|
||||||
|
|
||||||
import copy
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
from app.services.schedule_util import (
|
|
||||||
SCHEDULE_MODES,
|
|
||||||
clean_days,
|
|
||||||
clean_times,
|
|
||||||
compute_next_run as util_compute_next_run,
|
|
||||||
parse_hhmm,
|
|
||||||
parse_when,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# (seconds_before_action, spoken label, broadcast duration seconds)
|
|
||||||
COUNTDOWN_MARKS = [
|
|
||||||
(900, '15 minutes', 10),
|
|
||||||
(600, '10 minutes', 10),
|
|
||||||
(300, '5 minutes', 10),
|
|
||||||
(180, '3 minutes', 10),
|
|
||||||
(120, '2 minutes', 10),
|
|
||||||
(60, '1 minute', 10),
|
|
||||||
(30, '30 seconds', 10),
|
|
||||||
(10, '10 seconds', 5),
|
|
||||||
]
|
|
||||||
|
|
||||||
FINAL_MARK_SECONDS = 1
|
|
||||||
FINAL_DURATION = 10
|
|
||||||
FULL_COUNTDOWN_SECONDS = 900
|
|
||||||
# A mark that became due within the last N seconds is sent immediately
|
|
||||||
# (covers thread startup delay, e.g. the first 15-minute notice at job start).
|
|
||||||
# Marks older than this were missed while the dashboard was down: skipped.
|
|
||||||
MARK_GRACE_SECONDS = 60
|
|
||||||
|
|
||||||
|
|
||||||
def _default_state_dir():
|
|
||||||
return os.path.join(
|
|
||||||
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
|
|
||||||
|
|
||||||
|
|
||||||
def default_schedule():
|
|
||||||
return {
|
|
||||||
'enabled': False,
|
|
||||||
'mode': 'daily',
|
|
||||||
'daily_times': ['05:00'],
|
|
||||||
'weekly_days': [6],
|
|
||||||
'weekly_times': ['05:00'],
|
|
||||||
'monthly_days': [1],
|
|
||||||
'monthly_time': '05:00',
|
|
||||||
'once_at': '',
|
|
||||||
'next_run': '',
|
|
||||||
'last_started_for': '',
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class LifecycleService:
|
|
||||||
"""Owns one active countdown at a time + the restart schedule file."""
|
|
||||||
|
|
||||||
def __init__(self, ssh_service, admin_service, settings, state_dir=None):
|
|
||||||
self.ssh = ssh_service
|
|
||||||
self.admin = admin_service
|
|
||||||
self.settings = settings or {}
|
|
||||||
self.state_dir = state_dir or _default_state_dir()
|
|
||||||
os.makedirs(self.state_dir, exist_ok=True)
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self._active = None
|
|
||||||
self._cancel_event = threading.Event()
|
|
||||||
self._thread = None
|
|
||||||
|
|
||||||
# ── schedule persistence ──────────────────────────────────────────
|
|
||||||
|
|
||||||
def _schedule_path(self):
|
|
||||||
return os.path.join(self.state_dir, 'lifecycle-schedule.json')
|
|
||||||
|
|
||||||
def get_schedule(self):
|
|
||||||
cfg = default_schedule()
|
|
||||||
try:
|
|
||||||
with open(self._schedule_path()) as f:
|
|
||||||
stored = json.load(f) or {}
|
|
||||||
for key in cfg:
|
|
||||||
if key in stored:
|
|
||||||
cfg[key] = stored[key]
|
|
||||||
except FileNotFoundError:
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f'Lifecycle: could not read schedule: {e}')
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
def _save_schedule(self, cfg):
|
|
||||||
with open(self._schedule_path(), 'w') as f:
|
|
||||||
json.dump(cfg, f, indent=2)
|
|
||||||
|
|
||||||
def update_schedule(self, data):
|
|
||||||
"""Validate + store schedule, recompute next_run. Returns stored cfg."""
|
|
||||||
cfg = self.get_schedule()
|
|
||||||
data = dict(data or {})
|
|
||||||
|
|
||||||
if 'enabled' in data:
|
|
||||||
cfg['enabled'] = bool(data['enabled'])
|
|
||||||
if 'mode' in data:
|
|
||||||
mode = str(data['mode']).strip().lower()
|
|
||||||
if mode not in SCHEDULE_MODES:
|
|
||||||
raise ValueError(f'Invalid mode: {mode!r}')
|
|
||||||
cfg['mode'] = mode
|
|
||||||
if 'daily_times' in data:
|
|
||||||
cfg['daily_times'] = self._clean_times(data['daily_times'])
|
|
||||||
if 'weekly_times' in data:
|
|
||||||
cfg['weekly_times'] = self._clean_times(data['weekly_times'])
|
|
||||||
if 'weekly_days' in data:
|
|
||||||
cfg['weekly_days'] = self._clean_days(data['weekly_days'], 0, 6)
|
|
||||||
if 'monthly_days' in data:
|
|
||||||
cfg['monthly_days'] = self._clean_days(data['monthly_days'], 1, 31)
|
|
||||||
if 'monthly_time' in data:
|
|
||||||
parse_hhmm(data['monthly_time'])
|
|
||||||
cfg['monthly_time'] = str(data['monthly_time']).strip()
|
|
||||||
if 'once_at' in data:
|
|
||||||
cfg['once_at'] = str(data['once_at'] or '').strip()
|
|
||||||
if cfg['once_at']:
|
|
||||||
try:
|
|
||||||
parse_when(cfg['once_at'])
|
|
||||||
except ValueError:
|
|
||||||
raise ValueError('One-shot date/time is not valid.')
|
|
||||||
|
|
||||||
# Mode-specific sanity so a bad form cannot arm a silent never-fire job.
|
|
||||||
if cfg['mode'] == 'daily' and not cfg['daily_times']:
|
|
||||||
raise ValueError('Daily mode needs at least one time (HH:MM).')
|
|
||||||
if cfg['mode'] == 'weekly' and (not cfg['weekly_days'] or not cfg['weekly_times']):
|
|
||||||
raise ValueError('Weekly mode needs days and at least one time.')
|
|
||||||
if cfg['mode'] == 'monthly' and (not cfg['monthly_days'] or not cfg['monthly_time']):
|
|
||||||
raise ValueError('Monthly mode needs days of month and a time.')
|
|
||||||
if cfg['mode'] == 'once' and not cfg['once_at']:
|
|
||||||
raise ValueError('One-shot mode needs a date/time.')
|
|
||||||
|
|
||||||
cfg['next_run'] = self.compute_next_run(cfg)
|
|
||||||
# Arming a new schedule must not replay an old occurrence marker.
|
|
||||||
if 'next_run' in cfg and cfg.get('last_started_for') == cfg['next_run']:
|
|
||||||
cfg['last_started_for'] = ''
|
|
||||||
self._save_schedule(cfg)
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _clean_times(values):
|
|
||||||
return clean_times(values)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _clean_days(values, low, high):
|
|
||||||
return clean_days(values, low, high)
|
|
||||||
|
|
||||||
def compute_next_run(self, cfg=None, now=None):
|
|
||||||
"""Next action time as ISO string, or '' when nothing upcoming."""
|
|
||||||
return util_compute_next_run(cfg or self.get_schedule(), now)
|
|
||||||
|
|
||||||
def set_enabled(self, enabled):
|
|
||||||
"""Flip the enabled flag only; all schedule settings are preserved."""
|
|
||||||
cfg = self.get_schedule()
|
|
||||||
cfg['enabled'] = bool(enabled)
|
|
||||||
cfg['next_run'] = self.compute_next_run(cfg)
|
|
||||||
if cfg.get('last_started_for') == cfg['next_run']:
|
|
||||||
cfg['last_started_for'] = ''
|
|
||||||
self._save_schedule(cfg)
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
def clear_schedule(self):
|
|
||||||
"""Disarm the schedule but keep mode/times/days settings.
|
|
||||||
|
|
||||||
Clears the armed one-shot date, any pending next_run and the
|
|
||||||
last-fired marker; the configured mode, times and days are kept
|
|
||||||
so the schedule can be re-enabled without re-typing everything.
|
|
||||||
"""
|
|
||||||
cfg = self.get_schedule()
|
|
||||||
cfg['enabled'] = False
|
|
||||||
cfg['once_at'] = ''
|
|
||||||
cfg['next_run'] = ''
|
|
||||||
cfg['last_started_for'] = ''
|
|
||||||
self._save_schedule(cfg)
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
# ── active countdown ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
def status(self):
|
|
||||||
with self._lock:
|
|
||||||
if not self._active:
|
|
||||||
return {'active': False}
|
|
||||||
active = copy.deepcopy(self._active)
|
|
||||||
active['active'] = True
|
|
||||||
active['now'] = time.time()
|
|
||||||
return active
|
|
||||||
|
|
||||||
def start_shutdown(self, reason='manual', context=''):
|
|
||||||
return self._start('shutdown', time.time() + FULL_COUNTDOWN_SECONDS,
|
|
||||||
reason, context)
|
|
||||||
|
|
||||||
def start_restart(self, reason='manual', context=''):
|
|
||||||
return self._start('restart', time.time() + FULL_COUNTDOWN_SECONDS,
|
|
||||||
reason, context)
|
|
||||||
|
|
||||||
def start_restart_at(self, action_at, reason='scheduled', context=''):
|
|
||||||
return self._start('restart', float(action_at), reason, context)
|
|
||||||
|
|
||||||
def _start(self, kind, action_at, reason, context):
|
|
||||||
if kind not in ('shutdown', 'restart'):
|
|
||||||
return {'success': False, 'error': f'Unknown action: {kind}'}
|
|
||||||
with self._lock:
|
|
||||||
if self._active:
|
|
||||||
return {'success': False,
|
|
||||||
'error': f"A {self._active['kind']} countdown is already running"}
|
|
||||||
self._cancel_event.clear()
|
|
||||||
self._active = {
|
|
||||||
'kind': kind,
|
|
||||||
'reason': reason,
|
|
||||||
'context': context or '',
|
|
||||||
'started_at': time.time(),
|
|
||||||
'action_at': float(action_at),
|
|
||||||
'status': 'countdown',
|
|
||||||
'sent': [],
|
|
||||||
'log': [],
|
|
||||||
'error': '',
|
|
||||||
}
|
|
||||||
thread = threading.Thread(target=self._run_countdown, daemon=True)
|
|
||||||
self._thread = thread
|
|
||||||
thread.start()
|
|
||||||
action_iso = datetime.fromtimestamp(float(action_at)).isoformat()
|
|
||||||
logger.info(f'Lifecycle: {kind} countdown started ({reason}) -> {action_iso}')
|
|
||||||
return {'success': True, 'kind': kind,
|
|
||||||
'action_at': datetime.fromtimestamp(float(action_at)).isoformat()}
|
|
||||||
|
|
||||||
def cancel(self):
|
|
||||||
with self._lock:
|
|
||||||
if not self._active:
|
|
||||||
return {'success': False, 'error': 'No active countdown'}
|
|
||||||
if self._active.get('status') in ('executing', 'completed', 'failed'):
|
|
||||||
return {'success': False,
|
|
||||||
'error': 'Countdown already finished executing and cannot be cancelled'}
|
|
||||||
kind = self._active['kind']
|
|
||||||
reason = self._active.get('reason', 'manual')
|
|
||||||
context = self._active.get('context', '')
|
|
||||||
self._active['status'] = 'cancelling'
|
|
||||||
self._cancel_event.set()
|
|
||||||
thread = self._thread
|
|
||||||
if thread and thread.is_alive():
|
|
||||||
thread.join(timeout=30)
|
|
||||||
with self._lock:
|
|
||||||
self._active = None
|
|
||||||
self._thread = None
|
|
||||||
self._cancel_event.clear()
|
|
||||||
logger.info(f'Lifecycle: {kind} countdown cancelled')
|
|
||||||
# Tell players in-game so they know the shutdown/restart is off.
|
|
||||||
# The countdown thread itself stays silent on cancel: this is the
|
|
||||||
# single place the cancellation notice is sent (no duplicates).
|
|
||||||
notice_ok, notice_detail = self._cancellation_notice(kind, reason, context)
|
|
||||||
result = {'success': True, 'kind': kind,
|
|
||||||
'notice_sent': bool(notice_ok), 'notice': str(notice_detail)[:300]}
|
|
||||||
if not notice_ok:
|
|
||||||
logger.warning(f'Lifecycle: cancellation notice failed: {notice_detail}')
|
|
||||||
return result
|
|
||||||
|
|
||||||
def _cancellation_notice(self, kind, reason, context):
|
|
||||||
"""In-game broadcast announcing the countdown was cancelled."""
|
|
||||||
if kind == 'shutdown':
|
|
||||||
title = 'Server Shutdown'
|
|
||||||
message = 'Shutdown called off - the server is staying online.'
|
|
||||||
elif reason == 'scheduled':
|
|
||||||
context_suffix = f' ({context})' if context else ''
|
|
||||||
title = 'Scheduled Server Restart'
|
|
||||||
message = (f'Scheduled restart{context_suffix} called off - '
|
|
||||||
f'staying online.')
|
|
||||||
else:
|
|
||||||
title = 'Server Restart'
|
|
||||||
message = 'Restart called off - the server is staying online.'
|
|
||||||
try:
|
|
||||||
return self.admin.send_global_broadcast(title, message, 10)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f'Lifecycle cancellation-notice error: {e}')
|
|
||||||
return False, str(e)
|
|
||||||
|
|
||||||
def _wait_until(self, target_ts):
|
|
||||||
"""Sleep until target_ts, waking early on cancel (1s slices)."""
|
|
||||||
while True:
|
|
||||||
if self._cancel_event.is_set():
|
|
||||||
return False
|
|
||||||
remaining = float(target_ts) - time.time()
|
|
||||||
if remaining <= 0:
|
|
||||||
return True
|
|
||||||
self._cancel_event.wait(timeout=min(1.0, remaining))
|
|
||||||
if self._cancel_event.is_set():
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _run_countdown(self):
|
|
||||||
with self._lock:
|
|
||||||
active = self._active
|
|
||||||
if not active:
|
|
||||||
return
|
|
||||||
kind = active['kind']
|
|
||||||
reason = active.get('reason', 'manual')
|
|
||||||
context = active.get('context', '')
|
|
||||||
action_at = float(active['action_at'])
|
|
||||||
scheduled = (reason == 'scheduled')
|
|
||||||
|
|
||||||
for seconds_before, label, duration in COUNTDOWN_MARKS:
|
|
||||||
mark_at = action_at - seconds_before
|
|
||||||
now = time.time()
|
|
||||||
if now >= mark_at:
|
|
||||||
if now - mark_at <= MARK_GRACE_SECONDS:
|
|
||||||
# Due right now (e.g. the first notice at job start):
|
|
||||||
# send immediately instead of waiting.
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
# Missed while the dashboard was down: skip the stale mark.
|
|
||||||
self._record_sent(label, True, 'skipped (past due)')
|
|
||||||
continue
|
|
||||||
elif not self._wait_until(mark_at):
|
|
||||||
self._finish_cancelled()
|
|
||||||
return
|
|
||||||
title, message = self._message_for(kind, label, duration, scheduled, context,
|
|
||||||
final=False)
|
|
||||||
ok, detail = self._broadcast(title, message, duration)
|
|
||||||
self._record_sent(label, ok, detail)
|
|
||||||
if not ok:
|
|
||||||
# Keep counting down: a missed notice must not strand players
|
|
||||||
# without the final warning, but the miss is visible in status.
|
|
||||||
logger.warning(f'Lifecycle: broadcast failed at {label}: {detail}')
|
|
||||||
|
|
||||||
if not self._wait_until(action_at - FINAL_MARK_SECONDS):
|
|
||||||
self._finish_cancelled()
|
|
||||||
return
|
|
||||||
final_label = 'shutting down now' if kind == 'shutdown' else 'restarting now'
|
|
||||||
if scheduled and kind == 'restart':
|
|
||||||
final_label = 'scheduled restart starting now'
|
|
||||||
title, message = self._message_for(kind, final_label, FINAL_DURATION,
|
|
||||||
scheduled, context, final=True)
|
|
||||||
ok, detail = self._broadcast(title, message, FINAL_DURATION)
|
|
||||||
self._record_sent('now', ok, detail)
|
|
||||||
|
|
||||||
# Small buffer so the final notice is visible before the stop/restart.
|
|
||||||
time.sleep(2)
|
|
||||||
if self._cancel_event.is_set():
|
|
||||||
self._finish_cancelled()
|
|
||||||
return
|
|
||||||
|
|
||||||
self._set_status('executing')
|
|
||||||
ok, detail = self._execute(kind)
|
|
||||||
with self._lock:
|
|
||||||
if self._active:
|
|
||||||
self._active['status'] = 'completed' if ok else 'failed'
|
|
||||||
self._active['error'] = '' if ok else detail
|
|
||||||
self._active['completed_at'] = time.time()
|
|
||||||
self._active['log'].append(f'action: {detail}')
|
|
||||||
finished = copy.deepcopy(self._active)
|
|
||||||
# Leave the finished record briefly for the UI poll, then clear.
|
|
||||||
self._active = None
|
|
||||||
self._thread = None
|
|
||||||
logger.info(f"Lifecycle: {kind} finished ok={ok}: {detail}")
|
|
||||||
return finished
|
|
||||||
|
|
||||||
def _finish_cancelled(self):
|
|
||||||
with self._lock:
|
|
||||||
if self._active:
|
|
||||||
self._active['status'] = 'cancelled'
|
|
||||||
self._active = None
|
|
||||||
self._thread = None
|
|
||||||
self._cancel_event.clear()
|
|
||||||
logger.info('Lifecycle: countdown cancelled during wait')
|
|
||||||
|
|
||||||
def _set_status(self, status):
|
|
||||||
with self._lock:
|
|
||||||
if self._active:
|
|
||||||
self._active['status'] = status
|
|
||||||
|
|
||||||
def _record_sent(self, label, ok, detail):
|
|
||||||
with self._lock:
|
|
||||||
if self._active is not None:
|
|
||||||
self._active['sent'].append(
|
|
||||||
{'mark': label, 'ok': bool(ok), 'detail': str(detail)[:200],
|
|
||||||
'at': time.time()})
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _message_for(kind, label, duration, scheduled, context, final=False):
|
|
||||||
context_suffix = f' ({context})' if scheduled and context else ''
|
|
||||||
if kind == 'shutdown':
|
|
||||||
if final:
|
|
||||||
return ('Server Shutdown', 'Shutting down now - see you soon!')
|
|
||||||
return ('Server Shutdown',
|
|
||||||
f'Heads up - the server is shutting down in {label}. '
|
|
||||||
f'Get somewhere safe!')
|
|
||||||
# restart
|
|
||||||
if final:
|
|
||||||
if scheduled:
|
|
||||||
return ('Scheduled Server Restart',
|
|
||||||
f'Scheduled restart starting now{context_suffix} - back shortly!')
|
|
||||||
return ('Server Restart', 'Restarting now - back shortly!')
|
|
||||||
if scheduled:
|
|
||||||
return ('Scheduled Server Restart',
|
|
||||||
f'Heads up - scheduled restart in {label}{context_suffix}. '
|
|
||||||
f'Get somewhere safe!')
|
|
||||||
return ('Server Restart',
|
|
||||||
f'Heads up - server restart in {label}. Get somewhere safe!')
|
|
||||||
|
|
||||||
def _broadcast(self, title, message, duration):
|
|
||||||
try:
|
|
||||||
return self.admin.send_global_broadcast(title, message, int(duration))
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f'Lifecycle broadcast error: {e}')
|
|
||||||
return False, str(e)
|
|
||||||
|
|
||||||
def _execute(self, kind):
|
|
||||||
script = (self.settings.get('kubernetes', {}) or {}).get(
|
|
||||||
'battlegroup_script', '/home/dune/.dune/bin/battlegroup')
|
|
||||||
action = 'stop' if kind == 'shutdown' else 'restart'
|
|
||||||
try:
|
|
||||||
out, err, rc = self.ssh.run(f'{script} {action}', timeout=300)
|
|
||||||
detail = (out or '') + (err or '')
|
|
||||||
detail = detail.strip() or f'{action} completed'
|
|
||||||
if rc != 0:
|
|
||||||
return False, f'{action} failed (rc={rc}): {detail[:500]}'
|
|
||||||
return True, detail[:1000]
|
|
||||||
except Exception as e:
|
|
||||||
return False, str(e)
|
|
||||||
|
|
||||||
# ── scheduler tick (called from factory background thread) ─────────
|
|
||||||
|
|
||||||
def describe_context(self, cfg=None):
|
|
||||||
cfg = cfg or self.get_schedule()
|
|
||||||
mode = cfg.get('mode', 'daily')
|
|
||||||
if mode == 'once':
|
|
||||||
return 'one-time'
|
|
||||||
if mode == 'daily':
|
|
||||||
return 'daily ' + ', '.join(cfg.get('daily_times') or [])
|
|
||||||
if mode == 'weekly':
|
|
||||||
day_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
|
||||||
days = ', '.join(day_names[d] for d in (cfg.get('weekly_days') or []))
|
|
||||||
return f"weekly {days} {', '.join(cfg.get('weekly_times') or [])}"
|
|
||||||
if mode == 'monthly':
|
|
||||||
return (f"monthly day {', '.join(str(d) for d in (cfg.get('monthly_days') or []))} "
|
|
||||||
f"{cfg.get('monthly_time', '')}")
|
|
||||||
return mode
|
|
||||||
|
|
||||||
def check_and_fire(self, now=None):
|
|
||||||
"""Start the countdown when inside the 15-minute window before next_run."""
|
|
||||||
cfg = self.get_schedule()
|
|
||||||
if not cfg.get('enabled'):
|
|
||||||
return None
|
|
||||||
next_run = cfg.get('next_run') or self.compute_next_run(cfg, now)
|
|
||||||
if not next_run:
|
|
||||||
return None
|
|
||||||
# Keep next_run fresh if the mode changed underneath us.
|
|
||||||
if cfg.get('next_run') != next_run:
|
|
||||||
cfg['next_run'] = next_run
|
|
||||||
self._save_schedule(cfg)
|
|
||||||
try:
|
|
||||||
action_at = parse_when(next_run).timestamp()
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
now_ts = time.time() if now is None else now.timestamp()
|
|
||||||
if cfg.get('last_started_for') == next_run:
|
|
||||||
return None
|
|
||||||
with self._lock:
|
|
||||||
if self._active:
|
|
||||||
return None
|
|
||||||
if now_ts < action_at - FULL_COUNTDOWN_SECONDS:
|
|
||||||
return None
|
|
||||||
if now_ts > action_at + 120:
|
|
||||||
# Missed window (dashboard was down): roll forward, do not fire late.
|
|
||||||
cfg['last_started_for'] = next_run
|
|
||||||
cfg['next_run'] = self.compute_next_run(cfg, datetime.now())
|
|
||||||
self._save_schedule(cfg)
|
|
||||||
logger.warning(f'Lifecycle: missed scheduled restart for {next_run}, rolled forward')
|
|
||||||
return None
|
|
||||||
context = self.describe_context(cfg)
|
|
||||||
result = self.start_restart_at(action_at, reason='scheduled', context=context)
|
|
||||||
if result.get('success'):
|
|
||||||
cfg['last_started_for'] = next_run
|
|
||||||
# Advance to the occurrence *after* this one, not after now.
|
|
||||||
anchor = datetime.fromtimestamp(action_at) + timedelta(seconds=1)
|
|
||||||
cfg['next_run'] = self.compute_next_run(cfg, anchor)
|
|
||||||
self._save_schedule(cfg)
|
|
||||||
logger.info(f'Lifecycle: scheduled restart countdown started for {next_run}')
|
|
||||||
return result
|
|
||||||
return None
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
"""Shared schedule helpers: validation + next-run computation.
|
|
||||||
|
|
||||||
Used by the restart lifecycle scheduler and the custom-notification
|
|
||||||
scheduler. All times are server-local naive datetimes. ISO strings from
|
|
||||||
`<input type="datetime-local">` ("YYYY-MM-DDTHH:MM") and UTC ("...Z")
|
|
||||||
strings are both accepted.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
SCHEDULE_MODES = ('once', 'daily', 'weekly', 'monthly')
|
|
||||||
|
|
||||||
|
|
||||||
def parse_hhmm(value):
|
|
||||||
"""Parse 'HH:MM' -> (hour, minute), raising ValueError when invalid."""
|
|
||||||
parts = str(value or '').strip().split(':')
|
|
||||||
if len(parts) != 2:
|
|
||||||
raise ValueError(f'Invalid time: {value!r} (expected HH:MM)')
|
|
||||||
hour, minute = int(parts[0]), int(parts[1])
|
|
||||||
if not (0 <= hour <= 23 and 0 <= minute <= 59):
|
|
||||||
raise ValueError(f'Invalid time: {value!r}')
|
|
||||||
return hour, minute
|
|
||||||
|
|
||||||
|
|
||||||
def clean_times(values):
|
|
||||||
"""Validate a list of 'HH:MM' strings; returns sorted unique list."""
|
|
||||||
if isinstance(values, str):
|
|
||||||
values = [values]
|
|
||||||
cleaned = []
|
|
||||||
for value in values or []:
|
|
||||||
value = str(value).strip()
|
|
||||||
if not value:
|
|
||||||
continue
|
|
||||||
parse_hhmm(value)
|
|
||||||
if value not in cleaned:
|
|
||||||
cleaned.append(value)
|
|
||||||
return sorted(cleaned)
|
|
||||||
|
|
||||||
|
|
||||||
def clean_days(values, low, high):
|
|
||||||
"""Validate a list of integer days in [low, high]; sorted unique list."""
|
|
||||||
if isinstance(values, (int, str)):
|
|
||||||
values = [values]
|
|
||||||
cleaned = []
|
|
||||||
for value in values or []:
|
|
||||||
try:
|
|
||||||
day = int(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
raise ValueError(f'Invalid day: {value!r}')
|
|
||||||
if not (low <= day <= high):
|
|
||||||
raise ValueError(f'Day out of range: {value!r}')
|
|
||||||
if day not in cleaned:
|
|
||||||
cleaned.append(day)
|
|
||||||
return sorted(cleaned)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_when(raw):
|
|
||||||
"""Parse an ISO datetime string -> naive server-local datetime."""
|
|
||||||
dt = datetime.fromisoformat(str(raw).strip())
|
|
||||||
if dt.tzinfo is not None:
|
|
||||||
dt = dt.astimezone().replace(tzinfo=None)
|
|
||||||
return dt
|
|
||||||
|
|
||||||
|
|
||||||
def next_once(cfg, now):
|
|
||||||
raw = str(cfg.get('once_at') or '').strip()
|
|
||||||
if not raw:
|
|
||||||
return ''
|
|
||||||
candidate = parse_when(raw)
|
|
||||||
return candidate.isoformat() if candidate > now else ''
|
|
||||||
|
|
||||||
|
|
||||||
def next_daily_weekly(now, days, times):
|
|
||||||
cleaned_times = []
|
|
||||||
for value in times or []:
|
|
||||||
try:
|
|
||||||
cleaned_times.append(parse_hhmm(value))
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if not cleaned_times:
|
|
||||||
return ''
|
|
||||||
best = None
|
|
||||||
for offset in range(8):
|
|
||||||
base = datetime(now.year, now.month, now.day) + timedelta(days=offset)
|
|
||||||
if days is not None and base.weekday() not in days:
|
|
||||||
continue
|
|
||||||
for hour, minute in cleaned_times:
|
|
||||||
candidate = base.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
|
||||||
if candidate <= now:
|
|
||||||
continue
|
|
||||||
if best is None or candidate < best:
|
|
||||||
best = candidate
|
|
||||||
return best.isoformat() if best else ''
|
|
||||||
|
|
||||||
|
|
||||||
def next_monthly(now, cfg, time_key='monthly_time', days_key='monthly_days'):
|
|
||||||
try:
|
|
||||||
hour, minute = parse_hhmm(cfg.get(time_key, '05:00'))
|
|
||||||
except ValueError:
|
|
||||||
return ''
|
|
||||||
month_days = set(cfg.get(days_key) or [])
|
|
||||||
if not month_days:
|
|
||||||
return ''
|
|
||||||
# Scan day-by-day (covers varying month lengths without dateutil).
|
|
||||||
base = datetime(now.year, now.month, now.day)
|
|
||||||
for offset in range(1, 370):
|
|
||||||
day = base + timedelta(days=offset)
|
|
||||||
if day.day not in month_days:
|
|
||||||
continue
|
|
||||||
candidate = day.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
|
||||||
if candidate > now:
|
|
||||||
return candidate.isoformat()
|
|
||||||
return ''
|
|
||||||
|
|
||||||
|
|
||||||
def compute_next_run(cfg, now=None):
|
|
||||||
"""Next action time as ISO string, or '' when nothing upcoming."""
|
|
||||||
cfg = cfg or {}
|
|
||||||
now = now or datetime.now()
|
|
||||||
mode = cfg.get('mode', 'daily')
|
|
||||||
try:
|
|
||||||
if mode == 'once':
|
|
||||||
return next_once(cfg, now)
|
|
||||||
if mode == 'daily':
|
|
||||||
return next_daily_weekly(now, days=None, times=cfg.get('daily_times') or [])
|
|
||||||
if mode == 'weekly':
|
|
||||||
return next_daily_weekly(now, days=set(cfg.get('weekly_days') or []),
|
|
||||||
times=cfg.get('weekly_times') or [])
|
|
||||||
if mode == 'monthly':
|
|
||||||
return next_monthly(now, cfg)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f'Schedule: next-run calc failed: {e}')
|
|
||||||
return ''
|
|
||||||
@@ -1,251 +0,0 @@
|
|||||||
"""Scheduled custom notifications - one-off/recurring in-game broadcasts.
|
|
||||||
|
|
||||||
Shares schedule validation + next-run computation with the restart
|
|
||||||
lifecycle scheduler (app/services/schedule_util.py). Delivery reuses the
|
|
||||||
confirmed In-Game Broadcast path (AdminService.send_global_broadcast).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
import threading
|
|
||||||
import uuid
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
from app.services.schedule_util import (
|
|
||||||
SCHEDULE_MODES,
|
|
||||||
clean_days,
|
|
||||||
clean_times,
|
|
||||||
compute_next_run,
|
|
||||||
parse_hhmm,
|
|
||||||
parse_when,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
MIN_DURATION = 5
|
|
||||||
MAX_DURATION = 300
|
|
||||||
DEFAULT_DURATION = 30
|
|
||||||
# A missed occurrence older than this is rolled forward, never fired late.
|
|
||||||
MISSED_WINDOW_SECONDS = 3600
|
|
||||||
|
|
||||||
|
|
||||||
def _default_state_dir():
|
|
||||||
return os.path.join(
|
|
||||||
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
|
|
||||||
|
|
||||||
|
|
||||||
def default_entry():
|
|
||||||
return {
|
|
||||||
'id': uuid.uuid4().hex[:8],
|
|
||||||
'enabled': True,
|
|
||||||
'title': '',
|
|
||||||
'message': '',
|
|
||||||
'duration': DEFAULT_DURATION,
|
|
||||||
'mode': 'daily',
|
|
||||||
'daily_times': ['12:00'],
|
|
||||||
'weekly_days': [6],
|
|
||||||
'weekly_times': ['12:00'],
|
|
||||||
'monthly_days': [1],
|
|
||||||
'monthly_time': '12:00',
|
|
||||||
'once_at': '',
|
|
||||||
'next_run': '',
|
|
||||||
'last_fired_for': '',
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class ScheduledBroadcastService:
|
|
||||||
"""Stores + fires scheduled custom notification entries."""
|
|
||||||
|
|
||||||
def __init__(self, admin_service, state_dir=None):
|
|
||||||
self.admin = admin_service
|
|
||||||
self.state_dir = state_dir or _default_state_dir()
|
|
||||||
os.makedirs(self.state_dir, exist_ok=True)
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
|
|
||||||
# ── persistence ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def _path(self):
|
|
||||||
return os.path.join(self.state_dir, 'broadcast-schedule.json')
|
|
||||||
|
|
||||||
def list_entries(self):
|
|
||||||
try:
|
|
||||||
with open(self._path()) as f:
|
|
||||||
stored = json.load(f) or {}
|
|
||||||
entries = stored.get('entries') or []
|
|
||||||
return [e for e in entries if isinstance(e, dict)]
|
|
||||||
except FileNotFoundError:
|
|
||||||
return []
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f'ScheduledBroadcast: could not read schedule: {e}')
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _save(self, entries):
|
|
||||||
with open(self._path(), 'w') as f:
|
|
||||||
json.dump({'entries': entries}, f, indent=2)
|
|
||||||
|
|
||||||
def _find(self, entries, entry_id):
|
|
||||||
for entry in entries:
|
|
||||||
if entry.get('id') == entry_id:
|
|
||||||
return entry
|
|
||||||
return None
|
|
||||||
|
|
||||||
# ── CRUD ──────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def save_entry(self, data):
|
|
||||||
"""Create or update an entry; validates, recomputes next_run."""
|
|
||||||
data = dict(data or {})
|
|
||||||
with self._lock:
|
|
||||||
entries = self.list_entries()
|
|
||||||
entry_id = str(data.get('id') or '').strip()
|
|
||||||
if entry_id:
|
|
||||||
entry = self._find(entries, entry_id)
|
|
||||||
if entry is None:
|
|
||||||
raise ValueError(f'Unknown scheduled notification: {entry_id!r}')
|
|
||||||
else:
|
|
||||||
entry = default_entry()
|
|
||||||
entries.append(entry)
|
|
||||||
|
|
||||||
if 'enabled' in data:
|
|
||||||
entry['enabled'] = bool(data['enabled'])
|
|
||||||
for field in ('title', 'message'):
|
|
||||||
if field in data:
|
|
||||||
entry[field] = str(data[field] or '').strip()
|
|
||||||
if 'duration' in data:
|
|
||||||
try:
|
|
||||||
duration = int(data['duration'])
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
raise ValueError('Duration must be a number of seconds.')
|
|
||||||
entry['duration'] = max(MIN_DURATION, min(MAX_DURATION, duration))
|
|
||||||
if 'mode' in data:
|
|
||||||
mode = str(data['mode']).strip().lower()
|
|
||||||
if mode not in SCHEDULE_MODES:
|
|
||||||
raise ValueError(f'Invalid mode: {mode!r}')
|
|
||||||
entry['mode'] = mode
|
|
||||||
if 'daily_times' in data:
|
|
||||||
entry['daily_times'] = clean_times(data['daily_times'])
|
|
||||||
if 'weekly_times' in data:
|
|
||||||
entry['weekly_times'] = clean_times(data['weekly_times'])
|
|
||||||
if 'weekly_days' in data:
|
|
||||||
entry['weekly_days'] = clean_days(data['weekly_days'], 0, 6)
|
|
||||||
if 'monthly_days' in data:
|
|
||||||
entry['monthly_days'] = clean_days(data['monthly_days'], 1, 31)
|
|
||||||
if 'monthly_time' in data:
|
|
||||||
parse_hhmm(data['monthly_time'])
|
|
||||||
entry['monthly_time'] = str(data['monthly_time']).strip()
|
|
||||||
if 'once_at' in data:
|
|
||||||
entry['once_at'] = str(data['once_at'] or '').strip()
|
|
||||||
if entry['once_at']:
|
|
||||||
try:
|
|
||||||
parse_when(entry['once_at'])
|
|
||||||
except ValueError:
|
|
||||||
raise ValueError('One-shot date/time is not valid.')
|
|
||||||
|
|
||||||
if not entry['title'] or not entry['message']:
|
|
||||||
raise ValueError('Title and message are required.')
|
|
||||||
mode = entry['mode']
|
|
||||||
if mode == 'daily' and not entry['daily_times']:
|
|
||||||
raise ValueError('Daily mode needs at least one time (HH:MM).')
|
|
||||||
if mode == 'weekly' and (not entry['weekly_days'] or not entry['weekly_times']):
|
|
||||||
raise ValueError('Weekly mode needs days and at least one time.')
|
|
||||||
if mode == 'monthly' and (not entry['monthly_days'] or not entry['monthly_time']):
|
|
||||||
raise ValueError('Monthly mode needs days of month and a time.')
|
|
||||||
if mode == 'once' and not entry['once_at']:
|
|
||||||
raise ValueError('One-shot mode needs a date/time.')
|
|
||||||
|
|
||||||
entry['next_run'] = compute_next_run(entry)
|
|
||||||
if entry.get('last_fired_for') == entry['next_run']:
|
|
||||||
entry['last_fired_for'] = ''
|
|
||||||
self._save(entries)
|
|
||||||
logger.info(f"ScheduledBroadcast: saved entry {entry['id']} "
|
|
||||||
f"enabled={entry['enabled']} next={entry['next_run']}")
|
|
||||||
return dict(entry)
|
|
||||||
|
|
||||||
def delete_entry(self, entry_id):
|
|
||||||
with self._lock:
|
|
||||||
entries = self.list_entries()
|
|
||||||
kept = [e for e in entries if e.get('id') != entry_id]
|
|
||||||
if len(kept) == len(entries):
|
|
||||||
return False
|
|
||||||
self._save(kept)
|
|
||||||
logger.info(f'ScheduledBroadcast: deleted entry {entry_id}')
|
|
||||||
return True
|
|
||||||
|
|
||||||
def set_enabled(self, entry_id, enabled):
|
|
||||||
"""Flip enabled only; message + schedule settings are preserved."""
|
|
||||||
with self._lock:
|
|
||||||
entries = self.list_entries()
|
|
||||||
entry = self._find(entries, entry_id)
|
|
||||||
if entry is None:
|
|
||||||
raise ValueError(f'Unknown scheduled notification: {entry_id!r}')
|
|
||||||
entry['enabled'] = bool(enabled)
|
|
||||||
entry['next_run'] = compute_next_run(entry)
|
|
||||||
if entry.get('last_fired_for') == entry['next_run']:
|
|
||||||
entry['last_fired_for'] = ''
|
|
||||||
self._save(entries)
|
|
||||||
return dict(entry)
|
|
||||||
|
|
||||||
# ── scheduler tick (called from factory background thread) ─────────
|
|
||||||
|
|
||||||
def check_and_fire(self, now=None):
|
|
||||||
"""Send every due entry once. Returns list of fired entry summaries."""
|
|
||||||
now_dt = now or datetime.now()
|
|
||||||
now_ts = now_dt.timestamp()
|
|
||||||
fired = []
|
|
||||||
with self._lock:
|
|
||||||
entries = self.list_entries()
|
|
||||||
changed = False
|
|
||||||
for entry in entries:
|
|
||||||
if not entry.get('enabled'):
|
|
||||||
continue
|
|
||||||
next_run = entry.get('next_run') or compute_next_run(entry, now_dt)
|
|
||||||
if not next_run:
|
|
||||||
continue
|
|
||||||
if entry.get('next_run') != next_run:
|
|
||||||
entry['next_run'] = next_run
|
|
||||||
changed = True
|
|
||||||
if entry.get('last_fired_for') == next_run:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
action_ts = parse_when(next_run).timestamp()
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if now_ts < action_ts:
|
|
||||||
continue
|
|
||||||
if now_ts > action_ts + MISSED_WINDOW_SECONDS:
|
|
||||||
# Dashboard was down: roll forward, never fire late.
|
|
||||||
entry['last_fired_for'] = next_run
|
|
||||||
if entry['mode'] == 'once':
|
|
||||||
entry['enabled'] = False
|
|
||||||
entry['next_run'] = ''
|
|
||||||
else:
|
|
||||||
entry['next_run'] = compute_next_run(entry, now_dt)
|
|
||||||
changed = True
|
|
||||||
logger.warning(
|
|
||||||
f"ScheduledBroadcast: missed {entry['id']} for {next_run}, rolled forward")
|
|
||||||
continue
|
|
||||||
ok, detail = self._send(entry)
|
|
||||||
entry['last_fired_for'] = next_run
|
|
||||||
if entry['mode'] == 'once':
|
|
||||||
# One-shot fires exactly once, settings are kept for reuse.
|
|
||||||
entry['enabled'] = False
|
|
||||||
entry['next_run'] = ''
|
|
||||||
else:
|
|
||||||
anchor = datetime.fromtimestamp(action_ts) + timedelta(seconds=1)
|
|
||||||
entry['next_run'] = compute_next_run(entry, anchor)
|
|
||||||
changed = True
|
|
||||||
fired.append({'id': entry['id'], 'success': bool(ok),
|
|
||||||
'detail': str(detail)[:300]})
|
|
||||||
logger.info(f"ScheduledBroadcast: fired {entry['id']} "
|
|
||||||
f"for {next_run} ok={ok}")
|
|
||||||
if changed:
|
|
||||||
self._save(entries)
|
|
||||||
return fired
|
|
||||||
|
|
||||||
def _send(self, entry):
|
|
||||||
try:
|
|
||||||
return self.admin.send_global_broadcast(
|
|
||||||
entry['title'], entry['message'], int(entry.get('duration') or 30))
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f'ScheduledBroadcast send error: {e}')
|
|
||||||
return False, str(e)
|
|
||||||
+3
-47
@@ -79,15 +79,12 @@ class SSHService:
|
|||||||
self._client = client
|
self._client = client
|
||||||
return self._client
|
return self._client
|
||||||
|
|
||||||
def run(self, command, timeout=30, quiet=False):
|
def run(self, command, timeout=30):
|
||||||
"""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).
|
||||||
@@ -98,7 +95,6 @@ class SSHService:
|
|||||||
try:
|
try:
|
||||||
client = self._get_client()
|
client = self._get_client()
|
||||||
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
|
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
|
||||||
stdout.channel.settimeout(timeout)
|
|
||||||
out = stdout.read().decode('utf-8', errors='replace')
|
out = stdout.read().decode('utf-8', errors='replace')
|
||||||
err = stderr.read().decode('utf-8', errors='replace')
|
err = stderr.read().decode('utf-8', errors='replace')
|
||||||
rc = stdout.channel.recv_exit_status()
|
rc = stdout.channel.recv_exit_status()
|
||||||
@@ -106,19 +102,13 @@ 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:
|
||||||
if quiet:
|
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||||
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
|
||||||
if quiet:
|
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||||
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}")
|
||||||
@@ -131,40 +121,6 @@ class SSHService:
|
|||||||
self._client = None
|
self._client = None
|
||||||
return '', str(ex), -1
|
return '', str(ex), -1
|
||||||
|
|
||||||
def write_file(self, remote_path, data, timeout=30):
|
|
||||||
"""Write text data to a remote file via base64 over stdin.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
remote_path: Absolute path on the remote machine.
|
|
||||||
data: String content to write.
|
|
||||||
timeout: Max seconds to wait for command completion.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Tuple of (stdout, stderr, return_code).
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
encoded = base64.b64encode(data.encode('utf-8'))
|
|
||||||
try:
|
|
||||||
client = self._get_client()
|
|
||||||
stdin, stdout, stderr = client.exec_command(
|
|
||||||
f'base64 -d > {remote_path}',
|
|
||||||
timeout=timeout
|
|
||||||
)
|
|
||||||
stdout.channel.settimeout(timeout)
|
|
||||||
stdin.write(encoded)
|
|
||||||
stdin.flush()
|
|
||||||
stdin.channel.shutdown_write()
|
|
||||||
out = stdout.read().decode('utf-8', errors='replace')
|
|
||||||
err = stderr.read().decode('utf-8', errors='replace')
|
|
||||||
rc = stdout.channel.recv_exit_status()
|
|
||||||
if rc != 0:
|
|
||||||
logger.warning(f"SSH write_file failed (rc={rc}, path={remote_path}): {err[:200]}")
|
|
||||||
return out, err, rc
|
|
||||||
except Exception as ex:
|
|
||||||
logger.error(f"SSH write_file error ({remote_path}): {ex}")
|
|
||||||
self._client = None
|
|
||||||
return '', str(ex), -1
|
|
||||||
|
|
||||||
def check_connection(self):
|
def check_connection(self):
|
||||||
"""Test SSH connectivity with a simple echo command.
|
"""Test SSH connectivity with a simple echo command.
|
||||||
|
|
||||||
|
|||||||
@@ -74,7 +74,6 @@ NAV_PAGES = [
|
|||||||
('/director', 'Director'),
|
('/director', 'Director'),
|
||||||
('/shell', 'Shell'),
|
('/shell', 'Shell'),
|
||||||
('/files', 'Files'),
|
('/files', 'Files'),
|
||||||
('/backup', 'Backup'),
|
|
||||||
('/events', 'Events'),
|
('/events', 'Events'),
|
||||||
('/chat', 'Chat'),
|
('/chat', 'Chat'),
|
||||||
('/players', 'Players'),
|
('/players', 'Players'),
|
||||||
@@ -82,6 +81,8 @@ NAV_PAGES = [
|
|||||||
('/guilds', 'Guilds'),
|
('/guilds', 'Guilds'),
|
||||||
('/buildings', 'Buildings'),
|
('/buildings', 'Buildings'),
|
||||||
('/map', 'Map'),
|
('/map', 'Map'),
|
||||||
|
('/admin-experimental', 'Experimental'),
|
||||||
|
('/backup', 'Backup'),
|
||||||
]
|
]
|
||||||
|
|
||||||
NAV_GROUPS = [
|
NAV_GROUPS = [
|
||||||
@@ -91,7 +92,6 @@ NAV_GROUPS = [
|
|||||||
('/director', 'Director'),
|
('/director', 'Director'),
|
||||||
('/shell', 'Shell'),
|
('/shell', 'Shell'),
|
||||||
('/files', 'Files'),
|
('/files', 'Files'),
|
||||||
('/backup', 'Backup'),
|
|
||||||
]),
|
]),
|
||||||
('Players', [
|
('Players', [
|
||||||
('/players', 'Players'),
|
('/players', 'Players'),
|
||||||
@@ -104,4 +104,8 @@ NAV_GROUPS = [
|
|||||||
('/chat', 'Chat'),
|
('/chat', 'Chat'),
|
||||||
('/map', 'Map'),
|
('/map', 'Map'),
|
||||||
]),
|
]),
|
||||||
|
('System', [
|
||||||
|
('/admin-experimental', 'Experimental'),
|
||||||
|
('/backup', 'Backup'),
|
||||||
|
]),
|
||||||
]
|
]
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
"""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
|
|
||||||
+67
-30
@@ -149,6 +149,17 @@ 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 = @{} }
|
||||||
@@ -158,6 +169,16 @@ 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
|
||||||
@@ -170,6 +191,26 @@ 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
|
||||||
@@ -749,6 +790,22 @@ 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 " "
|
||||||
@@ -882,10 +939,11 @@ 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/ (log files)" -ForegroundColor Yellow
|
Write-Host " - logs/, app/logs/, backend/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/)" -ForegroundColor Yellow
|
Write-Host " - __pycache__/ (Python cache in app/, backend/)" -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
|
||||||
@@ -927,7 +985,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")
|
$cacheSearchPaths = @("app", "backend")
|
||||||
$totalCacheDirs = 0
|
$totalCacheDirs = 0
|
||||||
foreach ($csp in $cacheSearchPaths) {
|
foreach ($csp in $cacheSearchPaths) {
|
||||||
$cspPath = Join-Path $ProjectRoot $csp
|
$cspPath = Join-Path $ProjectRoot $csp
|
||||||
@@ -939,6 +997,10 @@ 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
|
||||||
@@ -949,7 +1011,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")
|
$artifactDirs = @(".pytest_cache", "htmlcov", "build", "backups", "frontend\.vite")
|
||||||
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++ }
|
||||||
@@ -2399,32 +2461,7 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
Set-Location -LiteralPath $ProjectRoot
|
Set-Location -LiteralPath $ProjectRoot
|
||||||
# Exit code 42 = watchdog tripped (dashboard wedged) - restart it
|
python run.py
|
||||||
# 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,4 +9,3 @@ 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,23 +30,6 @@ 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:
|
||||||
@@ -153,35 +136,4 @@ 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")
|
||||||
|
|
||||||
# Self-watchdog: exits with code 42 if the server stops answering,
|
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
||||||
# 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()
|
|
||||||
@@ -52,9 +52,6 @@ director:
|
|||||||
# File Browser
|
# File Browser
|
||||||
filebrowser:
|
filebrowser:
|
||||||
port: 18888 # File Browser service port
|
port: 18888 # File Browser service port
|
||||||
#allowed_roots: # Directories the file browser may access.
|
|
||||||
# - /srv # Empty/missing = defaults (/srv, /home/dune/.dune).
|
|
||||||
# - /home/dune/.dune
|
|
||||||
|
|
||||||
# Firewall Security
|
# Firewall Security
|
||||||
# Block external internet access to game server services that have no authentication.
|
# Block external internet access to game server services that have no authentication.
|
||||||
|
|||||||
@@ -192,78 +192,6 @@ 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..."
|
||||||
@@ -299,15 +227,15 @@ server:
|
|||||||
ssh_key: ${SSH_KEY_YAML}
|
ssh_key: ${SSH_KEY_YAML}
|
||||||
|
|
||||||
dashboard:
|
dashboard:
|
||||||
host: ${DASH_HOST}
|
host: 127.0.0.1
|
||||||
port: ${DASH_PORT}
|
port: ${DASH_PORT}
|
||||||
debug: false
|
debug: false
|
||||||
secret_key: ${SECRET_KEY}
|
secret_key: ${SECRET_KEY}
|
||||||
ssl_cert: ${SSL_CERT}
|
ssl_cert: null
|
||||||
ssl_key: ${SSL_KEY}
|
ssl_key: null
|
||||||
ssl_domain: ${SSL_DOMAIN}
|
ssl_domain: null
|
||||||
ssl_email: ${SSL_EMAIL}
|
ssl_email: null
|
||||||
http_redirect: ${HTTP_REDIRECT}
|
http_redirect: false
|
||||||
http_redirect_port: 80
|
http_redirect_port: 80
|
||||||
|
|
||||||
database:
|
database:
|
||||||
@@ -348,11 +276,14 @@ logging:
|
|||||||
max_bytes: 10485760
|
max_bytes: 10485760
|
||||||
backup_count: 5
|
backup_count: 5
|
||||||
|
|
||||||
rabbitmq:
|
rmq:
|
||||||
admin_port: ${RMQ_ADMIN_PORT}
|
admin_host: 127.0.0.1
|
||||||
game_port: ${RMQ_GAME_PORT}
|
admin_port: 32686
|
||||||
username: dashboard_admin
|
game_host: 127.0.0.1
|
||||||
|
game_port: 32021
|
||||||
|
username: admin
|
||||||
password: null
|
password: null
|
||||||
|
ttl: 15
|
||||||
YAML_EOF
|
YAML_EOF
|
||||||
|
|
||||||
echo " settings.yaml created!"
|
echo " settings.yaml created!"
|
||||||
@@ -367,30 +298,16 @@ 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"
|
echo " 1. Start the dashboard: bash start.sh -> option 1 (classic)"
|
||||||
|
echo " Or try the new UI: bash start.sh -> option 7 (React)"
|
||||||
echo ""
|
echo ""
|
||||||
if [ "$SSL_CERT" != "null" ]; then
|
echo " 2. Open http://localhost:${DASH_PORT} in your browser"
|
||||||
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,23 +31,9 @@ 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 " [4] Start Dashboard (Debug Mode)"
|
echo " [7] Start New Dashboard (React + ChakraUI)"
|
||||||
echo " Start with verbose debug logging. Only use when troubleshooting."
|
echo " Launch the modern React dashboard with auto-install."
|
||||||
echo ""
|
echo " Backend API + frontend dev server (http://localhost:5173)"
|
||||||
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 ""
|
||||||
@@ -77,7 +63,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, cheroot" 2>/dev/null
|
$PYTHON -c "import flask, flask_socketio, yaml, flask_login, flask_wtf, flask_limiter, paramiko, argon2, cryptography" 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."
|
||||||
@@ -112,8 +98,7 @@ 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
|
||||||
# Status goes to stderr so command substitution callers get a clean path on stdout.
|
echo " SSH Key: Found at $kp"
|
||||||
echo " SSH Key: Found at $kp" >&2
|
|
||||||
echo "$kp"
|
echo "$kp"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
@@ -277,7 +262,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
|
||||||
@@ -300,7 +285,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
|
||||||
@@ -312,7 +297,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 ""
|
||||||
|
|
||||||
@@ -321,8 +306,7 @@ 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 (only when a key file was actually found, otherwise the
|
# SSH Connection
|
||||||
# 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 "
|
||||||
@@ -331,11 +315,7 @@ 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)
|
||||||
if [ -f "$ssh_key" ]; then
|
test_ssh_connection "$ssh_key" "$server_host" "$server_user" || ((issues++))
|
||||||
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
|
||||||
@@ -383,13 +363,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 || true
|
read -r show_guide
|
||||||
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 || true
|
read -r
|
||||||
}
|
}
|
||||||
|
|
||||||
run_setup() {
|
run_setup() {
|
||||||
@@ -406,7 +386,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 || true
|
read -r
|
||||||
}
|
}
|
||||||
|
|
||||||
start_dashboard() {
|
start_dashboard() {
|
||||||
@@ -433,21 +413,6 @@ 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)
|
||||||
@@ -455,10 +420,6 @@ if lg.get('debug_enabled') is True:
|
|||||||
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 "
|
||||||
@@ -515,18 +476,14 @@ if k and k != 'null':
|
|||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Kill existing SSH tunnels on the DB/Director/RMQ ports.
|
# Kill existing SSH tunnels on the DB/Director ports
|
||||||
# Each kill is guarded so an empty port can never widen the pattern
|
pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
||||||
# into matching unrelated SSH processes.
|
pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
|
||||||
[ -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}" -L "${rmq_admin_port}:localhost:${rmq_admin_port}" -L "${rmq_game_port}:localhost:${rmq_game_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}" -N "${ssh_user}@${server_host}" &
|
||||||
ssh_tunnel_pid=$!
|
ssh_tunnel_pid=$!
|
||||||
|
|
||||||
connected=false
|
connected=false
|
||||||
@@ -561,7 +518,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 (DB), localhost:$director_port (Director), localhost:$rmq_admin_port (RMQ Admin), localhost:$rmq_game_port (RMQ Game)"
|
echo "[OK] SSH tunnel up on localhost:$local_port"
|
||||||
|
|
||||||
# [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..."
|
||||||
@@ -663,25 +620,7 @@ if k and k != 'null':
|
|||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
cd "$PROJECT_ROOT"
|
cd "$PROJECT_ROOT"
|
||||||
# Exit code 42 = watchdog tripped (dashboard wedged) - restart it
|
$PYTHON run.py
|
||||||
# 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..."
|
||||||
@@ -689,353 +628,250 @@ 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() {
|
||||||
# ── Shared Server Helpers ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
# Load server connection details from settings.yaml.
|
|
||||||
# Sets: server_host ssh_user namespace ssh_key. Returns non-zero on error.
|
|
||||||
load_server_settings() {
|
|
||||||
settings_file="$PROJECT_ROOT/settings.yaml"
|
|
||||||
if [ ! -f "$settings_file" ]; then
|
|
||||||
echo " [ERROR] settings.yaml not found. Run setup first."
|
|
||||||
return 1
|
|
||||||
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 " ============================================================"
|
echo " Starting NEW dashboard (React + ChakraUI)..."
|
||||||
echo " Starting Dashboard with DEBUG LOGGING enabled"
|
|
||||||
echo " ============================================================"
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " WARNING: Debug logging can significantly impact performance!"
|
|
||||||
echo " - Logs every HTTP request/response"
|
# Check Python
|
||||||
echo " - Logs all SSH commands and results"
|
if ! determine_python; then
|
||||||
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"
|
|
||||||
if [ ! -f "$settings_file" ]; then
|
# Check Node.js
|
||||||
echo " [ERROR] settings.yaml not found. Run setup first."
|
if ! command -v node &>/dev/null; then
|
||||||
|
echo " Node.js: NOT FOUND"
|
||||||
|
echo ""
|
||||||
|
echo " Node.js 18+ is required for the new frontend."
|
||||||
|
echo " Install: https://nodejs.org/ or use nvm"
|
||||||
|
echo ""
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
$PYTHON -c "
|
echo " Node.js: $(node --version)"
|
||||||
|
|
||||||
|
# Check dependencies
|
||||||
|
test_dependencies
|
||||||
|
|
||||||
|
# Check settings
|
||||||
|
settings_file="$PROJECT_ROOT/settings.yaml"
|
||||||
|
if [ ! -f "$settings_file" ]; then
|
||||||
|
echo ""
|
||||||
|
echo " [ERROR] settings.yaml not found. You need to run setup first."
|
||||||
|
echo ""
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Read settings
|
||||||
|
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)
|
||||||
|
local_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['database']['port'])" 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)
|
||||||
|
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
|
||||||
p = '$settings_file'
|
with open('$settings_file') as f:
|
||||||
s = yaml.safe_load(open(p)) or {}
|
s = yaml.safe_load(f) or {}
|
||||||
s.setdefault('logging', {})['debug_enabled'] = True
|
k = s.get('server', {}).get('ssh_key', '')
|
||||||
yaml.safe_dump(s, open(p, 'w'), default_flow_style=False, sort_keys=False)
|
if k and k != 'null':
|
||||||
" 2>/dev/null
|
print(k)
|
||||||
echo " Debug logging enabled for this run."
|
" 2>/dev/null)
|
||||||
echo ""
|
|
||||||
PRESERVE_DEBUG=1 start_dashboard
|
|
||||||
}
|
|
||||||
|
|
||||||
reset_to_factory() {
|
ssh_key=""
|
||||||
echo ""
|
key_paths=(
|
||||||
echo " Reset to Factory Defaults"
|
"$ssh_key_src"
|
||||||
echo ""
|
"$HOME/.ssh/dune-dashboard-key"
|
||||||
echo " WARNING: This will permanently delete the following:"
|
"$PROJECT_ROOT/internal-scripts/ssh/sshKey"
|
||||||
echo " - settings.yaml (all configuration)"
|
"/tmp/dune-tunnel-key"
|
||||||
echo " - logs/, app/logs/ (log files)"
|
"$HOME/.ssh/id_ed25519"
|
||||||
echo " - instance/ (local data)"
|
"$HOME/.ssh/id_rsa"
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
repair_game_database() {
|
for kp in "${key_paths[@]}"; do
|
||||||
echo ""
|
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
||||||
echo " Game Database Repair"
|
if ssh -i "$kp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes "${ssh_user}@${server_host}" "echo ok" &>/dev/null; then
|
||||||
echo " ====================="
|
ssh_key="$kp"
|
||||||
echo ""
|
echo " SSH Key: Found working key at $kp"
|
||||||
if ! load_server_settings; then
|
break
|
||||||
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 " No SSH keys found in any search location."
|
echo " [ERROR] No working SSH key found."
|
||||||
echo ""
|
|
||||||
read -rp " Press Enter to return..." || true
|
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
mkdir -p "$(dirname "$target_key")"
|
|
||||||
if [ "$newest" = "$target_key" ]; then
|
ssh_key_tmp="/tmp/dune-tunnel-key"
|
||||||
echo ""
|
cp "$ssh_key" "$ssh_key_tmp" 2>/dev/null
|
||||||
echo " The newest key is already at the target location."
|
chmod 600 "$ssh_key_tmp"
|
||||||
echo " No rotation needed."
|
|
||||||
else
|
|
||||||
cp "$newest" "$target_key"
|
|
||||||
chmod 600 "$target_key"
|
|
||||||
echo ""
|
|
||||||
echo " [OK] Synced newest key ($newest) to $target_key"
|
|
||||||
fi
|
|
||||||
echo ""
|
echo ""
|
||||||
read -rp " Press Enter to return..." || true
|
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
|
||||||
|
echo " [WARN] Backend may not have started yet"
|
||||||
|
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 " 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 ───────────────────────────────────────────────────────────
|
||||||
@@ -1044,20 +880,15 @@ show_banner
|
|||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
show_menu
|
show_menu
|
||||||
read -rp " Enter your choice: " choice || { echo ""; echo " Goodbye!"; echo ""; exit 0; }
|
read -rp " Enter your choice: " choice
|
||||||
|
|
||||||
case "$choice" in
|
case "$choice" in
|
||||||
1) start_dashboard ;;
|
1) start_dashboard ;;
|
||||||
2) run_setup ;;
|
2) run_setup ;;
|
||||||
3) run_diagnostics ;;
|
3) run_diagnostics ;;
|
||||||
4) start_dashboard_debug ;;
|
7) start_new_dashboard ;;
|
||||||
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-9 or Q."; echo "" ;;
|
*) echo ""; echo " Invalid choice. Please enter 1, 2, 3, 7, or Q."; echo "" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
|
|||||||
@@ -57,10 +57,10 @@
|
|||||||
{% for c in characters %}
|
{% for c in characters %}
|
||||||
<tr>
|
<tr>
|
||||||
<td><a href="/players/{{ c.id }}">{{ c.player_name or 'Unknown' }}</a></td>
|
<td><a href="/players/{{ c.id }}">{{ c.player_name or 'Unknown' }}</a></td>
|
||||||
<td>{% if c.online_status %}<span class="badge badge-{{ c.online_status.lower() }}">{{ c.online_status }}</span>{% else %}-{% endif %}</td>
|
<td>{% if c.online_status %}<span class="badge badge-{{ c.online_status.lower() }}">{{ c.online_status }}</span>{% else %}—{% endif %}</td>
|
||||||
<td>{{ c.id }}</td>
|
<td>{{ c.id }}</td>
|
||||||
<td>{{ c.map or 'N/A' }}</td>
|
<td>{{ c.map or 'N/A' }}</td>
|
||||||
<td>{% if c.faction_name %}<span class="badge badge-{{ c.faction_name.lower() }}">{{ c.faction_name }}</span>{% else %}-{% endif %}</td>
|
<td>{% if c.faction_name %}<span class="badge badge-{{ c.faction_name.lower() }}">{{ c.faction_name }}</span>{% else %}—{% endif %}</td>
|
||||||
<td style="font-size:11px;">{{ c.last_login_time.strftime('%Y-%m-%d %H:%M') if c.last_login_time else 'N/A' }}</td>
|
<td style="font-size:11px;">{{ c.last_login_time.strftime('%Y-%m-%d %H:%M') if c.last_login_time else 'N/A' }}</td>
|
||||||
<td style="font-size:10px;font-family:monospace;max-width:180px;word-break:break-all;">{{ c.transform_text or '' }}</td>
|
<td style="font-size:10px;font-family:monospace;max-width:180px;word-break:break-all;">{{ c.transform_text or '' }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -33,8 +33,8 @@
|
|||||||
{% for a in accounts %}
|
{% for a in accounts %}
|
||||||
<tr>
|
<tr>
|
||||||
<td><a href="/accounts/{{ a.id }}">{{ a.funcom_id or a.platform_name or 'Unknown' }}</a></td>
|
<td><a href="/accounts/{{ a.id }}">{{ a.funcom_id or a.platform_name or 'Unknown' }}</a></td>
|
||||||
<td>{{ a.character_name or '-' }}</td>
|
<td>{{ a.character_name or '—'|safe }}</td>
|
||||||
<td>{% if a.online_status %}<span class="badge badge-{{ a.online_status.lower() }}">{{ a.online_status }}</span>{% else %}-{% endif %}</td>
|
<td>{% if a.online_status %}<span class="badge badge-{{ a.online_status.lower() }}">{{ a.online_status }}</span>{% else %}—{% endif %}</td>
|
||||||
<td style="font-size:11px;font-family:monospace;">{{ a.user }}</td>
|
<td style="font-size:11px;font-family:monospace;">{{ a.user }}</td>
|
||||||
<td style="font-size:11px;">{{ a.platform_id or 'N/A' }}</td>
|
<td style="font-size:11px;">{{ a.platform_id or 'N/A' }}</td>
|
||||||
<td>{{ a.player_count }}</td>
|
<td>{{ a.player_count }}</td>
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+3
-11
@@ -9,21 +9,13 @@
|
|||||||
|
|
||||||
<div id="backup-status" class="error-banner" style="display:none;"></div>
|
<div id="backup-status" class="error-banner" style="display:none;"></div>
|
||||||
|
|
||||||
<div style="background:rgba(255,193,7,0.12);border:2px solid rgba(255,193,7,0.6);border-left:6px solid #ffc107;border-radius:8px;padding:14px 20px;margin-bottom:16px;">
|
|
||||||
<div style="font-size:14px;font-weight:700;color:#e8a317;margin-bottom:6px;">⚠ WIP - Use with caution</div>
|
|
||||||
<div style="font-size:13px;color:var(--text);line-height:1.5;">
|
|
||||||
This feature is still experimental. Test on a non-production environment first.
|
|
||||||
Keep offline backups of anything critical before using restore.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background:rgba(220,38,38,0.12);border:2px solid rgba(220,38,38,0.6);border-left:6px solid #dc2626;border-radius:8px;padding:16px 20px;margin-bottom:20px;">
|
<div style="background:rgba(220,38,38,0.12);border:2px solid rgba(220,38,38,0.6);border-left:6px solid #dc2626;border-radius:8px;padding:16px 20px;margin-bottom:20px;">
|
||||||
<div style="font-size:14px;font-weight:700;color:#ef4444;margin-bottom:8px;">⚠ SECURITY WARNING</div>
|
<div style="font-size:14px;font-weight:700;color:#ef4444;margin-bottom:8px;">⚠ SECURITY WARNING</div>
|
||||||
<div style="font-size:13px;color:var(--text);line-height:1.6;">
|
<div style="font-size:13px;color:var(--text);line-height:1.6;">
|
||||||
Backups contain <strong>sensitive information</strong> including database contents, K8s secrets, and server configuration.
|
Backups contain <strong>sensitive information</strong> including database contents, K8s secrets, and server configuration.
|
||||||
Store backup files in a <strong>secure, offline location</strong>. Use a password to encrypt backups containing private data.
|
Store backup files in a <strong>secure, offline location</strong>. Use a password to encrypt backups containing private data.
|
||||||
Do not share backup files or expose them in insecure storage.
|
Do not share backup files or expose them in insecure storage.
|
||||||
<strong style="color:#ef4444;display:block;margin-top:8px;">⚠ If you set a password, don't forget it - there's no way to recover it, and the backup will be locked for good.</strong>
|
<strong style="color:#ef4444;display:block;margin-top:8px;">⚠ If you set a password, never forget it — lost passwords cannot be recovered and the backup will be permanently unrecoverable.</strong>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -299,7 +291,7 @@
|
|||||||
<!-- Verify Backup Password Modal -->
|
<!-- Verify Backup Password Modal -->
|
||||||
<div id="verify-pw-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('verify-pw-modal')">
|
<div id="verify-pw-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('verify-pw-modal')">
|
||||||
<div class="modal" style="max-width:380px;">
|
<div class="modal" style="max-width:380px;">
|
||||||
<div class="modal-header"><h3>Verify Backup - <span id="verify-pw-label"></span></h3></div>
|
<div class="modal-header"><h3>Verify Backup — <span id="verify-pw-label"></span></h3></div>
|
||||||
<div class="modal-body" style="padding:20px;">
|
<div class="modal-body" style="padding:20px;">
|
||||||
<label style="display:block;font-size:13px;color:var(--text-light);">
|
<label style="display:block;font-size:13px;color:var(--text-light);">
|
||||||
Password
|
Password
|
||||||
@@ -706,7 +698,7 @@ async function startRestore() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!confirm('This will OVERWRITE ALL DATA on the configured server. Are you sure?')) return;
|
if (!confirm('This will OVERWRITE ALL DATA on the configured server. Are you sure?')) return;
|
||||||
if (!confirm('Last chance - are you absolutely sure you want to restore "' + name + '"?')) return;
|
if (!confirm('Last chance — are you absolutely sure you want to restore "' + name + '"?')) return;
|
||||||
|
|
||||||
const password = document.getElementById('restore-password').value;
|
const password = document.getElementById('restore-password').value;
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@
|
|||||||
<td>{{ e.actor_id }}</td>
|
<td>{{ e.actor_id }}</td>
|
||||||
<td>{{ e.map or '' }}</td>
|
<td>{{ e.map or '' }}</td>
|
||||||
<td>{{ e.event_type }}</td>
|
<td>{{ e.event_type }}</td>
|
||||||
<td>{% if e.actor_name %}{{ e.actor_name }}{% else %}-{% endif %}</td>
|
<td>{% if e.actor_name %}{{ e.actor_name }}{% else %}—{% endif %}</td>
|
||||||
<td style="font-size:11px;font-family:monospace;">{% if e.x %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}, {{ e.z|round(0)|int }}{% endif %}</td>
|
<td style="font-size:11px;font-family:monospace;">{% if e.x %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}, {{ e.z|round(0)|int }}{% endif %}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
|
|||||||
+6
-28
@@ -125,37 +125,15 @@ function formatSize(s) {
|
|||||||
return sz.toFixed(i===0?0:1) + ' ' + u[i];
|
return sz.toFixed(i===0?0:1) + ' ' + u[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
function escHtml(s) {
|
|
||||||
return String(s == null ? '' : s)
|
|
||||||
.replace(/&/g, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, ''');
|
|
||||||
}
|
|
||||||
|
|
||||||
function escAttr(s) {
|
|
||||||
// For values inside double-quoted onclick="..." JS single-quoted strings.
|
|
||||||
// The existing backslash/quote escaping is kept for JS; HTML-significant
|
|
||||||
// chars are entity-encoded (the browser decodes them before JS runs,
|
|
||||||
// so the actual values are unchanged).
|
|
||||||
return String(s == null ? '' : s)
|
|
||||||
.replace(/&/g, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"');
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderBreadcrumb(path) {
|
function renderBreadcrumb(path) {
|
||||||
const p = path.split('/').filter(Boolean);
|
const p = path.split('/').filter(Boolean);
|
||||||
let h = '<span onclick="loadFiles(\'/\')">📁 /</span>';
|
let h = '<span onclick="loadFiles(\'/\')">📁 /</span>';
|
||||||
let b = '';
|
let b = '';
|
||||||
for (let i=0;i<p.length;i++) {
|
for (let i=0;i<p.length;i++) {
|
||||||
b += '/'+p[i];
|
b += '/'+p[i];
|
||||||
const seg = escHtml(p[i]);
|
|
||||||
h += i===p.length-1
|
h += i===p.length-1
|
||||||
? '<span class="sep">/</span><span class="current">'+seg+'</span>'
|
? '<span class="sep">/</span><span class="current">'+p[i]+'</span>'
|
||||||
: '<span class="sep">/</span><span onclick="loadFiles(\''+escAttr(b.replace(/'/g,"\\'"))+'\')">'+seg+'</span>';
|
: '<span class="sep">/</span><span onclick="loadFiles(\''+b.replace(/'/g,"\\'")+'\')">'+p[i]+'</span>';
|
||||||
}
|
}
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
@@ -178,14 +156,14 @@ async function loadFiles(path) {
|
|||||||
let h = '';
|
let h = '';
|
||||||
for (const x of files) {
|
for (const x of files) {
|
||||||
const fp = (path==='/'?'':path)+'/'+x.name;
|
const fp = (path==='/'?'':path)+'/'+x.name;
|
||||||
const sp = escAttr(fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'"));
|
const sp = fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||||
const sn = escAttr(x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'"));
|
const sn = x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||||
const icon = x.is_dir ? '📁' : getIcon(x.name);
|
const icon = x.is_dir ? '📁' : getIcon(x.name);
|
||||||
const action = x.is_dir ? `loadFiles('${sp}')` : `openFile('${sp}','${sn}')`;
|
const action = x.is_dir ? `loadFiles('${sp}')` : `openFile('${sp}','${sn}')`;
|
||||||
h += `<div class="fm-item" onclick="${action}">
|
h += `<div class="fm-item" onclick="${action}">
|
||||||
<span class="fm-icon ${x.is_dir?'dir':''}">${icon}</span>
|
<span class="fm-icon ${x.is_dir?'dir':''}">${icon}</span>
|
||||||
<span class="fm-fname ${x.is_dir?'dir':''}">${escHtml(x.name)}</span>
|
<span class="fm-fname ${x.is_dir?'dir':''}">${x.name}</span>
|
||||||
<span class="fm-fsize">${escHtml(formatSize(x.size))}</span>
|
<span class="fm-fsize">${formatSize(x.size)}</span>
|
||||||
<button class="fm-delete-btn" onclick="event.stopPropagation();deleteFile('${sp}','${sn}')" title="Delete">🗑</button>
|
<button class="fm-delete-btn" onclick="event.stopPropagation();deleteFile('${sp}','${sn}')" title="Delete">🗑</button>
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@
|
|||||||
<td>{% if g.faction_name %}<span class="badge badge-{{ g.faction_name.lower() }}">{{ g.faction_name }}</span>{% else %}<span class="badge badge-neutral">Neutral</span>{% endif %}</td>
|
<td>{% if g.faction_name %}<span class="badge badge-{{ g.faction_name.lower() }}">{{ g.faction_name }}</span>{% else %}<span class="badge badge-neutral">Neutral</span>{% endif %}</td>
|
||||||
<td>{{ g.member_count }}</td>
|
<td>{{ g.member_count }}</td>
|
||||||
<td>{% if g.online_count %}{{ g.online_count }}{% else %}0{% endif %}</td>
|
<td>{% if g.online_count %}{{ g.online_count }}{% else %}0{% endif %}</td>
|
||||||
<td style="font-size:12px;color:var(--text-light);">{% if g.guild_description %}{{ g.guild_description[:80] }}{% if g.guild_description|length > 80 %}...{% endif %}{% else %}-{% endif %}</td>
|
<td style="font-size:12px;color:var(--text-light);">{% if g.guild_description %}{{ g.guild_description[:80] }}{% if g.guild_description|length > 80 %}...{% endif %}{% else %}—{% endif %}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr><td colspan="5" style="text-align:center;padding:20px;color:var(--text-light);">No guilds found</td></tr>
|
<tr><td colspan="5" style="text-align:center;padding:20px;color:var(--text-light);">No guilds found</td></tr>
|
||||||
|
|||||||
+4
-1
@@ -63,9 +63,12 @@
|
|||||||
<div class="map-summary-item"><strong id="summary-bases">0</strong><span>Bases</span></div>
|
<div class="map-summary-item"><strong id="summary-bases">0</strong><span>Bases</span></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="map-notice">
|
||||||
|
⚠ This page is still a work in progress - expect bugs and quirks. Base ownership names are inferred heuristically and may be inaccurate.
|
||||||
|
</div>
|
||||||
<div class="map-layout">
|
<div class="map-layout">
|
||||||
<div id="map-container">
|
<div id="map-container">
|
||||||
<div class="map-credit">Map images from <a href="https://awakening.wiki/" target="_blank" rel="noopener">awakening.wiki</a> - big thanks to them for mapping out Arrakis!</div>
|
<div class="map-credit">Map images sourced from <a href="https://awakening.wiki/" target="_blank" rel="noopener">awakening.wiki</a> — a massive thank you for their incredible work mapping Arrakis!</div>
|
||||||
</div>
|
</div>
|
||||||
<aside class="map-panel">
|
<aside class="map-panel">
|
||||||
<section class="panel-section">
|
<section class="panel-section">
|
||||||
|
|||||||
@@ -60,7 +60,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if is_online %}
|
{% if is_online %}
|
||||||
<div style="width:100%;font-size:11px;color:#e67e22;margin-top:4px;">Player is online - edit vitals only when offline. Health data is currently WIP.</div>
|
<div style="width:100%;font-size:11px;color:#e67e22;margin-top:4px;">Player is online — edit vitals only when offline. Health data is currently WIP.</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -162,11 +162,11 @@
|
|||||||
<div style="font-size:10px;color:var(--text-muted);padding:4px 8px;">Note: Currency values may be stale due to game server behavior</div>
|
<div style="font-size:10px;color:var(--text-muted);padding:4px 8px;">Note: Currency values may be stale due to game server behavior</div>
|
||||||
</div>
|
</div>
|
||||||
{% if is_online %}
|
{% if is_online %}
|
||||||
<div style="font-size:12px;color:#e67e22;padding:8px 16px;">Player is online - editing is disabled. Log out first.</div>
|
<div style="font-size:12px;color:#e67e22;padding:8px 16px;">Player is online — editing disabled. Log out first.</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<button onclick="openCurrenciesModal()" class="btn-edit" style="margin:8px 16px;">Edit</button>
|
<button onclick="openCurrenciesModal()" class="btn-edit" style="margin:8px 16px;">Edit</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div style="font-size:11px;color:var(--text-muted);padding:4px 16px 8px;">Read-only. Balances are from the last game save - the game server applies its own changes on top of these values.</div>
|
<div style="font-size:11px;color:var(--text-muted);padding:4px 16px 8px;">Read-only. Balances reflect last game save — game server writes deltas on top of DB value.</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -186,7 +186,7 @@
|
|||||||
<tr><td>{{ s.track_type }}</td><td>{{ s.xp_amount | format_number }}</td><td>{{ s.level }}</td></tr>
|
<tr><td>{{ s.track_type }}</td><td>{{ s.xp_amount | format_number }}</td><td>{{ s.level }}</td></tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if tech_knowledge is not none %}
|
{% if tech_knowledge is not none %}
|
||||||
<tr><td>Tech Knowledge Points</td><td>{{ tech_knowledge | format_number }}</td><td>-</td></tr>
|
<tr><td>Tech Knowledge Points</td><td>{{ tech_knowledge | format_number }}</td><td>—</td></tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -289,11 +289,11 @@
|
|||||||
<div class="detail-section">
|
<div class="detail-section">
|
||||||
<h2>Inventory</h2>
|
<h2>Inventory</h2>
|
||||||
{% if is_online %}
|
{% if is_online %}
|
||||||
<div style="font-size:12px;color:#e67e22;padding:0 16px 8px;">Player is online - editing is disabled. Log out first.</div>
|
<div style="font-size:12px;color:#e67e22;padding:0 16px 8px;">Player is online — editing disabled. Log out first.</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div class="experimental-banner">
|
<div class="experimental-banner">
|
||||||
<span class="banner-icon">⚠</span>
|
<span class="banner-icon">⚠</span>
|
||||||
<span class="banner-text">Inventory editing is still experimental and items might not save properly. Double-check your changes in-game. <strong>Use with caution</strong>.</span>
|
<span class="banner-text">Inventory editing is still being forged in the deep desert. Items may not persist, or the sandworm may eat your edits. <strong>Use with caution</strong> — the spice must flow, but bugs may flow with it.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
@@ -642,7 +642,7 @@
|
|||||||
<form onsubmit="return submitEdit(this, '/api/edit_xp')">
|
<form onsubmit="return submitEdit(this, '/api/edit_xp')">
|
||||||
<input type="hidden" name="player_id" value="{{ player.player_controller_id or '' }}">
|
<input type="hidden" name="player_id" value="{{ player.player_controller_id or '' }}">
|
||||||
<input type="hidden" name="track_type" value="{{ s.track_type }}">
|
<input type="hidden" name="track_type" value="{{ s.track_type }}">
|
||||||
<label>{{ s.track_type }} - XP: <input type="number" name="xp_amount" value="{{ s.xp_amount }}" style="width:100px;">
|
<label>{{ s.track_type }} — XP: <input type="number" name="xp_amount" value="{{ s.xp_amount }}" style="width:100px;">
|
||||||
Level: <input type="number" step="0.1" name="level" value="{{ s.level }}" style="width:80px;">
|
Level: <input type="number" step="0.1" name="level" value="{{ s.level }}" style="width:80px;">
|
||||||
</label>
|
</label>
|
||||||
<button type="submit" class="btn-save" style="font-size:11px;padding:2px 8px;">Save</button>
|
<button type="submit" class="btn-save" style="font-size:11px;padding:2px 8px;">Save</button>
|
||||||
|
|||||||
@@ -70,10 +70,10 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<td><a href="/players/{{ p.id }}">{{ p.player_name or 'Unknown' }}</a></td>
|
<td><a href="/players/{{ p.id }}">{{ p.player_name or 'Unknown' }}</a></td>
|
||||||
<td>{% if p.online_status %}<span class="badge badge-{{ p.online_status.lower() }}">{{ p.online_status }}</span>{% else %}<span class="badge badge-offline">Unknown</span>{% endif %}</td>
|
<td>{% if p.online_status %}<span class="badge badge-{{ p.online_status.lower() }}">{{ p.online_status }}</span>{% else %}<span class="badge badge-offline">Unknown</span>{% endif %}</td>
|
||||||
<td>{% if p.faction_name %}<span class="badge badge-{{ p.faction_name.lower() }}">{{ p.faction_name }}</span>{% else %}-{% endif %}</td>
|
<td>{% if p.faction_name %}<span class="badge badge-{{ p.faction_name.lower() }}">{{ p.faction_name }}</span>{% else %}—{% endif %}</td>
|
||||||
<td>{% if p.guild_name %}{{ p.guild_name }}{% else %}-{% endif %}</td>
|
<td>{% if p.guild_name %}{{ p.guild_name }}{% else %}—{% endif %}</td>
|
||||||
<td>{{ p.map or '-' }}</td>
|
<td>{{ p.map or '—'|safe }}</td>
|
||||||
<td style="font-size:12px;">{% if p.player_controller_id %}<span class="ip-cell" data-id="{{ p.player_controller_id }}" data-ip="{{ p.ip_address or '' }}">{{ p.ip_address or '-' }}</span>{% else %}-{% endif %}</td>
|
<td style="font-size:12px;">{% if p.player_controller_id %}<span class="ip-cell" data-id="{{ p.player_controller_id }}" data-ip="{{ p.ip_address or '' }}">{{ p.ip_address or '—' }}</span>{% else %}—{% endif %}</td>
|
||||||
<td style="font-size:12px;">{{ p.funcom_id or p.account_email }}</td>
|
<td style="font-size:12px;">{{ p.funcom_id or p.account_email }}</td>
|
||||||
<td>{{ p.vehicle_count }}</td>
|
<td>{{ p.vehicle_count }}</td>
|
||||||
<td>{{ p.building_count }}</td>
|
<td>{{ p.building_count }}</td>
|
||||||
@@ -228,7 +228,7 @@ document.querySelectorAll('.ip-cell').forEach(cell => {
|
|||||||
const resp = await csrfFetch('/api/set_player_ip', { method: 'POST', body: form });
|
const resp = await csrfFetch('/api/set_player_ip', { method: 'POST', body: form });
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.textContent = newIp || '-';
|
this.textContent = newIp || '—';
|
||||||
this.dataset.ip = newIp;
|
this.dataset.ip = newIp;
|
||||||
alert('IP updated!');
|
alert('IP updated!');
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+53
-893
File diff suppressed because it is too large.
Load diff
@@ -72,7 +72,7 @@
|
|||||||
<!-- Pod Logs Modal -->
|
<!-- Pod Logs Modal -->
|
||||||
<div id="logs-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('logs-modal')">
|
<div id="logs-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('logs-modal')">
|
||||||
<div class="modal" style="max-width:900px;">
|
<div class="modal" style="max-width:900px;">
|
||||||
<div class="modal-header"><h3>Pod Logs - <span id="logs-pod-name"></span></h3></div>
|
<div class="modal-header"><h3>Pod Logs — <span id="logs-pod-name"></span></h3></div>
|
||||||
<div id="logs-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading logs...</div>
|
<div id="logs-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading logs...</div>
|
||||||
<pre id="logs-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
|
<pre id="logs-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||||
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
<!-- Pod Describe Modal -->
|
<!-- Pod Describe Modal -->
|
||||||
<div id="describe-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('describe-modal')">
|
<div id="describe-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('describe-modal')">
|
||||||
<div class="modal" style="max-width:900px;">
|
<div class="modal" style="max-width:900px;">
|
||||||
<div class="modal-header"><h3>Describe Pod - <span id="describe-pod-name"></span></h3></div>
|
<div class="modal-header"><h3>Describe Pod — <span id="describe-pod-name"></span></h3></div>
|
||||||
<div id="describe-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading...</div>
|
<div id="describe-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading...</div>
|
||||||
<pre id="describe-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
|
<pre id="describe-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||||
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
@@ -116,10 +116,7 @@
|
|||||||
<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>
|
||||||
// Polling only: the server runs in threading mode, which has no true
|
const socket = io();
|
||||||
// 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;
|
||||||
@@ -327,7 +324,7 @@ function promptDeletePod(name, safe) {
|
|||||||
const btn = document.getElementById('delete-confirm-btn');
|
const btn = document.getElementById('delete-confirm-btn');
|
||||||
if (safe) {
|
if (safe) {
|
||||||
title.textContent = 'Delete DB Backup Pod';
|
title.textContent = 'Delete DB Backup Pod';
|
||||||
msg.innerHTML = 'This pod stores database backups. It is <strong>safe to delete</strong> - Kubernetes will recreate it on its own. Continue?';
|
msg.innerHTML = 'This pod stores database backups. It is <strong>safe to delete</strong> — Kubernetes will recreate it automatically. Continue?';
|
||||||
btn.className = 'btn-edit';
|
btn.className = 'btn-edit';
|
||||||
btn.textContent = 'Delete Backup Pod';
|
btn.textContent = 'Delete Backup Pod';
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -53,8 +53,8 @@
|
|||||||
<td><a href="/vehicles/{{ v.id }}">{{ v.id }}</a></td>
|
<td><a href="/vehicles/{{ v.id }}">{{ v.id }}</a></td>
|
||||||
<td style="font-size:12px;">{{ v.class | class_name }}</td>
|
<td style="font-size:12px;">{{ v.class | class_name }}</td>
|
||||||
<td>{{ v.actor_name or 'N/A' }}</td>
|
<td>{{ v.actor_name or 'N/A' }}</td>
|
||||||
<td>{% if v.owner_name %}<a href="/players/{{ v.owner_pawn_id }}" style="font-weight:500;">{{ v.owner_name }}</a>{% else %}-{% endif %}</td>
|
<td>{% if v.owner_name %}<a href="/players/{{ v.owner_pawn_id }}" style="font-weight:500;">{{ v.owner_name }}</a>{% else %}—{% endif %}</td>
|
||||||
<td>{% if v.pilot_name %}<span class="badge badge-online">Active</span> <a href="/players/{{ v.pilot_pawn_id }}">{{ v.pilot_name }}</a>{% else %}-{% endif %}</td>
|
<td>{% if v.pilot_name %}<span class="badge badge-online">Active</span> <a href="/players/{{ v.pilot_pawn_id }}">{{ v.pilot_name }}</a>{% else %}—{% endif %}</td>
|
||||||
<td>{{ v.map or 'N/A' }}</td>
|
<td>{{ v.map or 'N/A' }}</td>
|
||||||
<td style="font-size:11px;font-family:monospace;max-width:250px;word-break:break-all;">{{ v.transform_text or '' }}</td>
|
<td style="font-size:11px;font-family:monospace;max-width:250px;word-break:break-all;">{{ v.transform_text or '' }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
"""Tests for the battlegroup update guard (block while game pods run)."""
|
|
||||||
|
|
||||||
from app.services.k8s import K8sService
|
|
||||||
|
|
||||||
NS = 'funcom-seabass-sh-b17a5f036d1f7882-ccdijf'
|
|
||||||
|
|
||||||
|
|
||||||
class FakeSSH:
|
|
||||||
def __init__(self, out='', rc=0):
|
|
||||||
self.out = out
|
|
||||||
self.rc = rc
|
|
||||||
self.commands = []
|
|
||||||
|
|
||||||
def run(self, command, timeout=30, quiet=False):
|
|
||||||
self.commands.append(command)
|
|
||||||
return self.out, '', self.rc
|
|
||||||
|
|
||||||
|
|
||||||
def make_k8s(out='', rc=0):
|
|
||||||
return K8sService(ssh_service=FakeSSH(out, rc), namespace=NS)
|
|
||||||
|
|
||||||
|
|
||||||
class TestRunningGamePods:
|
|
||||||
def test_detects_running_game_pods(self):
|
|
||||||
out = (
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-sg-overmap-pod-2 Running\n'
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-sg-survival-1-pod-1 Running\n'
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-bgd-deploy-xxx Running\n'
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-mq-game-sts-0 Running\n'
|
|
||||||
)
|
|
||||||
running = make_k8s(out).get_running_game_pods()
|
|
||||||
# Only sg-*-pod-* count as game servers; infra pods do not block.
|
|
||||||
assert running == [
|
|
||||||
'sh-b17a5f036d1f7882-ccdijf-sg-overmap-pod-2',
|
|
||||||
'sh-b17a5f036d1f7882-ccdijf-sg-survival-1-pod-1',
|
|
||||||
]
|
|
||||||
|
|
||||||
def test_empty_when_no_game_pods_running(self):
|
|
||||||
out = (
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-bgd-deploy-xxx Running\n'
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-sg-overmap-pod-2 Completed\n'
|
|
||||||
f'sh-b17a5f036d1f7882-ccdijf-mq-game-sts-0 Running\n'
|
|
||||||
)
|
|
||||||
assert make_k8s(out).get_running_game_pods() == []
|
|
||||||
|
|
||||||
def test_empty_when_no_pods(self):
|
|
||||||
assert make_k8s('').get_running_game_pods() == []
|
|
||||||
|
|
||||||
def test_none_when_status_unknown(self):
|
|
||||||
assert make_k8s('', rc=1).get_running_game_pods() is None
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
"""Tests for graceful shutdown/restart lifecycle service."""
|
|
||||||
|
|
||||||
import time
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.services.lifecycle import (
|
|
||||||
COUNTDOWN_MARKS,
|
|
||||||
FINAL_DURATION,
|
|
||||||
LifecycleService,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class FakeSSH:
|
|
||||||
def __init__(self):
|
|
||||||
self.commands = []
|
|
||||||
|
|
||||||
def run(self, command, timeout=30, quiet=False):
|
|
||||||
self.commands.append(command)
|
|
||||||
return ('ok', '', 0)
|
|
||||||
|
|
||||||
|
|
||||||
class FakeAdmin:
|
|
||||||
def __init__(self):
|
|
||||||
self.broadcasts = []
|
|
||||||
|
|
||||||
def send_global_broadcast(self, title, message, duration=30):
|
|
||||||
self.broadcasts.append((title, message, duration))
|
|
||||||
return True, 'sent'
|
|
||||||
|
|
||||||
|
|
||||||
def make_service(tmp_path):
|
|
||||||
ssh = FakeSSH()
|
|
||||||
admin = FakeAdmin()
|
|
||||||
svc = LifecycleService(
|
|
||||||
ssh, admin,
|
|
||||||
{'kubernetes': {'battlegroup_script': '/home/dune/.dune/bin/battlegroup'}},
|
|
||||||
state_dir=str(tmp_path),
|
|
||||||
)
|
|
||||||
return svc, ssh, admin
|
|
||||||
|
|
||||||
|
|
||||||
class TestCountdownTable:
|
|
||||||
def test_marks_match_spec(self):
|
|
||||||
"""15m..30s last 10s, 10s lasts 5s, final lasts 10s."""
|
|
||||||
assert [(s, d) for s, _, d in COUNTDOWN_MARKS] == [
|
|
||||||
(900, 10), (600, 10), (300, 10), (180, 10),
|
|
||||||
(120, 10), (60, 10), (30, 10), (10, 5),
|
|
||||||
]
|
|
||||||
assert FINAL_DURATION == 10
|
|
||||||
|
|
||||||
def test_manual_messages(self):
|
|
||||||
title, msg = LifecycleService._message_for(
|
|
||||||
'restart', '5 minutes', 10, False, '', final=False)
|
|
||||||
assert 'restart' in title.lower()
|
|
||||||
assert '5 minutes' in msg
|
|
||||||
title, msg = LifecycleService._message_for(
|
|
||||||
'shutdown', '30 seconds', 10, False, '', final=False)
|
|
||||||
assert 'shut' in msg.lower()
|
|
||||||
|
|
||||||
def test_scheduled_messages_mention_schedule(self):
|
|
||||||
title, msg = LifecycleService._message_for(
|
|
||||||
'restart', '5 minutes', 10, True, 'daily 05:00', final=False)
|
|
||||||
assert 'Scheduled' in title
|
|
||||||
assert 'daily 05:00' in msg
|
|
||||||
|
|
||||||
|
|
||||||
class TestActiveJob:
|
|
||||||
def test_start_and_cancel(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
try:
|
|
||||||
result = svc.start_restart(reason='manual')
|
|
||||||
assert result['success']
|
|
||||||
assert svc.status()['active'] is True
|
|
||||||
assert svc.status()['kind'] == 'restart'
|
|
||||||
# Second job must be rejected while one is active.
|
|
||||||
again = svc.start_shutdown()
|
|
||||||
assert not again['success']
|
|
||||||
finally:
|
|
||||||
cancelled = svc.cancel()
|
|
||||||
assert cancelled['success']
|
|
||||||
assert svc.status()['active'] is False
|
|
||||||
|
|
||||||
def test_cancel_without_active(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
assert not svc.cancel()['success']
|
|
||||||
|
|
||||||
def test_first_notice_sent_immediately(self, tmp_path):
|
|
||||||
"""The 15-minute notice is due at job start: it must be sent, not skipped."""
|
|
||||||
svc, _, admin = make_service(tmp_path)
|
|
||||||
try:
|
|
||||||
assert svc.start_restart(reason='manual')['success']
|
|
||||||
deadline = time.time() + 10
|
|
||||||
while time.time() < deadline and not admin.broadcasts:
|
|
||||||
time.sleep(0.2)
|
|
||||||
assert admin.broadcasts, 'expected the 15-minute notice right after start'
|
|
||||||
title, message, duration = admin.broadcasts[0]
|
|
||||||
assert '15 minutes' in message and duration == 10
|
|
||||||
finally:
|
|
||||||
svc.cancel()
|
|
||||||
|
|
||||||
def test_cancel_sends_ingame_notice(self, tmp_path):
|
|
||||||
svc, _, admin = make_service(tmp_path)
|
|
||||||
assert svc.start_shutdown(reason='manual')['success']
|
|
||||||
deadline = time.time() + 10
|
|
||||||
while time.time() < deadline and not admin.broadcasts:
|
|
||||||
time.sleep(0.2)
|
|
||||||
result = svc.cancel()
|
|
||||||
assert result['success']
|
|
||||||
assert result['notice_sent'] is True
|
|
||||||
assert any('called off' in msg.lower() for _, msg, _ in admin.broadcasts)
|
|
||||||
|
|
||||||
def test_short_countdown_runs_to_execute(self, tmp_path):
|
|
||||||
"""12s countdown: stale marks skipped, late marks sent, action executed."""
|
|
||||||
import time as _time
|
|
||||||
svc, ssh, admin = make_service(tmp_path)
|
|
||||||
action_at = _time.time() + 12
|
|
||||||
assert svc.start_restart_at(action_at, reason='manual')['success']
|
|
||||||
deadline = _time.time() + 40
|
|
||||||
while _time.time() < deadline and svc.status().get('active', False):
|
|
||||||
_time.sleep(0.5)
|
|
||||||
assert not svc.status().get('active', False)
|
|
||||||
assert any('battlegroup' in cmd and 'restart' in cmd for cmd in ssh.commands)
|
|
||||||
assert any('restarting now' in msg.lower() for _, msg, _ in admin.broadcasts)
|
|
||||||
|
|
||||||
|
|
||||||
class TestScheduleCalc:
|
|
||||||
def test_daily_next_run(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
now = datetime(2026, 9, 21, 4, 0, 0) # Monday
|
|
||||||
cfg = {'mode': 'daily', 'daily_times': ['05:00']}
|
|
||||||
assert svc.compute_next_run(cfg, now) == '2026-09-21T05:00:00'
|
|
||||||
|
|
||||||
def test_daily_rolls_to_tomorrow(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
now = datetime(2026, 9, 21, 6, 0, 0)
|
|
||||||
cfg = {'mode': 'daily', 'daily_times': ['05:00']}
|
|
||||||
assert svc.compute_next_run(cfg, now) == '2026-09-22T05:00:00'
|
|
||||||
|
|
||||||
def test_weekly_next_run(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
now = datetime(2026, 9, 21, 4, 0, 0) # Monday (weekday 0)
|
|
||||||
cfg = {'mode': 'weekly', 'weekly_days': [6], 'weekly_times': ['05:00']}
|
|
||||||
nxt = datetime.fromisoformat(svc.compute_next_run(cfg, now))
|
|
||||||
assert nxt.weekday() == 6
|
|
||||||
assert (nxt.hour, nxt.minute) == (5, 0)
|
|
||||||
|
|
||||||
def test_monthly_next_run(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
now = datetime(2026, 9, 21, 6, 0, 0)
|
|
||||||
cfg = {'mode': 'monthly', 'monthly_days': [1], 'monthly_time': '05:00'}
|
|
||||||
nxt = datetime.fromisoformat(svc.compute_next_run(cfg, now))
|
|
||||||
assert (nxt.month, nxt.day, nxt.hour) == (10, 1, 5)
|
|
||||||
|
|
||||||
def test_once_future_and_past(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
now = datetime(2026, 9, 21, 4, 0, 0)
|
|
||||||
future = (now + timedelta(hours=2)).isoformat()
|
|
||||||
assert svc.compute_next_run({'mode': 'once', 'once_at': future}, now) == future
|
|
||||||
past = (now - timedelta(hours=1)).isoformat()
|
|
||||||
assert svc.compute_next_run({'mode': 'once', 'once_at': past}, now) == ''
|
|
||||||
|
|
||||||
def test_update_schedule_rejects_bad_mode(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.update_schedule({'mode': 'yearly'})
|
|
||||||
|
|
||||||
def test_disable_preserves_settings(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
svc.update_schedule({'enabled': True, 'mode': 'daily',
|
|
||||||
'daily_times': ['06:00']})
|
|
||||||
cfg = svc.set_enabled(False)
|
|
||||||
assert cfg['enabled'] is False
|
|
||||||
assert cfg['daily_times'] == ['06:00']
|
|
||||||
assert cfg['mode'] == 'daily'
|
|
||||||
cfg = svc.set_enabled(True)
|
|
||||||
assert cfg['enabled'] is True
|
|
||||||
assert cfg['daily_times'] == ['06:00']
|
|
||||||
|
|
||||||
def test_clear_disarms_but_keeps_settings(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
svc.update_schedule({'enabled': True, 'mode': 'weekly',
|
|
||||||
'weekly_days': [1, 3],
|
|
||||||
'weekly_times': ['07:00']})
|
|
||||||
cfg = svc.clear_schedule()
|
|
||||||
assert cfg['enabled'] is False
|
|
||||||
assert cfg['next_run'] == ''
|
|
||||||
assert cfg['mode'] == 'weekly'
|
|
||||||
assert cfg['weekly_days'] == [1, 3]
|
|
||||||
assert cfg['weekly_times'] == ['07:00']
|
|
||||||
|
|
||||||
def test_once_accepts_utc_and_local_strings(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
now = datetime.now().replace(second=0, microsecond=0)
|
|
||||||
future_local = (now + timedelta(hours=2)).replace(microsecond=0)
|
|
||||||
assert svc.compute_next_run(
|
|
||||||
{'mode': 'once', 'once_at': future_local.isoformat()}, now) != ''
|
|
||||||
future_utc = future_local.strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
assert svc.compute_next_run(
|
|
||||||
{'mode': 'once', 'once_at': future_utc}, now) != ''
|
|
||||||
|
|
||||||
|
|
||||||
class TestSchedulerFire:
|
|
||||||
def test_fire_inside_window_starts_countdown(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
try:
|
|
||||||
action_at = (datetime.now() + timedelta(minutes=10)).replace(
|
|
||||||
second=0, microsecond=0)
|
|
||||||
svc.update_schedule({
|
|
||||||
'enabled': True, 'mode': 'once',
|
|
||||||
'once_at': action_at.isoformat(),
|
|
||||||
})
|
|
||||||
result = svc.check_and_fire()
|
|
||||||
assert result and result['success']
|
|
||||||
assert svc.status()['active'] is True
|
|
||||||
assert svc.status()['reason'] == 'scheduled'
|
|
||||||
# Second tick must not double-fire the same occurrence.
|
|
||||||
assert svc.check_and_fire() is None
|
|
||||||
finally:
|
|
||||||
svc.cancel()
|
|
||||||
|
|
||||||
def test_no_fire_outside_window(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
action_at = datetime.now() + timedelta(hours=5)
|
|
||||||
svc.update_schedule({
|
|
||||||
'enabled': True, 'mode': 'once',
|
|
||||||
'once_at': action_at.replace(second=0, microsecond=0).isoformat(),
|
|
||||||
})
|
|
||||||
assert svc.check_and_fire() is None
|
|
||||||
assert svc.status()['active'] is False
|
|
||||||
|
|
||||||
def test_disabled_schedule_never_fires(self, tmp_path):
|
|
||||||
svc, _, _ = make_service(tmp_path)
|
|
||||||
action_at = datetime.now() + timedelta(minutes=5)
|
|
||||||
svc.update_schedule({
|
|
||||||
'enabled': False, 'mode': 'once',
|
|
||||||
'once_at': action_at.replace(second=0, microsecond=0).isoformat(),
|
|
||||||
})
|
|
||||||
assert svc.check_and_fire() is None
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
"""Tests for scheduled custom notifications."""
|
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.services.scheduled_broadcast import ScheduledBroadcastService
|
|
||||||
|
|
||||||
|
|
||||||
class FakeAdmin:
|
|
||||||
def __init__(self):
|
|
||||||
self.broadcasts = []
|
|
||||||
|
|
||||||
def send_global_broadcast(self, title, message, duration=30):
|
|
||||||
self.broadcasts.append((title, message, duration))
|
|
||||||
return True, 'sent'
|
|
||||||
|
|
||||||
|
|
||||||
def make_service(tmp_path):
|
|
||||||
admin = FakeAdmin()
|
|
||||||
svc = ScheduledBroadcastService(admin, state_dir=str(tmp_path))
|
|
||||||
return svc, admin
|
|
||||||
|
|
||||||
|
|
||||||
def base_entry(**overrides):
|
|
||||||
entry = {
|
|
||||||
'title': 'Notice',
|
|
||||||
'message': 'Hello players',
|
|
||||||
'duration': 30,
|
|
||||||
'mode': 'daily',
|
|
||||||
'daily_times': ['12:00'],
|
|
||||||
}
|
|
||||||
entry.update(overrides)
|
|
||||||
return entry
|
|
||||||
|
|
||||||
|
|
||||||
class TestEntryCrud:
|
|
||||||
def test_save_and_list(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
entry = svc.save_entry(base_entry())
|
|
||||||
assert entry['id']
|
|
||||||
assert entry['next_run']
|
|
||||||
assert [e['id'] for e in svc.list_entries()] == [entry['id']]
|
|
||||||
|
|
||||||
def test_requires_title_and_message(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.save_entry(base_entry(title=''))
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.save_entry(base_entry(message=''))
|
|
||||||
|
|
||||||
def test_duration_clamped(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
assert svc.save_entry(base_entry(duration=999))['duration'] == 300
|
|
||||||
assert svc.save_entry(base_entry(duration=1))['duration'] == 5
|
|
||||||
|
|
||||||
def test_rejects_bad_mode(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.save_entry(base_entry(mode='yearly'))
|
|
||||||
|
|
||||||
def test_delete(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
entry = svc.save_entry(base_entry())
|
|
||||||
assert svc.delete_entry(entry['id']) is True
|
|
||||||
assert svc.list_entries() == []
|
|
||||||
assert svc.delete_entry(entry['id']) is False
|
|
||||||
|
|
||||||
def test_enable_disable_preserves_settings(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
entry = svc.save_entry(base_entry(daily_times=['06:00', '18:00']))
|
|
||||||
disabled = svc.set_enabled(entry['id'], False)
|
|
||||||
assert disabled['enabled'] is False
|
|
||||||
assert disabled['daily_times'] == ['06:00', '18:00']
|
|
||||||
assert disabled['title'] == 'Notice'
|
|
||||||
assert disabled['message'] == 'Hello players'
|
|
||||||
enabled = svc.set_enabled(entry['id'], True)
|
|
||||||
assert enabled['enabled'] is True
|
|
||||||
assert enabled['daily_times'] == ['06:00', '18:00']
|
|
||||||
|
|
||||||
|
|
||||||
class TestFiring:
|
|
||||||
def test_daily_fires_at_time(self, tmp_path):
|
|
||||||
svc, admin = make_service(tmp_path)
|
|
||||||
target = (datetime.now() + timedelta(minutes=1)).replace(second=0, microsecond=0)
|
|
||||||
entry = svc.save_entry(base_entry(
|
|
||||||
daily_times=[target.strftime('%H:%M')]))
|
|
||||||
assert entry['next_run'] != ''
|
|
||||||
fired = svc.check_and_fire(target + timedelta(seconds=5))
|
|
||||||
assert len(fired) == 1
|
|
||||||
assert admin.broadcasts and admin.broadcasts[0][:2] == ('Notice', 'Hello players')
|
|
||||||
# Must not fire twice for the same occurrence.
|
|
||||||
assert svc.check_and_fire(target + timedelta(seconds=10)) == []
|
|
||||||
# ... but the next occurrence is armed.
|
|
||||||
updated = svc.list_entries()[0]
|
|
||||||
assert updated['next_run'] and updated['next_run'] != entry['next_run']
|
|
||||||
|
|
||||||
def test_once_past_never_arms(self, tmp_path):
|
|
||||||
svc, _ = make_service(tmp_path)
|
|
||||||
now = datetime.now().replace(second=0, microsecond=0)
|
|
||||||
entry = svc.save_entry(base_entry(
|
|
||||||
mode='once', once_at=(now - timedelta(minutes=1)).isoformat()))
|
|
||||||
assert entry['next_run'] == ''
|
|
||||||
|
|
||||||
def test_once_fires_then_disables_keeping_settings(self, tmp_path):
|
|
||||||
svc, admin = make_service(tmp_path)
|
|
||||||
now = datetime.now().replace(second=0, microsecond=0)
|
|
||||||
entry = svc.save_entry(base_entry(
|
|
||||||
mode='once', once_at=(now + timedelta(minutes=1)).isoformat()))
|
|
||||||
assert entry['next_run'] != ''
|
|
||||||
fired = svc.check_and_fire(now + timedelta(minutes=2))
|
|
||||||
assert len(fired) == 1
|
|
||||||
updated = [e for e in svc.list_entries() if e['id'] == entry['id']][0]
|
|
||||||
assert updated['enabled'] is False
|
|
||||||
assert updated['title'] == 'Notice' # settings kept for reuse
|
|
||||||
assert updated['once_at'] != ''
|
|
||||||
|
|
||||||
def test_disabled_entry_never_fires(self, tmp_path):
|
|
||||||
svc, admin = make_service(tmp_path)
|
|
||||||
target = (datetime.now() + timedelta(minutes=1)).replace(second=0, microsecond=0)
|
|
||||||
svc.save_entry(base_entry(
|
|
||||||
enabled=False, daily_times=[target.strftime('%H:%M')]))
|
|
||||||
assert svc.check_and_fire(target + timedelta(seconds=5)) == []
|
|
||||||
assert admin.broadcasts == []
|
|
||||||
|
|
||||||
def test_missed_window_rolls_forward_without_firing(self, tmp_path):
|
|
||||||
svc, admin = make_service(tmp_path)
|
|
||||||
now = datetime.now().replace(second=0, microsecond=0)
|
|
||||||
svc.save_entry(base_entry(
|
|
||||||
daily_times=[(now - timedelta(hours=3)).strftime('%H:%M')]))
|
|
||||||
# Force the stored next_run into the past to simulate downtime.
|
|
||||||
entries = svc.list_entries()
|
|
||||||
past = (now - timedelta(hours=2)).isoformat()
|
|
||||||
entries[0]['next_run'] = past
|
|
||||||
entries[0]['last_fired_for'] = ''
|
|
||||||
svc._save(entries)
|
|
||||||
assert svc.check_and_fire(now) == []
|
|
||||||
assert admin.broadcasts == []
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
"""Tests for no-behavior-change security validations."""
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.routes.api import fb_resolve_canonical, fb_within_roots
|
|
||||||
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:
|
|
||||||
ROOTS = ['/srv', '/home/dune/.dune']
|
|
||||||
|
|
||||||
def test_inside_roots(self):
|
|
||||||
assert fb_within_roots('/srv', self.ROOTS)
|
|
||||||
assert fb_within_roots('/srv/', self.ROOTS)
|
|
||||||
assert fb_within_roots('/srv/sub/dir/file.txt', self.ROOTS)
|
|
||||||
assert fb_within_roots('/home/dune/.dune/settings.conf', self.ROOTS)
|
|
||||||
|
|
||||||
def test_outside_roots(self):
|
|
||||||
assert not fb_within_roots('/', self.ROOTS)
|
|
||||||
assert not fb_within_roots('/etc/passwd', self.ROOTS)
|
|
||||||
assert not fb_within_roots('/etc/shadow', self.ROOTS)
|
|
||||||
assert not fb_within_roots('/home/dune/.ssh/id_rsa', self.ROOTS)
|
|
||||||
assert not fb_within_roots('/home/dune/.dune-evil/x', self.ROOTS)
|
|
||||||
assert not fb_within_roots('/srv-evil/x', self.ROOTS)
|
|
||||||
assert not fb_within_roots('', self.ROOTS)
|
|
||||||
|
|
||||||
def test_prefix_trick_rejected(self):
|
|
||||||
# '/srv-evil' must not match root '/srv'
|
|
||||||
assert not fb_within_roots('/srv-evil', ['/srv'])
|
|
||||||
assert fb_within_roots('/srv/a', ['/srv'])
|
|
||||||
|
|
||||||
|
|
||||||
class TestBackupNameWhitelist:
|
|
||||||
def test_valid_names(self):
|
|
||||||
assert is_valid_backup_name('backup-21-09-2026_103000')
|
|
||||||
assert is_valid_backup_name('backup-01-01-2000_000000')
|
|
||||||
|
|
||||||
def test_rejects_traversal_and_shell(self):
|
|
||||||
assert not is_valid_backup_name('../../settings')
|
|
||||||
assert not is_valid_backup_name('backup-21-09-2026_103000; id')
|
|
||||||
assert not is_valid_backup_name('x; id>/tmp/pwn; echo ')
|
|
||||||
assert not is_valid_backup_name('')
|
|
||||||
assert not is_valid_backup_name(None)
|
|
||||||
assert not is_valid_backup_name('backup-21-09-2026_103000.tar.gz')
|
|
||||||
assert not is_valid_backup_name('something-else')
|
|
||||||
|
|
||||||
|
|
||||||
class TestOnceAtValidation:
|
|
||||||
def test_lifecycle_rejects_garbage(self, tmp_path):
|
|
||||||
from app.services.lifecycle import LifecycleService
|
|
||||||
|
|
||||||
class FakeSSH:
|
|
||||||
def run(self, *a, **k):
|
|
||||||
return '', '', 0
|
|
||||||
|
|
||||||
class FakeAdmin:
|
|
||||||
def send_global_broadcast(self, *a, **k):
|
|
||||||
return True, 'sent'
|
|
||||||
|
|
||||||
svc = LifecycleService(FakeSSH(), FakeAdmin(), {}, state_dir=str(tmp_path))
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.update_schedule({'mode': 'once', 'once_at': 'not-a-date'})
|
|
||||||
|
|
||||||
def test_broadcast_rejects_garbage(self, tmp_path):
|
|
||||||
from app.services.scheduled_broadcast import ScheduledBroadcastService
|
|
||||||
|
|
||||||
class FakeAdmin:
|
|
||||||
def send_global_broadcast(self, *a, **k):
|
|
||||||
return True, 'sent'
|
|
||||||
|
|
||||||
svc = ScheduledBroadcastService(FakeAdmin(), state_dir=str(tmp_path))
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.save_entry({
|
|
||||||
'title': 't', 'message': 'm', 'mode': 'once',
|
|
||||||
'once_at': 'not-a-date',
|
|
||||||
})
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
"""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