Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91c7abc771 | ||
|
|
97cdbd3027 | ||
|
|
715845751b | ||
|
|
bd9bd452c9 | ||
|
|
bb5065dd59 | ||
|
|
f48a09e8d3 | ||
|
|
9c61e198fa | ||
|
|
ce241a283d | ||
|
|
91944a0213 | ||
|
|
421b37e854 | ||
|
|
312abe7bce | ||
|
|
54d9d5db25 | ||
|
|
aee4028f5c | ||
|
|
a2d5af20c9 | ||
|
|
306ebcc871 | ||
|
|
3486f3b2cb | ||
|
|
42eec81081 | ||
|
|
65a1948fd1 |
No files matched your search
+5
-2
@@ -38,6 +38,7 @@ config_local.py
|
|||||||
dune-tunnel-key
|
dune-tunnel-key
|
||||||
dune-awakening-server-sshKey
|
dune-awakening-server-sshKey
|
||||||
internal-scripts/ssh/sshKey
|
internal-scripts/ssh/sshKey
|
||||||
|
internal-scripts/ssh/known_hosts
|
||||||
|
|
||||||
# SSL Certificates
|
# SSL Certificates
|
||||||
ssl/
|
ssl/
|
||||||
@@ -73,6 +74,8 @@ logs/
|
|||||||
|
|
||||||
# Database
|
# Database
|
||||||
*.db
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
*.sqlite3
|
*.sqlite3
|
||||||
instance/
|
instance/
|
||||||
|
|
||||||
@@ -103,8 +106,8 @@ find_*.py
|
|||||||
AI_DOCS/
|
AI_DOCS/
|
||||||
AI_FULL_PROJECT_ANALYSIS_MODE/
|
AI_FULL_PROJECT_ANALYSIS_MODE/
|
||||||
|
|
||||||
# Version file (generated dynamically)
|
# VERSION is committed: it is the dashboard's version source of truth
|
||||||
VERSION
|
# (e.g. 0.7.5-experimental). The updater reads it, never ignores it.
|
||||||
|
|
||||||
# Security scripts (contain VM-specific configs)
|
# Security scripts (contain VM-specific configs)
|
||||||
scripts/
|
scripts/
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
||||||
|
|
||||||
> “A comprehensive web-based management dashboard for Dune: Awakening private servers.”
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
@@ -26,16 +24,18 @@ chmod +x start.sh
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
||||||
|
- **In-Game Notifications** — instant broadcasts plus scheduled one-shot/daily/weekly/monthly messages
|
||||||
|
- **Graceful Shutdown / Restart** — in-game countdown warnings with cancel notices, plus scheduled restarts
|
||||||
|
- **Battlegroup Control** — start/stop/restart/update, with update blocked while players are online
|
||||||
- **Chat Logs** with channel filtering and auto-refresh
|
- **Chat Logs** with channel filtering and auto-refresh
|
||||||
- **Director Tools** (battlegroups, world state, transfers)
|
- **Director Tools** (battlegroups, world state, transfers)
|
||||||
- **SSH File Browser** + **in-browser shell**
|
- **SSH File Browser** (jailed to allowed directories) + **in-browser shell**
|
||||||
|
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
|
||||||
|
- **Backup & Restore** — encrypted full-server snapshots with scheduled backups and retention cleanup
|
||||||
|
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources with verification
|
||||||
- **Firewall Hardening** via iptables
|
- **Firewall Hardening** via iptables
|
||||||
- **Auto‑Update** with safe file replacement
|
- **HTTPS + Remote Access** (self-signed or Let's Encrypt)
|
||||||
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
|
- **Cross-Platform Launchers** (Windows + Linux/macOS, incl. debug mode and SSH key rotation)
|
||||||
- **Cross‑Platform Launchers**
|
|
||||||
- **Organized Logging** with automatic cleanup and redaction
|
|
||||||
- **Debug Mode** with full SSH/K8s tracing
|
|
||||||
- **SSH Key Rotation** — scan all key locations and sync the newest key
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -60,36 +60,12 @@ 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)**
|
||||||
|
|||||||
@@ -46,10 +46,13 @@ DEFAULTS = {
|
|||||||
'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
|
'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
|
||||||
},
|
},
|
||||||
'director': {
|
'director': {
|
||||||
|
'host': '',
|
||||||
'port': 32479,
|
'port': 32479,
|
||||||
},
|
},
|
||||||
'filebrowser': {
|
'filebrowser': {
|
||||||
'port': 18888,
|
'port': 18888,
|
||||||
|
# Empty = built-in defaults (/srv, /home/dune/.dune).
|
||||||
|
'allowed_roots': [],
|
||||||
},
|
},
|
||||||
'firewall': {
|
'firewall': {
|
||||||
'block_filebrowser': True,
|
'block_filebrowser': True,
|
||||||
|
|||||||
+122
-16
@@ -6,6 +6,7 @@ import time
|
|||||||
import logging
|
import logging
|
||||||
import logging.handlers
|
import logging.handlers
|
||||||
import threading
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
from flask import Flask, request, g
|
from flask import Flask, request, g
|
||||||
from flask_login import current_user
|
from flask_login import current_user
|
||||||
from flask_socketio import SocketIO
|
from flask_socketio import SocketIO
|
||||||
@@ -25,6 +26,9 @@ from app.services.admin import AdminService
|
|||||||
from app.services.updater import UpdateService
|
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.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
|
||||||
@@ -51,6 +55,16 @@ def create_app(settings_path=None):
|
|||||||
app.config['WTF_CSRF_ENABLED'] = True
|
app.config['WTF_CSRF_ENABLED'] = True
|
||||||
app.config['WTF_CSRF_TIME_LIMIT'] = None
|
app.config['WTF_CSRF_TIME_LIMIT'] = None
|
||||||
|
|
||||||
|
# Cache-buster for static assets: browsers refetch CSS/JS whenever the
|
||||||
|
# files change, so theme fixes apply without a hard refresh.
|
||||||
|
try:
|
||||||
|
import time as _time
|
||||||
|
|
||||||
|
_asset_v = int(os.path.getmtime(os.path.join(base_dir, 'static', 'style.css')))
|
||||||
|
except OSError:
|
||||||
|
_asset_v = int(_time.time())
|
||||||
|
app.jinja_env.globals['asset_v'] = _asset_v
|
||||||
|
|
||||||
csrf = CSRFProtect(app)
|
csrf = CSRFProtect(app)
|
||||||
csrf.init_app(app)
|
csrf.init_app(app)
|
||||||
|
|
||||||
@@ -170,9 +184,12 @@ def create_app(settings_path=None):
|
|||||||
log_response_details(logging.getLogger(), response, duration * 1000)
|
log_response_details(logging.getLogger(), response, duration * 1000)
|
||||||
logging.getLogger().debug("=" * 60)
|
logging.getLogger().debug("=" * 60)
|
||||||
else:
|
else:
|
||||||
# Only log API requests to avoid noise
|
# Quiet console in normal mode: routine requests (including
|
||||||
if request.path.startswith('/api') or request.path.startswith('/server'):
|
# scanner 404s) are not logged. Turn on debug logging
|
||||||
logging.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
# (launcher option 4) to see every request. Server errors
|
||||||
|
# still surface so real problems are never silent.
|
||||||
|
if response.status_code >= 500:
|
||||||
|
logging.error(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
||||||
|
|
||||||
# Add timing header
|
# Add timing header
|
||||||
response.headers['X-Response-Time'] = f"{duration:.3f}s"
|
response.headers['X-Response-Time'] = f"{duration:.3f}s"
|
||||||
@@ -236,6 +253,16 @@ def create_app(settings_path=None):
|
|||||||
)
|
)
|
||||||
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
|
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
|
||||||
|
|
||||||
|
# Auto-detect namespace if not set in config — must run before
|
||||||
|
# services that consume the namespace (director, backup, etc.).
|
||||||
|
if settings['kubernetes']['namespace'] == '':
|
||||||
|
try:
|
||||||
|
k8s_service.auto_detect_namespace()
|
||||||
|
if k8s_service.namespace:
|
||||||
|
settings['kubernetes']['namespace'] = k8s_service.namespace
|
||||||
|
except Exception as e:
|
||||||
|
logging.warning(f"Could not auto-detect K8s namespace: {e}")
|
||||||
|
|
||||||
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
||||||
|
|
||||||
player_svc = PlayerService(db_service, dash_db=dash_db_service)
|
player_svc = PlayerService(db_service, dash_db=dash_db_service)
|
||||||
@@ -247,7 +274,7 @@ def create_app(settings_path=None):
|
|||||||
updater_svc = UpdateService(base_dir)
|
updater_svc = UpdateService(base_dir)
|
||||||
logging.debug("UpdateService initialized")
|
logging.debug("UpdateService initialized")
|
||||||
director_svc = DirectorService(
|
director_svc = DirectorService(
|
||||||
host='127.0.0.1',
|
host=settings.get('director', {}).get('host') or '127.0.0.1',
|
||||||
node_port=settings.get('director', {}).get('port', 32479),
|
node_port=settings.get('director', {}).get('port', 32479),
|
||||||
k8s_service=k8s_service,
|
k8s_service=k8s_service,
|
||||||
ssh_service=ssh_service,
|
ssh_service=ssh_service,
|
||||||
@@ -262,6 +289,15 @@ def create_app(settings_path=None):
|
|||||||
)
|
)
|
||||||
logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}")
|
logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}")
|
||||||
|
|
||||||
|
backup_svc = BackupService(ssh_service, k8s_service, rmq_svc, settings)
|
||||||
|
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,
|
||||||
@@ -275,6 +311,9 @@ def create_app(settings_path=None):
|
|||||||
'updater': updater_svc,
|
'updater': updater_svc,
|
||||||
'director': director_svc,
|
'director': director_svc,
|
||||||
'rmq': rmq_svc,
|
'rmq': rmq_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())}")
|
||||||
|
|
||||||
@@ -306,21 +345,13 @@ def create_app(settings_path=None):
|
|||||||
register_api_routes(app, services, settings)
|
register_api_routes(app, services, settings)
|
||||||
register_websocket_handlers(socketio, settings)
|
register_websocket_handlers(socketio, settings)
|
||||||
|
|
||||||
# Start update checker (disabled — being reworked)
|
# Background update check (channel-aware releases; installing is manual only)
|
||||||
# updater_svc.start_checker()
|
updater_svc.start_checker()
|
||||||
|
|
||||||
@app.teardown_appcontext
|
@app.teardown_appcontext
|
||||||
def cleanup_db(exc):
|
def cleanup_db(exc):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if settings['kubernetes']['namespace'] == '':
|
|
||||||
try:
|
|
||||||
k8s_service.auto_detect_namespace()
|
|
||||||
if k8s_service.namespace:
|
|
||||||
settings['kubernetes']['namespace'] = k8s_service.namespace
|
|
||||||
except Exception as e:
|
|
||||||
logging.warning(f"Could not auto-detect K8s namespace: {e}")
|
|
||||||
|
|
||||||
# Check SSL certificate expiry and start background monitor
|
# Check SSL certificate expiry and start background monitor
|
||||||
if ssl_enabled:
|
if ssl_enabled:
|
||||||
try:
|
try:
|
||||||
@@ -422,10 +453,12 @@ def create_app(settings_path=None):
|
|||||||
def _connection_monitor():
|
def _connection_monitor():
|
||||||
"""Background thread that monitors and auto-reconnects services."""
|
"""Background thread that monitors and auto-reconnects services."""
|
||||||
import time
|
import time
|
||||||
check_interval = 60 # Check every 60 seconds
|
check_interval = 30 # Check every 30 seconds
|
||||||
consecutive_failures = 0
|
consecutive_failures = 0
|
||||||
max_consecutive_failures = 5
|
max_consecutive_failures = 5
|
||||||
last_ssh_ok = True # Track SSH state to detect reconnection
|
last_ssh_ok = True # Track SSH state to detect reconnection
|
||||||
|
last_outage_warning = 0 # Last reminder logged during an outage
|
||||||
|
outage_reminder_interval = 3600 # Re-remind hourly, not every 30s
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
time.sleep(check_interval)
|
time.sleep(check_interval)
|
||||||
@@ -468,7 +501,14 @@ def create_app(settings_path=None):
|
|||||||
logging.debug("Connection monitor: All services healthy")
|
logging.debug("Connection monitor: All services healthy")
|
||||||
else:
|
else:
|
||||||
consecutive_failures += 1
|
consecutive_failures += 1
|
||||||
logging.warning(f"Connection monitor: Service issue detected (failures={consecutive_failures})")
|
# Warn on the state change, then only an hourly
|
||||||
|
# reminder for the rest of the outage.
|
||||||
|
now = time.time()
|
||||||
|
if consecutive_failures == 1:
|
||||||
|
logging.warning("Connection monitor: Service issue detected")
|
||||||
|
elif now - last_outage_warning >= outage_reminder_interval:
|
||||||
|
last_outage_warning = now
|
||||||
|
logging.warning(f"Connection monitor: still down after {consecutive_failures} checks")
|
||||||
|
|
||||||
# Force SSH reconnection if SSH check failed
|
# Force SSH reconnection if SSH check failed
|
||||||
if not ssh_ok and ssh_svc:
|
if not ssh_ok and ssh_svc:
|
||||||
@@ -496,6 +536,65 @@ def create_app(settings_path=None):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.debug(f"Could not initialize connection monitor: {e}")
|
logging.debug(f"Could not initialize connection monitor: {e}")
|
||||||
|
|
||||||
|
# ── Backup Scheduler ──────────────────────────────────────────────────
|
||||||
|
try:
|
||||||
|
backup_svc = services.get('backup')
|
||||||
|
if backup_svc:
|
||||||
|
def _backup_scheduler():
|
||||||
|
while True:
|
||||||
|
time.sleep(60)
|
||||||
|
try:
|
||||||
|
cfg = backup_svc.load_schedule()
|
||||||
|
if not cfg.get('enabled'):
|
||||||
|
continue
|
||||||
|
next_str = cfg.get('next_run', '')
|
||||||
|
if not next_str:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
next_ts = datetime.fromisoformat(next_str).timestamp()
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if time.time() >= next_ts:
|
||||||
|
ssh_svc = services.get('ssh')
|
||||||
|
if ssh_svc and not ssh_svc.check_connection():
|
||||||
|
logging.warning('Backup scheduler: SSH unavailable, skipping backup')
|
||||||
|
continue
|
||||||
|
logging.info('Backup scheduler: Triggering scheduled backup')
|
||||||
|
backup_svc.run_scheduled_backup()
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f'Backup scheduler: {e}')
|
||||||
|
|
||||||
|
sched_thread = threading.Thread(target=_backup_scheduler, daemon=True)
|
||||||
|
sched_thread.start()
|
||||||
|
logging.info('Backup scheduler: Background thread started')
|
||||||
|
except Exception as 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
|
||||||
|
|
||||||
@@ -529,6 +628,13 @@ def _setup_logging(settings):
|
|||||||
root_logger.addHandler(handler)
|
root_logger.addHandler(handler)
|
||||||
root_logger.addHandler(console_handler)
|
root_logger.addHandler(console_handler)
|
||||||
|
|
||||||
|
# Third-party chatter (e.g. paramiko connect/auth INFO on every SSH
|
||||||
|
# reconnect) stays at WARNING unless debug logging is on. Failures
|
||||||
|
# still surface through the existing warning/error calls.
|
||||||
|
if not settings['logging'].get('debug_enabled', False):
|
||||||
|
logging.getLogger('paramiko').setLevel(logging.WARNING)
|
||||||
|
logging.getLogger('urllib3').setLevel(logging.WARNING)
|
||||||
|
|
||||||
audit_logger = logging.getLogger('audit')
|
audit_logger = logging.getLogger('audit')
|
||||||
audit_handler = logging.handlers.RotatingFileHandler(
|
audit_handler = logging.handlers.RotatingFileHandler(
|
||||||
'logs/audit.log',
|
'logs/audit.log',
|
||||||
|
|||||||
+733
-663
File diff suppressed because it is too large.
Load diff
+95
-16
@@ -4,7 +4,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
from flask import Blueprint, render_template, request, jsonify
|
from flask import Blueprint, render_template, request, jsonify
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
from app.utils.constants import NAV_PAGES, GUILD_ROLES
|
from app.utils.constants import NAV_PAGES, NAV_GROUPS, GUILD_ROLES
|
||||||
from app.utils.debug_logging import sanitize_for_log
|
from app.utils.debug_logging import sanitize_for_log
|
||||||
from app.services.player import LIKE_PC
|
from app.services.player import LIKE_PC
|
||||||
|
|
||||||
@@ -49,6 +49,7 @@ def register_routes(app, services, settings):
|
|||||||
)
|
)
|
||||||
return dict(
|
return dict(
|
||||||
nav_pages=NAV_PAGES,
|
nav_pages=NAV_PAGES,
|
||||||
|
nav_groups=NAV_GROUPS,
|
||||||
current_path=request.path if request else '/',
|
current_path=request.path if request else '/',
|
||||||
fmt_role=fmt_role,
|
fmt_role=fmt_role,
|
||||||
conn_ok=conn_ok,
|
conn_ok=conn_ok,
|
||||||
@@ -362,27 +363,105 @@ def register_routes(app, services, settings):
|
|||||||
@app.route('/events')
|
@app.route('/events')
|
||||||
@login_required
|
@login_required
|
||||||
def events_page():
|
def events_page():
|
||||||
|
from flask import request as flask_request
|
||||||
|
from app.utils.events import (
|
||||||
|
GAME_EVENT_LABELS,
|
||||||
|
event_label,
|
||||||
|
parse_solaris_meta,
|
||||||
|
summarize_game_event,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Filters (validated; anything unknown falls back to 'all').
|
||||||
|
type_filter = flask_request.args.get('type', 'all')
|
||||||
|
try:
|
||||||
|
type_filter = int(type_filter)
|
||||||
|
if type_filter not in GAME_EVENT_LABELS:
|
||||||
|
type_filter = 'all'
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
type_filter = 'all'
|
||||||
|
map_filter = flask_request.args.get('map', 'all')
|
||||||
|
facing_filter = flask_request.args.get('facing', 'all')
|
||||||
|
if facing_filter not in ('0', '1'):
|
||||||
|
facing_filter = 'all'
|
||||||
|
|
||||||
game_events = []
|
game_events = []
|
||||||
event_logs = []
|
maps = []
|
||||||
|
counts_24h = {}
|
||||||
|
total_24h = 0
|
||||||
|
solaris = []
|
||||||
|
|
||||||
def safe_query(table, cols, order_col, limit):
|
|
||||||
try:
|
try:
|
||||||
return db.query(f"SELECT {cols} FROM {table} ORDER BY {order_col} DESC LIMIT {limit}") or []
|
map_rows = db.query(
|
||||||
|
"SELECT DISTINCT map FROM dune.game_events WHERE map IS NOT NULL ORDER BY map") or []
|
||||||
|
maps = [r['map'] for r in map_rows if r.get('map')]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error fetching {table}: {e}")
|
logger.error(f"Error fetching event maps: {e}")
|
||||||
return []
|
if map_filter != 'all' and map_filter not in maps:
|
||||||
|
map_filter = 'all'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
game_events = safe_query("dune.game_events", "*", "universe_time", 50)
|
stat_rows = db.query(
|
||||||
except Exception:
|
"SELECT event_type, COUNT(*)::int AS cnt FROM dune.game_events "
|
||||||
|
"WHERE universe_time > NOW() - INTERVAL '24 hours' "
|
||||||
|
"GROUP BY event_type") or []
|
||||||
|
for row in stat_rows:
|
||||||
|
try:
|
||||||
|
counts_24h[int(row['event_type'])] = row['cnt']
|
||||||
|
total_24h += row['cnt']
|
||||||
|
except (TypeError, ValueError, KeyError):
|
||||||
pass
|
pass
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error fetching event stats: {e}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
event_logs = safe_query("dune.event_log", "*", "event_time", 100)
|
conditions = []
|
||||||
except Exception:
|
params = []
|
||||||
pass
|
if type_filter != 'all':
|
||||||
|
conditions.append("event_type = %s")
|
||||||
|
params.append(type_filter)
|
||||||
|
if map_filter != 'all':
|
||||||
|
conditions.append("map = %s")
|
||||||
|
params.append(map_filter)
|
||||||
|
if facing_filter != 'all':
|
||||||
|
conditions.append("player_facing_event = %s")
|
||||||
|
params.append(facing_filter == '1')
|
||||||
|
where = ("WHERE " + " AND ".join(conditions)) if conditions else ""
|
||||||
|
game_events = db.query(
|
||||||
|
f"SELECT actor_id, universe_time, map, partition_id, event_type, "
|
||||||
|
f"x, y, z, custom_data, player_facing_event "
|
||||||
|
f"FROM dune.game_events {where} "
|
||||||
|
f"ORDER BY universe_time DESC LIMIT 200", params) or []
|
||||||
|
for event in game_events:
|
||||||
|
event['label'] = event_label(event.get('event_type'))
|
||||||
|
event['summary'] = summarize_game_event(
|
||||||
|
event.get('event_type'), event.get('custom_data'))
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error fetching game_events: {e}")
|
||||||
|
game_events = []
|
||||||
|
|
||||||
return render_template('events.html', game_events=game_events, event_logs=event_logs)
|
try:
|
||||||
|
log_rows = db.query(
|
||||||
|
"SELECT id, event_time, category, message, function_name, meta "
|
||||||
|
"FROM dune.event_log ORDER BY event_time DESC LIMIT 100") or []
|
||||||
|
for row in log_rows:
|
||||||
|
parsed = parse_solaris_meta(row.get('meta'))
|
||||||
|
if parsed:
|
||||||
|
row.update(parsed)
|
||||||
|
solaris.append(row)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error fetching event_log: {e}")
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
'events.html',
|
||||||
|
game_events=game_events,
|
||||||
|
type_filter=type_filter,
|
||||||
|
map_filter=map_filter,
|
||||||
|
facing_filter=facing_filter,
|
||||||
|
type_options=sorted(GAME_EVENT_LABELS.items()),
|
||||||
|
maps=maps,
|
||||||
|
counts_24h=counts_24h,
|
||||||
|
total_24h=total_24h,
|
||||||
|
solaris=solaris)
|
||||||
|
|
||||||
# Chat
|
# Chat
|
||||||
@app.route('/chat')
|
@app.route('/chat')
|
||||||
@@ -529,11 +608,11 @@ 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
|
# Backup / Restore
|
||||||
@app.route('/admin-experimental')
|
@app.route('/backup')
|
||||||
@login_required
|
@login_required
|
||||||
def admin_experimental():
|
def backup_page():
|
||||||
return render_template('admin_experimental.html')
|
return render_template('backup.html')
|
||||||
|
|
||||||
# Map - shows locations of players, vehicles, buildings
|
# Map - shows locations of players, vehicles, buildings
|
||||||
@app.route('/map')
|
@app.route('/map')
|
||||||
|
|||||||
@@ -802,6 +802,13 @@ 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()
|
||||||
|
|
||||||
@@ -809,7 +816,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}">>, '
|
f'Token = <<"{token_esc}">>, '
|
||||||
'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]}})), '
|
||||||
|
|||||||
@@ -0,0 +1,849 @@
|
|||||||
|
"""Backup service - backup creation, restore orchestration, backup management"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tarfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet, InvalidToken
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class BackupError(Exception):
|
||||||
|
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:
|
||||||
|
BACKUP_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
|
||||||
|
|
||||||
|
def __init__(self, ssh_service, k8s_service, rmq_service, settings):
|
||||||
|
self.ssh = ssh_service
|
||||||
|
self.k8s = k8s_service
|
||||||
|
self.rmq = rmq_service
|
||||||
|
self.settings = settings
|
||||||
|
self._restore_state = {}
|
||||||
|
os.makedirs(self.BACKUP_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
def _backup_path(self, name):
|
||||||
|
return os.path.join(self.BACKUP_DIR, name)
|
||||||
|
|
||||||
|
def _timestamp(self):
|
||||||
|
return datetime.now().strftime('%d-%m-%Y_%H%M%S')
|
||||||
|
|
||||||
|
def _fmt_date(self, ts):
|
||||||
|
if not ts:
|
||||||
|
return 'unknown'
|
||||||
|
try:
|
||||||
|
dt = datetime.strptime(ts, '%d-%m-%Y_%H%M%S')
|
||||||
|
return dt.strftime('%d-%m-%Y %H:%M:%S')
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return ts
|
||||||
|
|
||||||
|
# ── Backup Creation ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
def create_backup(self, password=''):
|
||||||
|
ts = self._timestamp()
|
||||||
|
backup_name = f'backup-{ts}'
|
||||||
|
work_dir = self._backup_path(backup_name)
|
||||||
|
os.makedirs(work_dir, exist_ok=True)
|
||||||
|
|
||||||
|
components = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. Battleground backup via VM tool
|
||||||
|
logger.info('Backup: Running battlegroup backup on VM...')
|
||||||
|
stdout, stderr, rc = self.ssh.run(
|
||||||
|
'/home/dune/.dune/bin/battlegroup backup', timeout=300)
|
||||||
|
if rc != 0:
|
||||||
|
raise BackupError(f'battlegroup backup failed: {stderr}')
|
||||||
|
|
||||||
|
bg_path = None
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if line.endswith('.tar.gz') or 'backup' in line.lower():
|
||||||
|
bg_path = line
|
||||||
|
if not bg_path:
|
||||||
|
raise BackupError('Could not locate battlegroup backup file on VM')
|
||||||
|
|
||||||
|
bg_local = os.path.join(work_dir, 'battlegroup-backup.tar.gz')
|
||||||
|
logger.info(f'Backup: Downloading {bg_path}...')
|
||||||
|
self._download_file(bg_path, bg_local)
|
||||||
|
components.append({
|
||||||
|
'name': 'battlegroup-backup.tar.gz',
|
||||||
|
'source': 'VM battlegroup tool',
|
||||||
|
'size': os.path.getsize(bg_local),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 2. K8s manifests
|
||||||
|
logger.info('Backup: Exporting K8s resources...')
|
||||||
|
k8s_dir = os.path.join(work_dir, 'k8s-manifests')
|
||||||
|
os.makedirs(k8s_dir, exist_ok=True)
|
||||||
|
ns = self.k8s.namespace
|
||||||
|
resources = [('battlegroup', 'battlegroup-crd.yaml'),
|
||||||
|
('deploy', 'deployments.yaml'),
|
||||||
|
('sts', 'statefulsets.yaml'),
|
||||||
|
('svc', 'services.yaml'),
|
||||||
|
('cm', 'configmaps.yaml'),
|
||||||
|
('secret', 'secrets.yaml')]
|
||||||
|
for res, fname in resources:
|
||||||
|
stdout, stderr, rc = self.ssh.run(
|
||||||
|
f'sudo kubectl get {res} -n {ns} -o yaml', timeout=60)
|
||||||
|
if rc == 0 and stdout.strip():
|
||||||
|
with open(os.path.join(k8s_dir, fname), 'w') as f:
|
||||||
|
f.write(stdout)
|
||||||
|
components.append({
|
||||||
|
'name': f'k8s-manifests/{fname}',
|
||||||
|
'source': f'kubectl get {res}',
|
||||||
|
'size': len(stdout),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 3. RMQ definitions
|
||||||
|
logger.info('Backup: Exporting RMQ definitions...')
|
||||||
|
rmq_dir = os.path.join(work_dir, 'rmq')
|
||||||
|
os.makedirs(rmq_dir, exist_ok=True)
|
||||||
|
for label, fetch_fn in [('admin-overview', self.rmq.overview),
|
||||||
|
('game-overview', self.rmq.game_overview)]:
|
||||||
|
try:
|
||||||
|
data = fetch_fn()
|
||||||
|
if data:
|
||||||
|
with open(os.path.join(rmq_dir, f'{label}.json'), 'w') as f:
|
||||||
|
json.dump(data, f, indent=2)
|
||||||
|
components.append({
|
||||||
|
'name': f'rmq/{label}.json',
|
||||||
|
'source': f'RMQ {label}',
|
||||||
|
'size': len(json.dumps(data)),
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f'Backup: Could not export RMQ {label}: {e}')
|
||||||
|
|
||||||
|
# 4. Dashboard database schema (bans, audit_log, chat_history, player_ips, player_actions, settings)
|
||||||
|
logger.info('Backup: Dumping dashboard schema...')
|
||||||
|
db_dump = None
|
||||||
|
ns = self.k8s.namespace
|
||||||
|
dbpod_cmd = (
|
||||||
|
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
|
||||||
|
f'sudo kubectl exec -n {ns} $dbpod -- pg_dump -U postgres -d dune '
|
||||||
|
f'--schema=dashboard --no-owner --no-acl 2>/dev/null'
|
||||||
|
)
|
||||||
|
stdout, stderr, rc = self.ssh.run(dbpod_cmd, timeout=120)
|
||||||
|
if rc == 0 and stdout.strip():
|
||||||
|
db_dump = os.path.join(work_dir, 'dashboard-db.sql')
|
||||||
|
with open(db_dump, 'w') as f:
|
||||||
|
f.write(stdout)
|
||||||
|
components.append({
|
||||||
|
'name': 'dashboard-db.sql',
|
||||||
|
'source': 'pg_dump dashboard schema',
|
||||||
|
'size': len(stdout),
|
||||||
|
})
|
||||||
|
logger.info(f'Backup: Dashboard schema dumped ({len(stdout)} bytes)')
|
||||||
|
else:
|
||||||
|
logger.warning(f'Backup: Could not dump dashboard schema: {stderr}')
|
||||||
|
|
||||||
|
# 5. Dashboard settings.yaml
|
||||||
|
settings_path = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'settings.yaml')
|
||||||
|
if os.path.exists(settings_path):
|
||||||
|
shutil.copy2(settings_path, os.path.join(work_dir, 'settings.yaml'))
|
||||||
|
components.append({
|
||||||
|
'name': 'settings.yaml',
|
||||||
|
'source': 'local',
|
||||||
|
'size': os.path.getsize(settings_path),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 6. Write manifest
|
||||||
|
manifest = {
|
||||||
|
'name': backup_name,
|
||||||
|
'created': ts,
|
||||||
|
'dashboard_version': 'v0.5.0',
|
||||||
|
'components': components,
|
||||||
|
}
|
||||||
|
with open(os.path.join(work_dir, 'metadata.json'), 'w') as f:
|
||||||
|
json.dump(manifest, f, indent=2)
|
||||||
|
|
||||||
|
# 7. Package into tarball
|
||||||
|
archive_path = self._backup_path(f'{backup_name}.tar.gz')
|
||||||
|
with tarfile.open(archive_path, 'w:gz') as tar:
|
||||||
|
tar.add(work_dir, arcname=backup_name)
|
||||||
|
shutil.rmtree(work_dir)
|
||||||
|
|
||||||
|
# 8. Encrypt with password if provided
|
||||||
|
encrypted = False
|
||||||
|
if password:
|
||||||
|
logger.info('Backup: Encrypting with password...')
|
||||||
|
self._encrypt_file(archive_path, password)
|
||||||
|
encrypted = True
|
||||||
|
|
||||||
|
# Write sidecar metadata so list/preview work without password
|
||||||
|
meta_path = self._backup_path(f'{backup_name}.meta')
|
||||||
|
with open(meta_path, 'w') as f:
|
||||||
|
json.dump({'name': backup_name, 'created': ts, 'components': components}, f)
|
||||||
|
|
||||||
|
total_size = os.path.getsize(archive_path)
|
||||||
|
logger.info(f'Backup created: {archive_path} ({total_size} bytes)')
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'backup': backup_name,
|
||||||
|
'path': archive_path,
|
||||||
|
'size': total_size,
|
||||||
|
'components': components,
|
||||||
|
'encrypted': encrypted,
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if os.path.exists(work_dir):
|
||||||
|
shutil.rmtree(work_dir)
|
||||||
|
logger.error(f'Backup failed: {e}')
|
||||||
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
|
def _download_file(self, remote_path, local_path):
|
||||||
|
stdout, stderr, rc = self.ssh.run(
|
||||||
|
f'cat {shlex.quote(remote_path)} | base64', timeout=120)
|
||||||
|
if rc != 0:
|
||||||
|
raise BackupError(f'Failed to read remote file: {stderr}')
|
||||||
|
raw = base64.b64decode(stdout)
|
||||||
|
with open(local_path, 'wb') as f:
|
||||||
|
f.write(raw)
|
||||||
|
|
||||||
|
def _encrypt_file(self, filepath, password):
|
||||||
|
salt = os.urandom(16)
|
||||||
|
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=600000)
|
||||||
|
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
|
||||||
|
f = Fernet(key)
|
||||||
|
with open(filepath, 'rb') as fh:
|
||||||
|
data = fh.read()
|
||||||
|
encrypted = salt + f.encrypt(data)
|
||||||
|
with open(filepath, 'wb') as fh:
|
||||||
|
fh.write(encrypted)
|
||||||
|
|
||||||
|
def _decrypt_file(self, filepath, password):
|
||||||
|
with open(filepath, 'rb') as fh:
|
||||||
|
data = fh.read()
|
||||||
|
salt = data[:16]
|
||||||
|
ciphertext = data[16:]
|
||||||
|
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=600000)
|
||||||
|
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
|
||||||
|
f = Fernet(key)
|
||||||
|
return f.decrypt(ciphertext)
|
||||||
|
|
||||||
|
def _backup_is_encrypted(self, name):
|
||||||
|
path = self._backup_path(f'{name}.tar.gz')
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
with tarfile.open(path, 'r:gz') as tar:
|
||||||
|
tar.getmembers()
|
||||||
|
return False
|
||||||
|
except Exception:
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _schedule_path(self):
|
||||||
|
return os.path.join(self.BACKUP_DIR, 'schedule.json')
|
||||||
|
|
||||||
|
def load_schedule(self):
|
||||||
|
path = self._schedule_path()
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {'enabled': False, 'mode': 'interval', 'interval_minutes': 1440,
|
||||||
|
'schedule_days': [], 'schedule_times': ['05:00'],
|
||||||
|
'keep': 5, 'password': '', 'next_run': ''}
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
return json.load(f)
|
||||||
|
except Exception:
|
||||||
|
return {'enabled': False, 'mode': 'interval', 'interval_minutes': 1440,
|
||||||
|
'schedule_days': [], 'schedule_times': ['05:00'],
|
||||||
|
'keep': 5, 'password': '', 'next_run': ''}
|
||||||
|
|
||||||
|
def save_schedule(self, cfg):
|
||||||
|
with open(self._schedule_path(), 'w') as f:
|
||||||
|
json.dump(cfg, f, indent=2)
|
||||||
|
|
||||||
|
def get_schedule(self):
|
||||||
|
return self.load_schedule()
|
||||||
|
|
||||||
|
def _next_run_from_schedule(self, cfg):
|
||||||
|
now = datetime.now()
|
||||||
|
days_set = set(cfg.get('schedule_days', []))
|
||||||
|
times = cfg.get('schedule_times', [])
|
||||||
|
if not days_set or not times:
|
||||||
|
return ''
|
||||||
|
best = None
|
||||||
|
for offset in range(8):
|
||||||
|
base = datetime(now.year, now.month, now.day) + timedelta(days=offset)
|
||||||
|
wd = base.weekday()
|
||||||
|
if wd not in days_set:
|
||||||
|
continue
|
||||||
|
for t in times:
|
||||||
|
try:
|
||||||
|
h, m = (int(x) for x in t.split(':'))
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
candidate = base.replace(hour=h, minute=m, 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_run_from_interval(self, cfg):
|
||||||
|
return datetime.fromtimestamp(time.time() + cfg['interval_minutes'] * 60).isoformat()
|
||||||
|
|
||||||
|
def update_schedule(self, data):
|
||||||
|
cfg = self.load_schedule()
|
||||||
|
cfg['enabled'] = bool(data.get('enabled', cfg['enabled']))
|
||||||
|
if 'mode' in data:
|
||||||
|
cfg['mode'] = data['mode']
|
||||||
|
if 'interval_minutes' in data:
|
||||||
|
cfg['interval_minutes'] = int(data['interval_minutes'])
|
||||||
|
if 'schedule_days' in data:
|
||||||
|
cfg['schedule_days'] = data['schedule_days']
|
||||||
|
if 'schedule_times' in data:
|
||||||
|
cfg['schedule_times'] = data['schedule_times']
|
||||||
|
cfg['keep'] = int(data.get('keep', cfg['keep']))
|
||||||
|
if 'password' in data:
|
||||||
|
if data['password']:
|
||||||
|
cfg['password'] = data['password']
|
||||||
|
# empty string = keep existing password (don't overwrite)
|
||||||
|
if cfg.get('mode') == 'schedule':
|
||||||
|
cfg['next_run'] = self._next_run_from_schedule(cfg)
|
||||||
|
else:
|
||||||
|
cfg['next_run'] = self._next_run_from_interval(cfg)
|
||||||
|
self.save_schedule(cfg)
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
def run_scheduled_backup(self):
|
||||||
|
cfg = self.load_schedule()
|
||||||
|
if not cfg.get('enabled'):
|
||||||
|
return {'success': False, 'error': 'Scheduled backups are disabled'}
|
||||||
|
pw = cfg.get('password', '') or None
|
||||||
|
result = self.create_backup(password=pw or '')
|
||||||
|
if result.get('success'):
|
||||||
|
keep = cfg.get('keep', 5)
|
||||||
|
if keep > 0:
|
||||||
|
self._enforce_retention(keep)
|
||||||
|
if cfg.get('mode') == 'schedule':
|
||||||
|
cfg['next_run'] = self._next_run_from_schedule(cfg)
|
||||||
|
else:
|
||||||
|
cfg['next_run'] = self._next_run_from_interval(cfg)
|
||||||
|
self.save_schedule(cfg)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _enforce_retention(self, keep):
|
||||||
|
backups = []
|
||||||
|
for fname in sorted(os.listdir(self.BACKUP_DIR), reverse=True):
|
||||||
|
if fname.endswith('.tar.gz'):
|
||||||
|
backups.append(fname.replace('.tar.gz', ''))
|
||||||
|
backups.sort(reverse=True)
|
||||||
|
for old in backups[keep:]:
|
||||||
|
self.delete_backup(old)
|
||||||
|
|
||||||
|
# ── Backup Listing ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def list_backups(self):
|
||||||
|
backups = []
|
||||||
|
if not os.path.isdir(self.BACKUP_DIR):
|
||||||
|
return backups
|
||||||
|
for fname in sorted(os.listdir(self.BACKUP_DIR), reverse=True):
|
||||||
|
if fname.endswith('.tar.gz'):
|
||||||
|
fpath = os.path.join(self.BACKUP_DIR, fname)
|
||||||
|
info = self.get_backup_info(fpath)
|
||||||
|
name = fname.replace('.tar.gz', '')
|
||||||
|
backups.append({
|
||||||
|
'name': name,
|
||||||
|
'path': fpath,
|
||||||
|
'size': os.path.getsize(fpath),
|
||||||
|
'created': self._fmt_date(info.get('created', '')),
|
||||||
|
'components': info.get('components', []),
|
||||||
|
'password_protected': self._backup_is_encrypted(name),
|
||||||
|
})
|
||||||
|
return backups
|
||||||
|
|
||||||
|
def get_backup_info(self, path):
|
||||||
|
if path.endswith('.tar.gz'):
|
||||||
|
meta_path = path.replace('.tar.gz', '.meta')
|
||||||
|
if os.path.exists(meta_path):
|
||||||
|
try:
|
||||||
|
with open(meta_path) as f:
|
||||||
|
return json.load(f)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f'Could not read sidecar meta from {meta_path}: {e}')
|
||||||
|
try:
|
||||||
|
with tarfile.open(path, 'r:gz') as tar:
|
||||||
|
for m in tar.getmembers():
|
||||||
|
if m.name.endswith('metadata.json'):
|
||||||
|
with tar.extractfile(m) as f:
|
||||||
|
return json.loads(f.read().decode('utf-8'))
|
||||||
|
except Exception as e:
|
||||||
|
# Expected for encrypted archives (handled by verify with a
|
||||||
|
# password) and pre-sidecar backups; not worth a warning.
|
||||||
|
logger.debug(f'Could not read metadata from {path}: {e}')
|
||||||
|
return {}
|
||||||
|
|
||||||
|
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')
|
||||||
|
if os.path.exists(path):
|
||||||
|
os.remove(path)
|
||||||
|
meta_path = self._backup_path(f'{name}.meta')
|
||||||
|
if os.path.exists(meta_path):
|
||||||
|
os.remove(meta_path)
|
||||||
|
return True
|
||||||
|
|
||||||
|
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')
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {'success': False, 'error': 'Backup not found'}
|
||||||
|
is_encrypted = self._backup_is_encrypted(name)
|
||||||
|
meta = self.get_backup_info(path)
|
||||||
|
if is_encrypted and not password:
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'valid': True,
|
||||||
|
'encrypted': True,
|
||||||
|
'files': 0,
|
||||||
|
'size': os.path.getsize(path),
|
||||||
|
'components': meta.get('components', []),
|
||||||
|
'note': 'Enter password to verify contents',
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
if is_encrypted:
|
||||||
|
decrypted = self._decrypt_file(path, password)
|
||||||
|
import tempfile
|
||||||
|
tmp = tempfile.NamedTemporaryFile(suffix='.tar.gz', delete=False)
|
||||||
|
tmp.write(decrypted)
|
||||||
|
tmp_path = tmp.name
|
||||||
|
tmp.close()
|
||||||
|
try:
|
||||||
|
with tarfile.open(tmp_path, 'r:gz') as tar:
|
||||||
|
members = tar.getmembers()
|
||||||
|
finally:
|
||||||
|
os.unlink(tmp_path)
|
||||||
|
else:
|
||||||
|
with tarfile.open(path, 'r:gz') as tar:
|
||||||
|
members = tar.getmembers()
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'valid': True,
|
||||||
|
'encrypted': is_encrypted,
|
||||||
|
'files': len(members),
|
||||||
|
'size': os.path.getsize(path),
|
||||||
|
'components': meta.get('components', []),
|
||||||
|
}
|
||||||
|
except InvalidToken:
|
||||||
|
return {'success': False, 'valid': False, 'error': 'Wrong password'}
|
||||||
|
except Exception as e:
|
||||||
|
return {'success': False, 'valid': False, 'error': f'Backup corrupted: {e}'}
|
||||||
|
|
||||||
|
# ── Restore Orchestration ─────────────────────────────────────────
|
||||||
|
|
||||||
|
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')
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {'success': False, 'error': 'Backup not found'}
|
||||||
|
info = self.get_backup_info(path)
|
||||||
|
comps = info.get('components', [])
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'backup': name,
|
||||||
|
'created': self._fmt_date(info.get('created', '')),
|
||||||
|
'components': comps,
|
||||||
|
'has_db': any('battlegroup-backup' in c.get('name', '') for c in comps),
|
||||||
|
'has_dash_db': any('dashboard-db.sql' in c.get('name', '') for c in comps),
|
||||||
|
'has_k8s': any('k8s-manifests' in c.get('name', '') for c in comps),
|
||||||
|
'has_settings': any('settings.yaml' in c.get('name', '') for c in comps),
|
||||||
|
'has_rmq': any(c.get('name', '').startswith('rmq/') for c in comps),
|
||||||
|
'password_protected': self._backup_is_encrypted(name),
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_connection(self):
|
||||||
|
ssh_user = self.settings.get('server', {}).get('user', 'dune')
|
||||||
|
ssh_key = self.settings.get('server', {}).get('ssh_key', '')
|
||||||
|
vm_ip = self.settings.get('server', {}).get('host', '')
|
||||||
|
if not ssh_key:
|
||||||
|
return {'success': False, 'error': 'No SSH key configured in dashboard settings'}
|
||||||
|
if not vm_ip:
|
||||||
|
return {'success': False, 'error': 'No server host configured in dashboard settings'}
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=10',
|
||||||
|
'-o', 'LogLevel=QUIET', '-i', ssh_key,
|
||||||
|
f'{ssh_user}@{vm_ip}',
|
||||||
|
'hostname && sudo kubectl get nodes --no-headers 2>/dev/null | head -1'],
|
||||||
|
capture_output=True, text=True, timeout=30)
|
||||||
|
if result.returncode != 0:
|
||||||
|
return {'success': False, 'error': result.stderr.strip() or 'Connection failed'}
|
||||||
|
lines = [l for l in result.stdout.splitlines() if l.strip()]
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'hostname': lines[0] if lines else 'unknown',
|
||||||
|
'k8s_ok': len(lines) > 1,
|
||||||
|
}
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
return {'success': False, 'error': 'Connection timed out'}
|
||||||
|
except FileNotFoundError:
|
||||||
|
return {'success': False, 'error': 'SSH client not found on dashboard machine'}
|
||||||
|
except Exception as e:
|
||||||
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
|
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_key = self.settings.get('server', {}).get('ssh_key', '')
|
||||||
|
vm_ip = self.settings.get('server', {}).get('host', '')
|
||||||
|
if not ssh_key:
|
||||||
|
return {'success': False, 'error': 'No SSH key configured in dashboard settings'}
|
||||||
|
if not vm_ip:
|
||||||
|
return {'success': False, 'error': 'No server host configured in dashboard settings'}
|
||||||
|
state_key = backup_name
|
||||||
|
self._restore_state[state_key] = {
|
||||||
|
'status': 'preparing',
|
||||||
|
'progress': 0,
|
||||||
|
'steps': [],
|
||||||
|
'current_step': 0,
|
||||||
|
'backup_name': backup_name,
|
||||||
|
'vm_ip': vm_ip,
|
||||||
|
'ssh_user': ssh_user,
|
||||||
|
'ssh_key_path': ssh_key,
|
||||||
|
'options': options,
|
||||||
|
'errors': [],
|
||||||
|
'completed_steps': [],
|
||||||
|
'started': time.time(),
|
||||||
|
}
|
||||||
|
t = threading.Thread(target=self._run_restore, args=(state_key,), daemon=True)
|
||||||
|
t.start()
|
||||||
|
return {'success': True, 'restore_id': state_key}
|
||||||
|
|
||||||
|
def get_restore_status(self, restore_id):
|
||||||
|
state = self._restore_state.get(restore_id)
|
||||||
|
if not state:
|
||||||
|
return {'success': False, 'error': 'Restore not found'}
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'status': state['status'],
|
||||||
|
'progress': state['progress'],
|
||||||
|
'steps': state['steps'],
|
||||||
|
'current_step': state['current_step'],
|
||||||
|
'completed_steps': state['completed_steps'],
|
||||||
|
'errors': state['errors'],
|
||||||
|
}
|
||||||
|
|
||||||
|
def _run_restore(self, state_key):
|
||||||
|
state = self._restore_state[state_key]
|
||||||
|
opts = state['options']
|
||||||
|
vm_ip = state['vm_ip']
|
||||||
|
ssh_user = state['ssh_user']
|
||||||
|
ssh_key = state['ssh_key_path']
|
||||||
|
backup_name = state['backup_name']
|
||||||
|
ns = self.k8s.namespace
|
||||||
|
|
||||||
|
def ssh_cmd(cmd, timeout=120):
|
||||||
|
return subprocess.run(
|
||||||
|
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'LogLevel=QUIET',
|
||||||
|
'-i', ssh_key, f'{ssh_user}@{vm_ip}', cmd],
|
||||||
|
capture_output=True, text=True, timeout=timeout)
|
||||||
|
|
||||||
|
def add_step(label):
|
||||||
|
state['steps'].append(label)
|
||||||
|
|
||||||
|
def complete_step(label, success, detail=''):
|
||||||
|
state['completed_steps'].append({
|
||||||
|
'label': label, 'success': success, 'detail': detail,
|
||||||
|
})
|
||||||
|
if not success:
|
||||||
|
state['errors'].append(detail or f'{label} failed')
|
||||||
|
state['current_step'] += 1
|
||||||
|
total = max(len(state['steps']), 1)
|
||||||
|
state['progress'] = min(int(state['current_step'] / total * 100), 99)
|
||||||
|
|
||||||
|
archive_path = self._backup_path(f'{backup_name}.tar.gz')
|
||||||
|
pw = opts.get('password', '')
|
||||||
|
|
||||||
|
# Step 0: Decrypt backup if password provided
|
||||||
|
if self._backup_is_encrypted(backup_name):
|
||||||
|
add_step('Decrypting backup archive')
|
||||||
|
try:
|
||||||
|
if not pw:
|
||||||
|
raise BackupError('Backup is encrypted but no password provided')
|
||||||
|
decrypted = self._decrypt_file(archive_path, pw)
|
||||||
|
import tempfile
|
||||||
|
tmp = tempfile.NamedTemporaryFile(suffix='.tar.gz', delete=False)
|
||||||
|
tmp.write(decrypted)
|
||||||
|
upload_path = tmp.name
|
||||||
|
tmp.close()
|
||||||
|
complete_step('Decrypting backup archive', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Decrypting backup archive', False, str(e))
|
||||||
|
state['status'] = 'failed'
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
upload_path = archive_path
|
||||||
|
|
||||||
|
# Step 1: Upload backup archive to new VM
|
||||||
|
add_step('Uploading backup archive to new VM')
|
||||||
|
try:
|
||||||
|
with open(upload_path, 'rb') as f:
|
||||||
|
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 > {shlex.quote(remote_archive)}', timeout=300)
|
||||||
|
if r.returncode != 0:
|
||||||
|
raise BackupError(f'Upload failed: {r.stderr}')
|
||||||
|
complete_step('Uploading backup archive to new VM', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Uploading backup archive to new VM', False, str(e))
|
||||||
|
state['status'] = 'failed'
|
||||||
|
return
|
||||||
|
finally:
|
||||||
|
if upload_path != archive_path:
|
||||||
|
try:
|
||||||
|
os.unlink(upload_path)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Step 2: Extract archive on VM
|
||||||
|
add_step('Extracting backup archive on VM')
|
||||||
|
try:
|
||||||
|
restore_dir = f'/tmp/restore-{backup_name}'
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'mkdir -p {shlex.quote(restore_dir)} && '
|
||||||
|
f'cd {shlex.quote(restore_dir)} && '
|
||||||
|
f'tar xzf {shlex.quote(remote_archive)} --strip-components=1',
|
||||||
|
timeout=60)
|
||||||
|
if r.returncode != 0:
|
||||||
|
raise BackupError(f'Extract failed: {r.stderr}')
|
||||||
|
complete_step('Extracting backup archive on VM', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Extracting backup archive on VM', False, str(e))
|
||||||
|
|
||||||
|
# Step 3: Restore K8s secrets and configmaps
|
||||||
|
if opts.get('restore_k8s', True):
|
||||||
|
add_step('Restoring K8s secrets and configmaps')
|
||||||
|
try:
|
||||||
|
d = f'/tmp/restore-{backup_name}'
|
||||||
|
for fname in ['secrets.yaml', 'configmaps.yaml']:
|
||||||
|
manifest = f'{d}/k8s-manifests/{fname}'
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'sudo kubectl apply -n {shlex.quote(str(ns))} -f {shlex.quote(manifest)} 2>/dev/null || true',
|
||||||
|
timeout=30)
|
||||||
|
if r.returncode != 0:
|
||||||
|
logger.warning(f'Could not apply {fname}: {r.stderr}')
|
||||||
|
complete_step('Restoring K8s secrets and configmaps', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Restoring K8s secrets and configmaps', False, str(e))
|
||||||
|
|
||||||
|
# Step 4: Restore battlegroup CRD and wait for pods
|
||||||
|
if opts.get('restore_battlegroup', True):
|
||||||
|
add_step('Applying battlegroup CRD')
|
||||||
|
try:
|
||||||
|
d = f'/tmp/restore-{backup_name}'
|
||||||
|
crd = f'{d}/k8s-manifests/battlegroup-crd.yaml'
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'sudo kubectl apply -f {shlex.quote(crd)}', timeout=60)
|
||||||
|
if r.returncode != 0:
|
||||||
|
raise BackupError(r.stderr)
|
||||||
|
complete_step('Applying battlegroup CRD', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Applying battlegroup CRD', False, str(e))
|
||||||
|
|
||||||
|
add_step('Waiting for pods to provision (up to 5 min)')
|
||||||
|
try:
|
||||||
|
for i in range(30):
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'sudo kubectl get pods -n {shlex.quote(str(ns))} --no-headers 2>/dev/null | '
|
||||||
|
f'grep -c -E "(dbdepl|mq-.*-sts)" || true', timeout=15)
|
||||||
|
if r.returncode == 0 and r.stdout.strip():
|
||||||
|
count = int(r.stdout.strip())
|
||||||
|
if count >= 2:
|
||||||
|
complete_step('Waiting for pods to provision', True)
|
||||||
|
break
|
||||||
|
time.sleep(10)
|
||||||
|
else:
|
||||||
|
complete_step('Waiting for pods to provision', False, 'Timed out')
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Waiting for pods to provision', False, str(e))
|
||||||
|
|
||||||
|
add_step('Waiting for DB pod to be Running')
|
||||||
|
try:
|
||||||
|
for i in range(30):
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db --no-headers '
|
||||||
|
f'-o custom-columns=STATUS:.status.phase 2>/dev/null | head -1',
|
||||||
|
timeout=15)
|
||||||
|
if 'Running' in r.stdout:
|
||||||
|
complete_step('Waiting for DB pod to be Running', True)
|
||||||
|
break
|
||||||
|
time.sleep(10)
|
||||||
|
else:
|
||||||
|
complete_step('Waiting for DB pod to be Running', False, 'DB pod did not start')
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Waiting for DB pod to be Running', False, str(e))
|
||||||
|
|
||||||
|
# Step 5: Import game database
|
||||||
|
if opts.get('restore_db', True):
|
||||||
|
add_step('Importing game database')
|
||||||
|
try:
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'cd {shlex.quote(restore_dir)} && '
|
||||||
|
f'/home/dune/.dune/bin/battlegroup import',
|
||||||
|
timeout=600)
|
||||||
|
if r.returncode != 0:
|
||||||
|
raise BackupError(r.stderr)
|
||||||
|
complete_step('Importing game database', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Importing game database', False, str(e))
|
||||||
|
|
||||||
|
# Step 6: Restore dashboard database schema
|
||||||
|
if opts.get('restore_dash_db', True):
|
||||||
|
add_step('Restoring dashboard schema (bans, chat, audit, settings)')
|
||||||
|
try:
|
||||||
|
dash_sql_path = self._backup_path(f'{backup_name}.tar.gz')
|
||||||
|
dash_sql_content = None
|
||||||
|
with tarfile.open(dash_sql_path, 'r:gz') as tar:
|
||||||
|
for m in tar.getmembers():
|
||||||
|
if m.name.endswith('dashboard-db.sql'):
|
||||||
|
with tar.extractfile(m) as f:
|
||||||
|
dash_sql_content = f.read()
|
||||||
|
break
|
||||||
|
if dash_sql_content:
|
||||||
|
b64_sql = base64.b64encode(dash_sql_content).decode()
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && '
|
||||||
|
f'echo {shlex.quote(b64_sql)} | base64 -d | '
|
||||||
|
f'sudo kubectl exec -n {shlex.quote(str(ns))} -i $dbpod -- psql -U postgres -d dune',
|
||||||
|
timeout=120)
|
||||||
|
if r.returncode != 0:
|
||||||
|
logger.warning(f'Dashboard DB restore warning: {r.stderr}')
|
||||||
|
complete_step('Restoring dashboard schema (bans, chat, audit, settings)', True)
|
||||||
|
else:
|
||||||
|
complete_step('Restoring dashboard schema (bans, chat, audit, settings)', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Restoring dashboard schema (bans, chat, audit, settings)', False, str(e))
|
||||||
|
|
||||||
|
if opts.get('restore_db', True) or opts.get('restore_dash_db', True):
|
||||||
|
add_step('Re-applying dashboard schema ownership')
|
||||||
|
try:
|
||||||
|
sql = ("ALTER SCHEMA dashboard OWNER TO dune;"
|
||||||
|
"GRANT ALL PRIVILEGES ON 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;")
|
||||||
|
r = ssh_cmd(
|
||||||
|
f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && '
|
||||||
|
f'sudo kubectl exec -n {shlex.quote(str(ns))} $dbpod -- psql -U postgres -d dune '
|
||||||
|
f'-c {shlex.quote(sql)}', timeout=30)
|
||||||
|
if r.returncode != 0:
|
||||||
|
logger.warning(f'Dashboard schema ownership warning: {r.stderr}')
|
||||||
|
complete_step('Re-applying dashboard schema ownership', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Re-applying dashboard schema ownership', False, str(e))
|
||||||
|
|
||||||
|
# Step 7: Apply ping fix if new IP provided
|
||||||
|
if opts.get('restore_ping_fix', True) and opts.get('new_ip'):
|
||||||
|
add_step('Applying HOST_DATACENTER ping fix')
|
||||||
|
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)
|
||||||
|
hostname = r.stdout.strip()
|
||||||
|
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,253}', hostname):
|
||||||
|
raise BackupError(f'Unexpected hostname: {hostname!r}')
|
||||||
|
for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']:
|
||||||
|
full_name = f'{ns}-{deploy_suffix}'
|
||||||
|
ssh_cmd(
|
||||||
|
f'sudo kubectl set env deploy/{shlex.quote(full_name)} -n {shlex.quote(str(ns))} '
|
||||||
|
f'HOST_DATACENTER_ID={shlex.quote(hostname)} '
|
||||||
|
f'HOST_DATACENTER_IP_ADDRESS={shlex.quote(new_ip)}',
|
||||||
|
timeout=30)
|
||||||
|
complete_step('Applying HOST_DATACENTER ping fix', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Applying HOST_DATACENTER ping fix', False, str(e))
|
||||||
|
|
||||||
|
# Step 8: Re-create RMQ dashboard_admin user
|
||||||
|
if opts.get('restore_rmq', True):
|
||||||
|
add_step('Re-creating RMQ dashboard_admin user on both instances')
|
||||||
|
try:
|
||||||
|
pw = self.settings.get('rabbitmq', {}).get('password', '')
|
||||||
|
for side in ['admin', 'game']:
|
||||||
|
pod_r = ssh_cmd(
|
||||||
|
f'sudo kubectl get pods -n {shlex.quote(str(ns))} -o name | grep mq-{side}-sts | head -1',
|
||||||
|
timeout=15)
|
||||||
|
if pod_r.returncode != 0 or not pod_r.stdout.strip():
|
||||||
|
logger.warning(f'No mq-{side} pod found')
|
||||||
|
continue
|
||||||
|
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 [
|
||||||
|
f'rabbitmqctl add_user dashboard_admin {shlex.quote(str(pw))}',
|
||||||
|
f'rabbitmqctl set_user_tags dashboard_admin administrator',
|
||||||
|
f'rabbitmqctl set_permissions -p / dashboard_admin ".*" ".*" ".*"',
|
||||||
|
f'rabbitmqctl eval '
|
||||||
|
f'\'application:set_env(rabbit, auth_backends, '
|
||||||
|
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)
|
||||||
|
complete_step('Re-creating RMQ dashboard_admin user on both instances', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Re-creating RMQ dashboard_admin user on both instances', False, str(e))
|
||||||
|
|
||||||
|
# Step 9: Restore settings.yaml locally
|
||||||
|
if opts.get('restore_settings', True):
|
||||||
|
add_step('Restoring dashboard settings.yaml locally')
|
||||||
|
try:
|
||||||
|
d = f'/tmp/restore-{backup_name}'
|
||||||
|
settings_file = f'{d}/settings.yaml'
|
||||||
|
r = ssh_cmd(f'cat {shlex.quote(settings_file)}', timeout=15)
|
||||||
|
if r.returncode == 0 and r.stdout.strip():
|
||||||
|
local_settings = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
||||||
|
'settings.yaml')
|
||||||
|
with open(local_settings, 'w') as f:
|
||||||
|
f.write(r.stdout)
|
||||||
|
complete_step('Restoring dashboard settings.yaml locally', True)
|
||||||
|
else:
|
||||||
|
complete_step('Restoring dashboard settings.yaml locally', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Restoring dashboard settings.yaml locally', False, str(e))
|
||||||
|
|
||||||
|
# Step 10: Cleanup
|
||||||
|
add_step('Cleaning up temporary files on VM')
|
||||||
|
try:
|
||||||
|
ssh_cmd(f'rm -rf {shlex.quote(restore_dir)} {shlex.quote(remote_archive)}',
|
||||||
|
timeout=15)
|
||||||
|
complete_step('Cleaning up temporary files on VM', True)
|
||||||
|
except Exception as e:
|
||||||
|
complete_step('Cleaning up temporary files on VM', False, str(e))
|
||||||
|
|
||||||
|
state['status'] = 'completed' if not state['errors'] else 'completed_with_errors'
|
||||||
|
state['progress'] = 100
|
||||||
|
state['completed_at'] = time.time()
|
||||||
@@ -99,12 +99,14 @@ class ChatService:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
if not namespace:
|
if not namespace:
|
||||||
logger.warning("Cannot catch up - kubernetes namespace not set")
|
# The API response already reports the failure to the UI.
|
||||||
|
logger.debug("Cannot catch up - kubernetes namespace not set")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
pod_name = self.k8s.get_text_router_pod()
|
pod_name = self.k8s.get_text_router_pod()
|
||||||
if not pod_name:
|
if not pod_name:
|
||||||
logger.warning("Cannot catch up - no text-router pod found")
|
# The API response already reports the failure to the UI.
|
||||||
|
logger.debug("Cannot catch up - no text-router pod found")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
logger.debug(f"Attempting to catch up chat from pod: {pod_name}")
|
logger.debug(f"Attempting to catch up chat from pod: {pod_name}")
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ class DatabaseService:
|
|||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
if self.pool is None:
|
if self.pool is None:
|
||||||
# Retry up to 10 times with 2s delays (20s total) to handle startup race conditions
|
# Retry up to 10 times with 2s delays (20s total) to handle startup race conditions
|
||||||
|
try:
|
||||||
for attempt in range(10):
|
for attempt in range(10):
|
||||||
try:
|
try:
|
||||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||||
@@ -35,6 +36,9 @@ class DatabaseService:
|
|||||||
else:
|
else:
|
||||||
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
||||||
self.pool = None
|
self.pool = None
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n Stopped during database startup.")
|
||||||
|
raise SystemExit(0)
|
||||||
return self.pool
|
return self.pool
|
||||||
|
|
||||||
def get_connection(self):
|
def get_connection(self):
|
||||||
@@ -155,6 +159,7 @@ class DashboardDatabaseService:
|
|||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
if self.pool is not None:
|
if self.pool is not None:
|
||||||
return self.pool
|
return self.pool
|
||||||
|
try:
|
||||||
for attempt in range(10):
|
for attempt in range(10):
|
||||||
try:
|
try:
|
||||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||||
@@ -182,6 +187,9 @@ class DashboardDatabaseService:
|
|||||||
else:
|
else:
|
||||||
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
self.pool = None
|
self.pool = None
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n Stopped during database startup.")
|
||||||
|
raise SystemExit(0)
|
||||||
return self.pool
|
return self.pool
|
||||||
|
|
||||||
def _ensure_database(self):
|
def _ensure_database(self):
|
||||||
|
|||||||
@@ -1,15 +1,23 @@
|
|||||||
"""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.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__)
|
||||||
|
|
||||||
|
# Internal port the BGD container listens on (used with service cluster IP)
|
||||||
|
_BGD_CONTAINER_PORT = 11717
|
||||||
|
|
||||||
|
|
||||||
class DirectorService:
|
class DirectorService:
|
||||||
"""Service for interacting with the game server's battlegroup director.
|
"""Service for interacting with the game server's battlegroup director.
|
||||||
@@ -27,6 +35,7 @@ class DirectorService:
|
|||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
self._bgd_svc_url = None # cached cluster URL for SSH fallback
|
||||||
resource_prefix = namespace
|
resource_prefix = namespace
|
||||||
for prefix in ['funcom-seabass-']:
|
for prefix in ['funcom-seabass-']:
|
||||||
if resource_prefix.startswith(prefix):
|
if resource_prefix.startswith(prefix):
|
||||||
@@ -35,9 +44,39 @@ class DirectorService:
|
|||||||
self.resource_prefix = resource_prefix
|
self.resource_prefix = resource_prefix
|
||||||
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
||||||
|
|
||||||
|
def _resolve_bgd_svc_url(self):
|
||||||
|
"""Find the BGD Service cluster IP via kubectl (stable across pod restarts)."""
|
||||||
|
out, err, rc = self.k8s.run('get svc -o name', timeout=10)
|
||||||
|
if rc != 0:
|
||||||
|
return None
|
||||||
|
for line in (out or '').split('\n'):
|
||||||
|
line = line.strip()
|
||||||
|
if 'bgd-svc' in line:
|
||||||
|
svc_name = line.split('/')[-1].strip()
|
||||||
|
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(
|
||||||
|
f'get svc {shlex.quote(svc_name)} -o jsonpath={{.spec.clusterIP}}', timeout=10)
|
||||||
|
if ip_rc == 0 and ip_out:
|
||||||
|
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)
|
||||||
|
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
|
||||||
|
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
|
||||||
|
return None
|
||||||
|
|
||||||
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
||||||
timeout: int = 15, raw_data: bool = False) -> str:
|
timeout: int = 15, raw_data: bool = False) -> str:
|
||||||
"""Execute HTTP request to director service via NodePort.
|
"""Execute HTTP request to director service.
|
||||||
|
|
||||||
|
Tries local HTTP first (SSH tunnel + kubectl port-forward).
|
||||||
|
Falls back to SSH + wget directly to the BGD service cluster IP,
|
||||||
|
which survives server restarts without needing a port-forward.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
path: URL path (e.g., '/v0/battlegroup').
|
path: URL path (e.g., '/v0/battlegroup').
|
||||||
@@ -67,8 +106,44 @@ class DirectorService:
|
|||||||
method=method
|
method=method
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Try local HTTP first (SSH tunnel + kubectl port-forward on VM)
|
||||||
|
try:
|
||||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
return resp.read().decode()
|
return resp.read().decode()
|
||||||
|
except (urllib.error.URLError, ConnectionError, OSError) as e:
|
||||||
|
logger.debug("Director local HTTP failed, trying SSH fallback: %s", e)
|
||||||
|
|
||||||
|
# Fallback: SSH to BGD service cluster IP (always works, no tunnel needed)
|
||||||
|
if not self._bgd_svc_url:
|
||||||
|
self._bgd_svc_url = self._resolve_bgd_svc_url()
|
||||||
|
if self._bgd_svc_url:
|
||||||
|
svc_url = f"{self._bgd_svc_url}{path}"
|
||||||
|
logger.debug("Director SSH fallback: %s %s", method, svc_url)
|
||||||
|
if method == 'GET':
|
||||||
|
out, err, rc = self.ssh.run(f'wget -qO- {shlex.quote(svc_url)}', timeout=timeout)
|
||||||
|
else:
|
||||||
|
body_bytes = None
|
||||||
|
if raw_data and isinstance(data, str):
|
||||||
|
body_bytes = data.encode()
|
||||||
|
elif data is not None:
|
||||||
|
body_bytes = json.dumps(data).encode()
|
||||||
|
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
|
||||||
|
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
|
||||||
|
self.ssh.run(f'echo {shlex.quote(body_b64)} | base64 -d > {shlex.quote(tmp)}', timeout=5)
|
||||||
|
try:
|
||||||
|
out, err, rc = self.ssh.run(
|
||||||
|
f'wget -qO- --post-file={shlex.quote(tmp)} '
|
||||||
|
f'--header="Content-Type: application/json" {shlex.quote(svc_url)}',
|
||||||
|
timeout=timeout)
|
||||||
|
finally:
|
||||||
|
self.ssh.run(f'rm -f {shlex.quote(tmp)}', timeout=5)
|
||||||
|
if rc == 0 and out:
|
||||||
|
return out
|
||||||
|
logger.warning("Director SSH fallback failed (rc=%d): %s",
|
||||||
|
rc, err[:100] if err else 'none')
|
||||||
|
self._bgd_svc_url = None # stale cache, re-resolve next time
|
||||||
|
|
||||||
|
raise ConnectionError("Connection refused: Director unreachable via local HTTP or SSH fallback")
|
||||||
|
|
||||||
# ── Director API methods ──────────────────────────────────────────
|
# ── Director API methods ──────────────────────────────────────────
|
||||||
|
|
||||||
@@ -181,8 +256,15 @@ class DirectorService:
|
|||||||
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||||
name = self._map_to_scale_name(map_name)
|
name = self._map_to_scale_name(map_name)
|
||||||
cm_out, cm_err, cm_rc = self.k8s.run(
|
cm_out, cm_err, cm_rc = self.k8s.run(
|
||||||
f'get serversetscale {name} -o json')
|
f'get serversetscale {name} -o json', quiet=True)
|
||||||
if cm_rc != 0 or not cm_out:
|
if cm_rc != 0 or not cm_out:
|
||||||
|
# A missing ServerSetScale just means the map has none; only
|
||||||
|
# unexpected failures deserve a warning.
|
||||||
|
if cm_rc != 0 and 'not found' not in (cm_err or '').lower():
|
||||||
|
logger.warning("ServerSetScale lookup failed for %s: %s",
|
||||||
|
map_name, (cm_err or '')[:150])
|
||||||
|
else:
|
||||||
|
logger.debug("No ServerSetScale for %s", map_name)
|
||||||
return None
|
return None
|
||||||
return json.loads(cm_out)
|
return json.loads(cm_out)
|
||||||
|
|
||||||
|
|||||||
+57
-6
@@ -1,6 +1,7 @@
|
|||||||
"""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__)
|
||||||
|
|
||||||
@@ -10,10 +11,10 @@ class K8sService:
|
|||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
|
||||||
def run(self, kubectl_command, timeout=30):
|
def run(self, kubectl_command, timeout=30, quiet=False):
|
||||||
full_cmd = f'sudo kubectl {kubectl_command} -n {self.namespace}'
|
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
|
||||||
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
|
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
|
||||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
result = self.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
|
||||||
out, err, rc = result
|
out, err, rc = result
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
||||||
@@ -30,6 +31,32 @@ 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:
|
||||||
@@ -60,6 +87,23 @@ class K8sService:
|
|||||||
return []
|
return []
|
||||||
return [d.strip() for d in (out or '').strip().split('\n') if d.strip()]
|
return [d.strip() for d in (out or '').strip().split('\n') if d.strip()]
|
||||||
|
|
||||||
|
def _parse_memory_gib(self, raw):
|
||||||
|
raw = raw.strip().upper()
|
||||||
|
if raw.endswith('KI'):
|
||||||
|
return round(int(raw[:-2]) / (1024 ** 3), 1)
|
||||||
|
if raw.endswith('MI'):
|
||||||
|
return round(int(raw[:-2]) / 1024, 1)
|
||||||
|
if raw.endswith('GI'):
|
||||||
|
return round(int(raw[:-2]), 1)
|
||||||
|
if raw.endswith('TI'):
|
||||||
|
return round(int(raw[:-2]) * 1024, 1)
|
||||||
|
if raw.endswith('PI'):
|
||||||
|
return round(int(raw[:-2]) * 1024 ** 2, 1)
|
||||||
|
try:
|
||||||
|
return round(int(raw) / (1024 ** 3), 1)
|
||||||
|
except ValueError:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
def get_node_metrics(self):
|
def get_node_metrics(self):
|
||||||
out, err, rc = self.run('top nodes')
|
out, err, rc = self.run('top nodes')
|
||||||
if rc == 0 and out.strip():
|
if rc == 0 and out.strip():
|
||||||
@@ -67,10 +111,17 @@ class K8sService:
|
|||||||
if len(lines) >= 2:
|
if len(lines) >= 2:
|
||||||
parts = lines[1].split()
|
parts = lines[1].split()
|
||||||
if len(parts) >= 4:
|
if len(parts) >= 4:
|
||||||
|
cpu_pct_str = parts[2]
|
||||||
|
mem_str = parts[3]
|
||||||
|
mem_pct_str = parts[4] if len(parts) >= 5 else ''
|
||||||
return {
|
return {
|
||||||
'cpu': parts[2],
|
'cpu': cpu_pct_str,
|
||||||
'memory': parts[3],
|
'memory': mem_str,
|
||||||
'cpu_pct': parts[1]
|
'cpu_pct': parts[1],
|
||||||
|
'cpu_num': float(cpu_pct_str.rstrip('%')),
|
||||||
|
'memory_gib': self._parse_memory_gib(mem_str),
|
||||||
|
'memory_pct': mem_pct_str,
|
||||||
|
'memory_pct_num': float(mem_pct_str.rstrip('%')) if mem_pct_str else 0.0,
|
||||||
}
|
}
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,497 @@
|
|||||||
|
"""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
|
||||||
@@ -199,7 +199,7 @@ class PlayerService:
|
|||||||
def get_player_detail(self, player_id):
|
def get_player_detail(self, player_id):
|
||||||
player = self.db.query("""
|
player = self.db.query("""
|
||||||
SELECT a.*, a.transform::text as transform_text,
|
SELECT a.*, a.transform::text as transform_text,
|
||||||
ea.id as account_id, ea.user as account_email, ea.platform_id,
|
ea.id as account_id, ea.user as account_email, acc.platform_id,
|
||||||
acc.funcom_id,
|
acc.funcom_id,
|
||||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
||||||
ps.online_status::text as online_status,
|
ps.online_status::text as online_status,
|
||||||
@@ -235,7 +235,8 @@ class PlayerService:
|
|||||||
FROM dune.actors WHERE id = %s
|
FROM dune.actors WHERE id = %s
|
||||||
""", [state_pawn_id], one=True) or {}
|
""", [state_pawn_id], one=True) or {}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Failed to get vitals: {e}")
|
# Missing pawn data is routine (page renders N/A instead).
|
||||||
|
logger.debug(f"Failed to get vitals: {e}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def get_player_guild(self, player_controller_id):
|
def get_player_guild(self, player_controller_id):
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""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 ''
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
"""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)
|
||||||
+83
-1
@@ -1,15 +1,32 @@
|
|||||||
"""SSH service - remote command execution via paramiko."""
|
"""SSH service - remote command execution via paramiko."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import threading
|
import threading
|
||||||
import paramiko
|
import paramiko
|
||||||
|
|
||||||
from app.utils.ssh_key import resolve_ssh_key
|
from app.utils.ssh_key import resolve_ssh_key
|
||||||
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
|
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
|
||||||
|
|
||||||
|
KEEPALIVE_INTERVAL = 15
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def known_hosts_path():
|
||||||
|
"""Location of the persisted known-hosts file.
|
||||||
|
|
||||||
|
Overridable via DUNE_KNOWN_HOSTS (used by tests). Host keys are saved
|
||||||
|
after the first successful connect, so later connects verify the host
|
||||||
|
instead of warning about unknown keys every time.
|
||||||
|
"""
|
||||||
|
override = os.environ.get('DUNE_KNOWN_HOSTS')
|
||||||
|
if override:
|
||||||
|
return override
|
||||||
|
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
return os.path.join(base_dir, 'internal-scripts', 'ssh', 'known_hosts')
|
||||||
|
|
||||||
|
|
||||||
class SSHService:
|
class SSHService:
|
||||||
"""SSH service using paramiko for connection reuse.
|
"""SSH service using paramiko for connection reuse.
|
||||||
|
|
||||||
@@ -37,9 +54,21 @@ class SSHService:
|
|||||||
transport = self._client.get_transport()
|
transport = self._client.get_transport()
|
||||||
if transport and transport.is_active():
|
if transport and transport.is_active():
|
||||||
return self._client
|
return self._client
|
||||||
|
logger.debug("SSH: closing stale client before reconnect")
|
||||||
|
try:
|
||||||
|
self._client.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
self._client = None
|
self._client = None
|
||||||
|
|
||||||
client = paramiko.SSHClient()
|
client = paramiko.SSHClient()
|
||||||
|
hosts_file = known_hosts_path()
|
||||||
|
try:
|
||||||
|
if os.path.exists(hosts_file):
|
||||||
|
client.load_host_keys(hosts_file)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"Could not load known hosts: {e}")
|
||||||
|
hosts_file = None
|
||||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
logger.debug("SSH host key verification policy set to AutoAddPolicy")
|
logger.debug("SSH host key verification policy set to AutoAddPolicy")
|
||||||
|
|
||||||
@@ -56,6 +85,15 @@ class SSHService:
|
|||||||
try:
|
try:
|
||||||
client.connect(**connect_kwargs)
|
client.connect(**connect_kwargs)
|
||||||
logger.debug("SSH connection established to %s@%s", self.user, self.host)
|
logger.debug("SSH connection established to %s@%s", self.user, self.host)
|
||||||
|
if hosts_file:
|
||||||
|
try:
|
||||||
|
os.makedirs(os.path.dirname(hosts_file), exist_ok=True)
|
||||||
|
client.save_host_keys(hosts_file)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"Could not save known hosts: {e}")
|
||||||
|
transport = client.get_transport()
|
||||||
|
if transport:
|
||||||
|
transport.set_keepalive(KEEPALIVE_INTERVAL)
|
||||||
except paramiko.AuthenticationException:
|
except paramiko.AuthenticationException:
|
||||||
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
||||||
raise
|
raise
|
||||||
@@ -69,12 +107,15 @@ class SSHService:
|
|||||||
self._client = client
|
self._client = client
|
||||||
return self._client
|
return self._client
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
"""Execute a remote command via SSH.
|
"""Execute a remote command via SSH.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
command: The shell command to execute.
|
command: The shell command to execute.
|
||||||
timeout: Maximum time in seconds to wait for the command.
|
timeout: Maximum time in seconds to wait for the command.
|
||||||
|
quiet: When True, expected non-zero results (e.g. probing for
|
||||||
|
an optional resource) are logged at debug level instead of
|
||||||
|
warning. Return values are unchanged.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Tuple of (stdout, stderr, return_code).
|
Tuple of (stdout, stderr, return_code).
|
||||||
@@ -85,6 +126,7 @@ 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()
|
||||||
@@ -92,12 +134,18 @@ 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.debug(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||||
|
else:
|
||||||
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
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.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')
|
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:
|
||||||
@@ -111,6 +159,40 @@ 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.
|
||||||
|
|
||||||
|
|||||||
+330
-89
@@ -1,6 +1,18 @@
|
|||||||
"""Update service - checks GitHub for new releases and applies updates"""
|
"""Update service - channel-aware self updates from GitHub Releases.
|
||||||
|
|
||||||
|
Version source of truth: the committed VERSION file (e.g. ``0.7.5`` for
|
||||||
|
stable, ``0.7.5-experimental`` for experimental). The channel is the suffix.
|
||||||
|
|
||||||
|
Rules (all enforced server-side):
|
||||||
|
- experimental installs track ``vX.Y.Z-experimental`` releases (matched
|
||||||
|
case-insensitively); stable installs track exact ``vX.Y.Z`` releases.
|
||||||
|
- An update target must be newer than OR equal to the running version
|
||||||
|
(equal = reinstall/repair). Older versions are always refused.
|
||||||
|
- Checking is automatic (background thread); installing is always manual.
|
||||||
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
@@ -11,7 +23,7 @@ import urllib.request
|
|||||||
import zipfile
|
import zipfile
|
||||||
import tempfile
|
import tempfile
|
||||||
import subprocess
|
import subprocess
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -28,40 +40,155 @@ PROTECTED_PATHS = {
|
|||||||
'.env',
|
'.env',
|
||||||
}
|
}
|
||||||
|
|
||||||
# File extensions that are always safe to overwrite
|
_VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$")
|
||||||
SAFE_EXTENSIONS = {'.py', '.html', '.css', '.js', '.sh', '.ps1', '.md', '.txt', '.yaml', '.yml', '.json', '.ini', '.cfg'}
|
_STABLE_RE = re.compile(r"^v\d+\.\d+\.\d+$", re.IGNORECASE)
|
||||||
|
_EXPERIMENTAL_RE = re.compile(r"^v\d+\.\d+\.\d+-experimental$", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_version(value):
|
||||||
|
"""Parse 'v0.7.5-experimental' -> ((0, 7, 5), 'experimental').
|
||||||
|
|
||||||
|
Returns None for anything that is not a plain dotted version with an
|
||||||
|
optional single suffix. Never raises.
|
||||||
|
"""
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
match = _VERSION_RE.fullmatch(str(value).strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
numbers = (int(match.group(1)), int(match.group(2)), int(match.group(3)))
|
||||||
|
return numbers, (match.group(4) or '')
|
||||||
|
|
||||||
|
|
||||||
|
def channel_of(version):
|
||||||
|
"""'experimental' for *-experimental versions, else 'stable'."""
|
||||||
|
parsed = parse_version(version)
|
||||||
|
if parsed and parsed[1].lower() == 'experimental':
|
||||||
|
return 'experimental'
|
||||||
|
return 'stable'
|
||||||
|
|
||||||
|
|
||||||
|
def compare_versions(a, b):
|
||||||
|
"""Compare numeric parts only. Returns -1, 0 or 1. Unknowns sort last."""
|
||||||
|
pa, pb = parse_version(a), parse_version(b)
|
||||||
|
if pa is None and pb is None:
|
||||||
|
return 0
|
||||||
|
if pa is None:
|
||||||
|
return -1
|
||||||
|
if pb is None:
|
||||||
|
return 1
|
||||||
|
if pa[0] < pb[0]:
|
||||||
|
return -1
|
||||||
|
if pa[0] > pb[0]:
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def release_matches_channel(tag, channel):
|
||||||
|
"""True when a release tag belongs to the channel (case-insensitive)."""
|
||||||
|
tag = str(tag or '')
|
||||||
|
if channel == 'experimental':
|
||||||
|
return bool(_EXPERIMENTAL_RE.fullmatch(tag))
|
||||||
|
return bool(_STABLE_RE.fullmatch(tag))
|
||||||
|
|
||||||
|
|
||||||
class UpdateService:
|
class UpdateService:
|
||||||
def __init__(self, project_root):
|
def __init__(self, project_root):
|
||||||
self.project_root = project_root
|
self.project_root = project_root
|
||||||
self._update_available = False
|
self._current_version = self._read_local_version()
|
||||||
self._latest_sha = None
|
self._channel = channel_of(self._current_version)
|
||||||
self._current_sha = None
|
self._latest = None # {'version', 'tag', 'notes', 'zipball_url'}
|
||||||
|
self._other_latest = None
|
||||||
|
self._releases = {'experimental': [], 'stable': []} # per-channel lists, newest first
|
||||||
self._last_check = 0
|
self._last_check = 0
|
||||||
self._check_interval = 1800 # 30 minutes
|
self._check_interval = 1800 # 30 minutes
|
||||||
self._update_in_progress = False
|
self._update_in_progress = False
|
||||||
self._update_status = None
|
self._update_status = None
|
||||||
self._current_branch = self._detect_branch()
|
self._preview = None # {'version', 'notes'} - in-memory test helper
|
||||||
|
|
||||||
def _detect_branch(self):
|
# ── version / channel ────────────────────────────────────────────
|
||||||
"""Detect the current git branch or ZIP branch from folder name."""
|
|
||||||
|
def _read_local_version(self):
|
||||||
try:
|
try:
|
||||||
branch = subprocess.check_output(
|
with open(os.path.join(self.project_root, 'VERSION')) as f:
|
||||||
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
|
version = f.read().strip().replace('\r', '').replace('\n', '')
|
||||||
cwd=self.project_root, stderr=subprocess.DEVNULL
|
if parse_version(version):
|
||||||
).decode().strip()
|
return version
|
||||||
if branch:
|
|
||||||
return branch
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
return '0.0.0'
|
||||||
|
|
||||||
folder_name = os.path.basename(self.project_root).lower()
|
@property
|
||||||
if 'nightly' in folder_name:
|
def current_version(self):
|
||||||
return 'nightly'
|
return self._current_version
|
||||||
if 'beta' in folder_name:
|
|
||||||
return 'beta'
|
@property
|
||||||
return 'main'
|
def channel(self):
|
||||||
|
return self._channel
|
||||||
|
|
||||||
|
# ── silence state (backups/update-silence.json) ──────────────────
|
||||||
|
|
||||||
|
def _silence_path(self):
|
||||||
|
return os.path.join(self.project_root, 'backups', 'update-silence.json')
|
||||||
|
|
||||||
|
def get_silence(self):
|
||||||
|
try:
|
||||||
|
with open(self._silence_path()) as f:
|
||||||
|
stored = json.load(f) or {}
|
||||||
|
return {
|
||||||
|
'silenced_versions': list(stored.get('silenced_versions', [])),
|
||||||
|
'silence_all': bool(stored.get('silence_all', False)),
|
||||||
|
}
|
||||||
|
except (FileNotFoundError, ValueError, OSError):
|
||||||
|
return {'silenced_versions': [], 'silence_all': False}
|
||||||
|
|
||||||
|
def _save_silence(self, state):
|
||||||
|
try:
|
||||||
|
os.makedirs(os.path.dirname(self._silence_path()), exist_ok=True)
|
||||||
|
with open(self._silence_path(), 'w') as f:
|
||||||
|
json.dump({
|
||||||
|
'silenced_versions': list(state.get('silenced_versions', [])),
|
||||||
|
'silence_all': bool(state.get('silence_all', False)),
|
||||||
|
}, f, indent=2)
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning(f'Update silence: could not save: {e}')
|
||||||
|
return self.get_silence()
|
||||||
|
|
||||||
|
def silence_version(self, version):
|
||||||
|
state = self.get_silence()
|
||||||
|
version = str(version or '').strip()
|
||||||
|
if version and version not in state['silenced_versions']:
|
||||||
|
state['silenced_versions'].append(version)
|
||||||
|
return self._save_silence(state)
|
||||||
|
|
||||||
|
def unsilence_version(self, version):
|
||||||
|
state = self.get_silence()
|
||||||
|
version = str(version or '').strip()
|
||||||
|
if version in state['silenced_versions']:
|
||||||
|
state['silenced_versions'].remove(version)
|
||||||
|
return self._save_silence(state)
|
||||||
|
|
||||||
|
def set_silence_all(self, enabled):
|
||||||
|
state = self.get_silence()
|
||||||
|
state['silence_all'] = bool(enabled)
|
||||||
|
return self._save_silence(state)
|
||||||
|
|
||||||
|
def clear_silence(self):
|
||||||
|
return self._save_silence({'silenced_versions': [], 'silence_all': False})
|
||||||
|
|
||||||
|
# ── preview helper (banner testing only, never installable) ─────
|
||||||
|
|
||||||
|
def set_preview(self, version, notes=''):
|
||||||
|
version = str(version or '').strip()
|
||||||
|
if not parse_version(version):
|
||||||
|
raise ValueError('Preview version is not a valid version number.')
|
||||||
|
self._preview = {'version': version, 'notes': str(notes or '')}
|
||||||
|
return dict(self._preview)
|
||||||
|
|
||||||
|
def clear_preview(self):
|
||||||
|
self._preview = None
|
||||||
|
|
||||||
|
# ── background checker ───────────────────────────────────────────
|
||||||
|
|
||||||
def start_checker(self):
|
def start_checker(self):
|
||||||
"""Start background update checker thread."""
|
"""Start background update checker thread."""
|
||||||
@@ -78,107 +205,219 @@ class UpdateService:
|
|||||||
logger.debug(f"Update check failed: {e}")
|
logger.debug(f"Update check failed: {e}")
|
||||||
time.sleep(self._check_interval)
|
time.sleep(self._check_interval)
|
||||||
|
|
||||||
def check_for_updates(self):
|
def _fetch_releases(self):
|
||||||
"""Check GitHub for new commits."""
|
"""All releases from GitHub (follows pagination)."""
|
||||||
try:
|
releases = []
|
||||||
branch = self._current_branch
|
url = f"{GITHUB_API}/releases?per_page=100"
|
||||||
git_dir = os.path.join(self.project_root, '.git')
|
while url:
|
||||||
if os.path.isdir(git_dir):
|
req = urllib.request.Request(url)
|
||||||
# Git clone: compare local HEAD to origin/<branch>
|
|
||||||
subprocess.run(
|
|
||||||
['git', 'fetch', 'origin', branch, '--quiet'],
|
|
||||||
cwd=self.project_root, stderr=subprocess.DEVNULL, timeout=15
|
|
||||||
)
|
|
||||||
local_sha = subprocess.check_output(
|
|
||||||
['git', 'rev-parse', 'HEAD'],
|
|
||||||
cwd=self.project_root, stderr=subprocess.DEVNULL
|
|
||||||
).decode().strip()[:7]
|
|
||||||
remote_sha = subprocess.check_output(
|
|
||||||
['git', 'rev-parse', f'origin/{branch}'],
|
|
||||||
cwd=self.project_root, stderr=subprocess.DEVNULL
|
|
||||||
).decode().strip()[:7]
|
|
||||||
else:
|
|
||||||
# ZIP download: compare VERSION file to GitHub API
|
|
||||||
req = urllib.request.Request(f"{GITHUB_API}/commits/{branch}")
|
|
||||||
req.add_header('Accept', 'application/vnd.github.v3+json')
|
req.add_header('Accept', 'application/vnd.github.v3+json')
|
||||||
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
||||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||||
data = json.loads(resp.read().decode())
|
releases.extend(json.loads(resp.read().decode()))
|
||||||
remote_sha = data['sha'][:7]
|
url = self._next_page(resp.headers.get('Link', ''))
|
||||||
|
return releases
|
||||||
|
|
||||||
version_file = os.path.join(self.project_root, 'VERSION')
|
@staticmethod
|
||||||
if os.path.exists(version_file):
|
def _next_page(link_header):
|
||||||
with open(version_file) as f:
|
for part in (link_header or '').split(','):
|
||||||
local_sha = f.read().strip().replace('\r', '').replace('\n', '')[:7]
|
segments = part.split(';')
|
||||||
else:
|
if len(segments) == 2 and 'rel="next"' in segments[1]:
|
||||||
# First run after ZIP download: record current version
|
return segments[0].strip().strip('<>')
|
||||||
local_sha = remote_sha
|
return ''
|
||||||
with open(version_file, 'w') as f:
|
|
||||||
f.write(remote_sha + '\n')
|
|
||||||
|
|
||||||
self._latest_sha = remote_sha
|
@staticmethod
|
||||||
self._current_sha = local_sha
|
def _collect_channel(releases, channel):
|
||||||
self._update_available = remote_sha != local_sha and remote_sha != ""
|
"""All releases for a channel, newest first.
|
||||||
|
|
||||||
|
Each entry is {'version', 'tag', 'notes', 'zipball_url'}.
|
||||||
|
Drafts, non-matching tags and unparsable versions are skipped.
|
||||||
|
"""
|
||||||
|
found = []
|
||||||
|
for release in releases:
|
||||||
|
if not isinstance(release, dict) or release.get('draft'):
|
||||||
|
continue
|
||||||
|
tag = str(release.get('tag_name') or '')
|
||||||
|
if not release_matches_channel(tag, channel):
|
||||||
|
continue
|
||||||
|
parsed = parse_version(tag)
|
||||||
|
if parsed is None:
|
||||||
|
continue
|
||||||
|
version = tag[1:] if tag.lower().startswith('v') else tag
|
||||||
|
found.append({
|
||||||
|
'version': version,
|
||||||
|
'tag': tag,
|
||||||
|
'notes': str(release.get('body') or ''),
|
||||||
|
'zipball_url': str(release.get('zipball_url') or ''),
|
||||||
|
})
|
||||||
|
found.sort(key=lambda e: parse_version(e['version'])[0], reverse=True)
|
||||||
|
return found
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _pick_latest(releases, channel):
|
||||||
|
"""Newest release for a channel. Returns entry dict or None."""
|
||||||
|
collected = UpdateService._collect_channel(releases, channel)
|
||||||
|
return collected[0] if collected else None
|
||||||
|
|
||||||
|
def check_for_updates(self):
|
||||||
|
"""Refresh latest-version info for our channel (and the other one)."""
|
||||||
|
try:
|
||||||
|
releases = self._fetch_releases()
|
||||||
|
other = 'stable' if self._channel == 'experimental' else 'experimental'
|
||||||
|
self._releases = {
|
||||||
|
'experimental': self._collect_channel(releases, 'experimental'),
|
||||||
|
'stable': self._collect_channel(releases, 'stable'),
|
||||||
|
}
|
||||||
|
self._latest = (self._releases[self._channel][0]
|
||||||
|
if self._releases[self._channel] else None)
|
||||||
|
self._other_latest = (self._releases[other][0]
|
||||||
|
if self._releases[other] else None)
|
||||||
self._last_check = time.time()
|
self._last_check = time.time()
|
||||||
logger.info(f"Update check ({branch}): {'available' if self._update_available else 'up to date'} (local={local_sha}, remote={remote_sha})")
|
if self._latest:
|
||||||
|
logger.info(
|
||||||
|
f"Update check ({self._channel}): latest={self._latest['version']} "
|
||||||
|
f"current={self._current_version}")
|
||||||
|
else:
|
||||||
|
logger.info(f"Update check ({self._channel}): no releases found")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug(f"Update check error: {e}")
|
logger.debug(f"Update check error: {e}")
|
||||||
|
|
||||||
|
def _is_newer_or_same(self, version):
|
||||||
|
return compare_versions(version, self._current_version) >= 0
|
||||||
|
|
||||||
|
def status(self):
|
||||||
|
"""Full status payload for the banner/API."""
|
||||||
|
silence = self.get_silence()
|
||||||
|
latest = dict(self._latest) if self._latest else None
|
||||||
|
available = bool(
|
||||||
|
latest and self._is_newer_or_same(latest['version'])
|
||||||
|
and compare_versions(latest['version'], self._current_version) != 0)
|
||||||
|
other = dict(self._other_latest) if self._other_latest else None
|
||||||
|
show_other = bool(
|
||||||
|
other and other['version'] != (latest['version'] if latest else None)
|
||||||
|
and self._is_newer_or_same(other['version']))
|
||||||
|
# Per-channel release lists for the version picker (newest first).
|
||||||
|
# zipball URLs stay server-side; the panel only needs version/notes.
|
||||||
|
lists = {}
|
||||||
|
for channel, entries in (self._releases or {}).items():
|
||||||
|
lists[channel] = [
|
||||||
|
{'version': e['version'], 'tag': e['tag'],
|
||||||
|
'notes': e['notes']}
|
||||||
|
for e in entries
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
'current_version': self._current_version,
|
||||||
|
'channel': self._channel,
|
||||||
|
'available': available,
|
||||||
|
'latest': latest,
|
||||||
|
'releases': lists,
|
||||||
|
'other_channel': {
|
||||||
|
'channel': 'stable' if self._channel == 'experimental' else 'experimental',
|
||||||
|
'latest': other,
|
||||||
|
'available': show_other,
|
||||||
|
},
|
||||||
|
'preview': dict(self._preview) if self._preview else None,
|
||||||
|
'silenced_versions': silence['silenced_versions'],
|
||||||
|
'silence_all': silence['silence_all'],
|
||||||
|
'update_in_progress': self._update_in_progress,
|
||||||
|
'update_status': self._update_status,
|
||||||
|
'last_check': self._last_check,
|
||||||
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def update_available(self):
|
def update_available(self):
|
||||||
return self._update_available
|
status = self.status()
|
||||||
|
return status['available'] or status['preview'] is not None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def update_status(self):
|
def update_status(self):
|
||||||
return self._update_status
|
return self._update_status
|
||||||
|
|
||||||
def apply_update(self):
|
# ── apply ────────────────────────────────────────────────────────
|
||||||
"""Download and apply the latest update."""
|
|
||||||
|
def _find_release(self, version):
|
||||||
|
"""Find a known release matching a version string exactly."""
|
||||||
|
for entry in (self._latest, self._other_latest):
|
||||||
|
if entry and entry['version'] == version:
|
||||||
|
return entry
|
||||||
|
for entries in (self._releases or {}).values():
|
||||||
|
for entry in entries:
|
||||||
|
if entry['version'] == version:
|
||||||
|
return entry
|
||||||
|
return None
|
||||||
|
|
||||||
|
def apply_update(self, version=None):
|
||||||
|
"""Download and apply a release. Version must be known and not older."""
|
||||||
if self._update_in_progress:
|
if self._update_in_progress:
|
||||||
return False, "Update already in progress"
|
return False, "Update already in progress"
|
||||||
|
|
||||||
|
target = str(version or '').strip()
|
||||||
|
if not target:
|
||||||
|
# Default: newest for our own channel.
|
||||||
|
if not self._latest:
|
||||||
|
return False, "No release found for this channel"
|
||||||
|
target = self._latest['version']
|
||||||
|
|
||||||
|
if parse_version(target) is None:
|
||||||
|
return False, "Invalid version number"
|
||||||
|
if not self._is_newer_or_same(target):
|
||||||
|
return False, (
|
||||||
|
f"Refusing downgrade: {target} is older than "
|
||||||
|
f"the running {self._current_version}")
|
||||||
|
entry = self._find_release(target)
|
||||||
|
if entry is None:
|
||||||
|
# Refresh once in case a release landed since the last check.
|
||||||
|
self.check_for_updates()
|
||||||
|
entry = self._find_release(target)
|
||||||
|
if entry is None:
|
||||||
|
return False, f"Unknown version: {target} (not a published release)"
|
||||||
|
if not entry.get('zipball_url'):
|
||||||
|
return False, "Release has no downloadable archive"
|
||||||
|
|
||||||
self._update_in_progress = True
|
self._update_in_progress = True
|
||||||
self._update_status = "Downloading update..."
|
self._update_status = f"Downloading {target}..."
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Download latest zip from the detected branch
|
req = urllib.request.Request(entry['zipball_url'])
|
||||||
branch = self._current_branch
|
req.add_header('Accept', 'application/vnd.github.v3+json')
|
||||||
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/{branch}.zip"
|
|
||||||
req = urllib.request.Request(zip_url)
|
|
||||||
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
||||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
with urllib.request.urlopen(req, timeout=120) as resp:
|
||||||
zip_data = resp.read()
|
zip_data = resp.read()
|
||||||
|
if not zip_data.startswith(b'PK\x03\x04'):
|
||||||
|
raise ValueError("Downloaded file is not a zip archive")
|
||||||
|
|
||||||
self._update_status = "Extracting update..."
|
self._update_status = "Extracting update..."
|
||||||
|
|
||||||
# Extract to temp directory
|
|
||||||
temp_dir = tempfile.mkdtemp(prefix='dune_update_')
|
temp_dir = tempfile.mkdtemp(prefix='dune_update_')
|
||||||
zip_path = os.path.join(temp_dir, 'update.zip')
|
zip_path = os.path.join(temp_dir, 'update.zip')
|
||||||
with open(zip_path, 'wb') as f:
|
with open(zip_path, 'wb') as f:
|
||||||
f.write(zip_data)
|
f.write(zip_data)
|
||||||
|
|
||||||
with zipfile.ZipFile(zip_path, 'r') as zf:
|
with zipfile.ZipFile(zip_path, 'r') as zf:
|
||||||
|
# Reject archives with absolute paths or parent escapes.
|
||||||
|
for member in zf.namelist():
|
||||||
|
if member.startswith('/') or '..' in member.split('/'):
|
||||||
|
raise ValueError(f"Unsafe archive entry: {member!r}")
|
||||||
zf.extractall(temp_dir)
|
zf.extractall(temp_dir)
|
||||||
|
|
||||||
# Find the extracted folder (e.g., dune-dashboard-main)
|
extracted = [d for d in os.listdir(temp_dir)
|
||||||
extracted = [d for d in os.listdir(temp_dir) if os.path.isdir(os.path.join(temp_dir, d)) and d != '__MACOSX']
|
if os.path.isdir(os.path.join(temp_dir, d))
|
||||||
|
and d != '__MACOSX']
|
||||||
if not extracted:
|
if not extracted:
|
||||||
return False, "Failed to extract update"
|
return False, "Failed to extract update"
|
||||||
|
|
||||||
source_dir = os.path.join(temp_dir, extracted[0])
|
source_dir = os.path.join(temp_dir, extracted[0])
|
||||||
|
|
||||||
# Create backup
|
backup_dir = os.path.join(
|
||||||
backup_dir = os.path.join(self.project_root, 'backups', f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
|
self.project_root, 'backups',
|
||||||
|
f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
|
||||||
os.makedirs(backup_dir, exist_ok=True)
|
os.makedirs(backup_dir, exist_ok=True)
|
||||||
|
|
||||||
# Copy files, skipping protected paths
|
|
||||||
self._update_status = "Applying files..."
|
self._update_status = "Applying files..."
|
||||||
files_updated = 0
|
files_updated = 0
|
||||||
for root, dirs, files in os.walk(source_dir):
|
for root, dirs, files in os.walk(source_dir):
|
||||||
rel_root = os.path.relpath(root, source_dir)
|
rel_root = os.path.relpath(root, source_dir)
|
||||||
target_root = os.path.join(self.project_root, rel_root)
|
target_root = os.path.join(self.project_root, rel_root)
|
||||||
|
|
||||||
# Skip protected directories
|
|
||||||
if any(p in PROTECTED_PATHS for p in rel_root.split(os.sep)):
|
if any(p in PROTECTED_PATHS for p in rel_root.split(os.sep)):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -190,11 +429,9 @@ class UpdateService:
|
|||||||
src_file = os.path.join(root, file)
|
src_file = os.path.join(root, file)
|
||||||
dst_file = os.path.join(target_root, file)
|
dst_file = os.path.join(target_root, file)
|
||||||
|
|
||||||
# Skip protected files
|
|
||||||
if file in PROTECTED_PATHS:
|
if file in PROTECTED_PATHS:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Backup existing file if it exists
|
|
||||||
if os.path.exists(dst_file):
|
if os.path.exists(dst_file):
|
||||||
backup_file = os.path.join(backup_dir, rel_root, file)
|
backup_file = os.path.join(backup_dir, rel_root, file)
|
||||||
os.makedirs(os.path.dirname(backup_file), exist_ok=True)
|
os.makedirs(os.path.dirname(backup_file), exist_ok=True)
|
||||||
@@ -203,18 +440,15 @@ class UpdateService:
|
|||||||
shutil.copy2(src_file, dst_file)
|
shutil.copy2(src_file, dst_file)
|
||||||
files_updated += 1
|
files_updated += 1
|
||||||
|
|
||||||
# Cleanup temp
|
|
||||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
# Update VERSION file to match new version
|
with open(os.path.join(self.project_root, 'VERSION'), 'w') as f:
|
||||||
version_file = os.path.join(self.project_root, 'VERSION')
|
f.write(target + '\n')
|
||||||
with open(version_file, 'w') as f:
|
|
||||||
f.write(self._latest_sha + '\n')
|
|
||||||
|
|
||||||
|
self._current_version = target
|
||||||
|
self._channel = channel_of(target)
|
||||||
self._update_status = f"Update applied! {files_updated} files updated. Restarting..."
|
self._update_status = f"Update applied! {files_updated} files updated. Restarting..."
|
||||||
self._update_available = False
|
|
||||||
|
|
||||||
# Restart the application
|
|
||||||
self._restart_app()
|
self._restart_app()
|
||||||
|
|
||||||
return True, f"Update applied successfully ({files_updated} files)"
|
return True, f"Update applied successfully ({files_updated} files)"
|
||||||
@@ -226,13 +460,20 @@ class UpdateService:
|
|||||||
return False, str(e)
|
return False, str(e)
|
||||||
|
|
||||||
def _restart_app(self):
|
def _restart_app(self):
|
||||||
"""Restart the dashboard via the launcher script to preserve SSH/DB tunnels."""
|
"""Restart the dashboard through the launcher in auto-start mode.
|
||||||
|
|
||||||
|
The launcher re-establishes SSH tunnels and port-forwards, then goes
|
||||||
|
straight into the dashboard without stopping at the selection menu.
|
||||||
|
The old process exits below, so the port is free when the new one
|
||||||
|
binds.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
if os.name == 'nt':
|
if os.name == 'nt':
|
||||||
launcher = os.path.join(self.project_root, 'launcher.ps1')
|
launcher = os.path.join(self.project_root, 'launcher.ps1')
|
||||||
if os.path.exists(launcher):
|
if os.path.exists(launcher):
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', launcher],
|
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
|
||||||
|
'-File', launcher, '-AutoStart'],
|
||||||
creationflags=subprocess.CREATE_NEW_CONSOLE
|
creationflags=subprocess.CREATE_NEW_CONSOLE
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -240,7 +481,7 @@ class UpdateService:
|
|||||||
else:
|
else:
|
||||||
launcher = os.path.join(self.project_root, 'start.sh')
|
launcher = os.path.join(self.project_root, 'start.sh')
|
||||||
if os.path.exists(launcher):
|
if os.path.exists(launcher):
|
||||||
subprocess.Popen(['bash', launcher], start_new_session=True)
|
subprocess.Popen(['bash', launcher, '--auto-start'], start_new_session=True)
|
||||||
else:
|
else:
|
||||||
subprocess.Popen([sys.executable, os.path.join(self.project_root, 'run.py')], start_new_session=True)
|
subprocess.Popen([sys.executable, os.path.join(self.project_root, 'run.py')], start_new_session=True)
|
||||||
os._exit(0)
|
os._exit(0)
|
||||||
|
|||||||
+23
-1
@@ -74,6 +74,7 @@ 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'),
|
||||||
@@ -81,5 +82,26 @@ NAV_PAGES = [
|
|||||||
('/guilds', 'Guilds'),
|
('/guilds', 'Guilds'),
|
||||||
('/buildings', 'Buildings'),
|
('/buildings', 'Buildings'),
|
||||||
('/map', 'Map'),
|
('/map', 'Map'),
|
||||||
('/admin-experimental', 'Experimental'),
|
]
|
||||||
|
|
||||||
|
NAV_GROUPS = [
|
||||||
|
('/', 'Overview'),
|
||||||
|
('Server', [
|
||||||
|
('/server', 'Server'),
|
||||||
|
('/director', 'Director'),
|
||||||
|
('/shell', 'Shell'),
|
||||||
|
('/files', 'Files'),
|
||||||
|
('/backup', 'Backup'),
|
||||||
|
]),
|
||||||
|
('Players', [
|
||||||
|
('/players', 'Players'),
|
||||||
|
('/vehicles', 'Vehicles'),
|
||||||
|
('/guilds', 'Guilds'),
|
||||||
|
('/buildings', 'Buildings'),
|
||||||
|
]),
|
||||||
|
('World', [
|
||||||
|
('/events', 'Events'),
|
||||||
|
('/chat', 'Chat'),
|
||||||
|
('/map', 'Map'),
|
||||||
|
]),
|
||||||
]
|
]
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Human-readable summaries for game event log entries.
|
||||||
|
|
||||||
|
Event types arrive as opaque numeric codes; the meaning lives in the
|
||||||
|
``custom_data`` JSONB payload. Labels below were decoded from live data.
|
||||||
|
Unknown codes fall back to "Event <n>" so new types never break the page.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
GAME_EVENT_LABELS = {
|
||||||
|
0: 'Death',
|
||||||
|
10: 'Build placed',
|
||||||
|
13: 'Shield change',
|
||||||
|
19: 'Totem switch',
|
||||||
|
20: 'Vehicle damage',
|
||||||
|
23: 'Vehicle event',
|
||||||
|
95: 'Totem power',
|
||||||
|
97: 'Permission change',
|
||||||
|
99: 'Vehicle stored',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def event_label(event_type):
|
||||||
|
"""Short label for a numeric event type."""
|
||||||
|
try:
|
||||||
|
return GAME_EVENT_LABELS.get(int(event_type), f'Event {event_type}')
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return f'Event {event_type}'
|
||||||
|
|
||||||
|
|
||||||
|
def clean_name(value):
|
||||||
|
"""Strip game ## prefixes; None/empty -> ''."""
|
||||||
|
if not value or value in ('None', '!!act#0'):
|
||||||
|
return ''
|
||||||
|
text = str(value)
|
||||||
|
while text.startswith('#'):
|
||||||
|
text = text[1:]
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _payload(custom_data):
|
||||||
|
"""custom_data as a dict (psycopg2 returns JSONB as dict already)."""
|
||||||
|
if not custom_data:
|
||||||
|
return {}
|
||||||
|
if isinstance(custom_data, dict):
|
||||||
|
return custom_data
|
||||||
|
try:
|
||||||
|
parsed = json.loads(custom_data)
|
||||||
|
return parsed if isinstance(parsed, dict) else {}
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def summarize_game_event(event_type, custom_data):
|
||||||
|
"""One-line human summary of a game event. Never raises."""
|
||||||
|
try:
|
||||||
|
data = _payload(custom_data)
|
||||||
|
get = lambda *keys: next(
|
||||||
|
(clean_name(data.get(k)) for k in keys if clean_name(data.get(k))), '')
|
||||||
|
|
||||||
|
if event_type == 0: # Death
|
||||||
|
killer = get('m_KillerType') or 'Unknown'
|
||||||
|
damage = get('m_DamageType')
|
||||||
|
detail = f'killed by {killer}'
|
||||||
|
if damage and damage != 'None':
|
||||||
|
detail += f' ({damage})'
|
||||||
|
return detail
|
||||||
|
if event_type == 10: # Build placed
|
||||||
|
who = get('m_CauserType')
|
||||||
|
what = get('m_BuildableName')
|
||||||
|
return f'{who or "Someone"} placed {what or "a building"}'.strip()
|
||||||
|
if event_type == 13: # Shield change
|
||||||
|
state = get('m_TotemShieldState')
|
||||||
|
what = get('m_BuildableName')
|
||||||
|
return f'Totem shield {state or "changed"}{f" ({what})" if what else ""}'
|
||||||
|
if event_type == 19: # Totem switch
|
||||||
|
state = get('m_StateChange')
|
||||||
|
what = get('m_BuildableName')
|
||||||
|
return f'Totem {what or "totem"} turned {state or "unknown state"}'
|
||||||
|
if event_type == 20: # Vehicle damage
|
||||||
|
vehicle = get('m_VehicleModelName', 'm_BuildableName')
|
||||||
|
causer = get('m_CauserType')
|
||||||
|
return f'{vehicle or "Vehicle"} damaged by {causer or "unknown"}'
|
||||||
|
if event_type == 23: # Vehicle event
|
||||||
|
vehicle = get('m_VehicleModelName', 'm_BuildableName')
|
||||||
|
return f'{vehicle or "Vehicle"} event'
|
||||||
|
if event_type == 95: # Totem power
|
||||||
|
secs = data.get('m_PowerTimeLeftSeconds')
|
||||||
|
what = get('m_BuildableName')
|
||||||
|
if isinstance(secs, (int, float)):
|
||||||
|
hours = int(secs) // 3600
|
||||||
|
return f'{what or "Totem"} power: ~{hours}h left'
|
||||||
|
return f'{what or "Totem"} power check'
|
||||||
|
if event_type == 97: # Permission change
|
||||||
|
what = get('m_PermissionActorName', 'm_DefaultActorTypeName')
|
||||||
|
old = get('m_OldPermissionRank')
|
||||||
|
new = get('m_NewPermissionRank')
|
||||||
|
return f'{what or "Something"}: {old or "?"} -> {new or "?"}'
|
||||||
|
if event_type == 99: # Vehicle stored
|
||||||
|
vehicle = get('m_BuildableName')
|
||||||
|
stored = data.get('m_bStored')
|
||||||
|
action = 'stored' if stored else 'retrieved'
|
||||||
|
return f'{vehicle or "Vehicle"} {action}'
|
||||||
|
return ''
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f'Event summary failed for type {event_type}: {e}')
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def parse_solaris_meta(meta):
|
||||||
|
"""Parse event_log meta into {fls_id, delta, balance}. Handles both
|
||||||
|
JSON and the Python-repr format the game writes. Returns None if useless."""
|
||||||
|
if not meta:
|
||||||
|
return None
|
||||||
|
data = None
|
||||||
|
if isinstance(meta, dict):
|
||||||
|
data = meta
|
||||||
|
else:
|
||||||
|
text = str(meta).strip()
|
||||||
|
try:
|
||||||
|
data = json.loads(text)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
try:
|
||||||
|
data = ast.literal_eval(text)
|
||||||
|
except (ValueError, TypeError, SyntaxError, MemoryError):
|
||||||
|
return None
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return {
|
||||||
|
'fls_id': str(data.get('fls_id') or ''),
|
||||||
|
'delta': int(data.get('solaris_delta', 0)),
|
||||||
|
'balance': int(data.get('solaris_balance', 0)),
|
||||||
|
}
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""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 dead scanner connection (typically an internet
|
||||||
|
# scanner hitting the public HTTPS port): vanishing mid-handshake, sending
|
||||||
|
# plain HTTP to the TLS port, or the follow-up cleanup of an already-dead
|
||||||
|
# socket. Never real failures.
|
||||||
|
_HANDSHAKE_NOISE = (
|
||||||
|
'during handshake',
|
||||||
|
'SSLV3_ALERT',
|
||||||
|
'UNEXPECTED_EOF',
|
||||||
|
'TLSV1_ALERT',
|
||||||
|
'plain HTTP',
|
||||||
|
'HTTP_REQUEST',
|
||||||
|
'not a socket',
|
||||||
|
'WinError 10038',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def cheroot_error_filter(original_error_log, msg='', level=20, traceback=False):
|
||||||
|
"""Drop-in replacement for ``server.error_log``.
|
||||||
|
|
||||||
|
Handshake noise -> debug log. Everything else -> original handler.
|
||||||
|
"""
|
||||||
|
text = str(msg)
|
||||||
|
lowered = text.lower()
|
||||||
|
if any(fragment.lower() in lowered for fragment in _HANDSHAKE_NOISE):
|
||||||
|
logger.debug('TLS handshake dropped by peer: %s', text[:200])
|
||||||
|
return
|
||||||
|
original_error_log(msg, level=level, traceback=traceback)
|
||||||
|
|
||||||
|
|
||||||
|
def build_server(host, port, wsgi_app, cert_path=None, key_path=None,
|
||||||
|
numthreads=16, socket_timeout=60):
|
||||||
|
"""Build a cheroot server with timeouts, bounded queues and TLS support."""
|
||||||
|
from cheroot import wsgi as cheroot_wsgi
|
||||||
|
|
||||||
|
server = cheroot_wsgi.Server(
|
||||||
|
(host, port), wsgi_app,
|
||||||
|
numthreads=numthreads,
|
||||||
|
request_queue_size=128,
|
||||||
|
timeout=socket_timeout,
|
||||||
|
accepted_queue_size=128,
|
||||||
|
accepted_queue_timeout=10,
|
||||||
|
)
|
||||||
|
if cert_path and key_path:
|
||||||
|
from cheroot.ssl.builtin import BuiltinSSLAdapter
|
||||||
|
server.ssl_adapter = BuiltinSSLAdapter(cert_path, key_path)
|
||||||
|
original = server.error_log
|
||||||
|
server.error_log = lambda msg='', level=20, traceback=False: \
|
||||||
|
cheroot_error_filter(original, msg, level=level, traceback=traceback)
|
||||||
|
return server
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""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
|
||||||
|
# A lone failed probe that recovers is just a blip; warn once
|
||||||
|
# the pattern looks real (second consecutive failure).
|
||||||
|
if failures == 1:
|
||||||
|
logger.debug(f'Watchdog: self-check failed ({failures}/{failures_needed})')
|
||||||
|
else:
|
||||||
|
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
|
||||||
+38
-66
@@ -2,6 +2,10 @@
|
|||||||
# This script handles both setup and starting the dashboard.
|
# This script handles both setup and starting the dashboard.
|
||||||
# Run this script and choose what you want to do.
|
# Run this script and choose what you want to do.
|
||||||
|
|
||||||
|
# -AutoStart skips the menu and starts the dashboard straight away
|
||||||
|
# (used after self-updates so the panel comes back up unattended).
|
||||||
|
param([switch]$AutoStart)
|
||||||
|
|
||||||
$ErrorActionPreference = "Continue"
|
$ErrorActionPreference = "Continue"
|
||||||
|
|
||||||
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
@@ -149,17 +153,6 @@ function Write-LogNoConsole {
|
|||||||
Add-Content -Path $logFile -Value $sanitizedEntry -Encoding UTF8
|
Add-Content -Path $logFile -Value $sanitizedEntry -Encoding UTF8
|
||||||
}
|
}
|
||||||
|
|
||||||
function Start-LogSession {
|
|
||||||
param([string]$SessionName = "Launcher Session")
|
|
||||||
$sessionFile = Join-Path $LauncherLogDir "$LogDate-$LogTime-session.log"
|
|
||||||
$header = "=" * 60
|
|
||||||
$sanitizedName = Sanitize-LogMessage -Message $SessionName
|
|
||||||
Add-Content -Path $sessionFile -Value (Sanitize-LogMessage -Message $header) -Encoding UTF8
|
|
||||||
Add-Content -Path $sessionFile -Value "$sanitizedName - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -Encoding UTF8
|
|
||||||
Add-Content -Path $sessionFile -Value (Sanitize-LogMessage -Message $header) -Encoding UTF8
|
|
||||||
return $sessionFile
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-Step {
|
function Write-Step {
|
||||||
param([string]$Name, [string]$Category = "general")
|
param([string]$Name, [string]$Category = "general")
|
||||||
if (-not $global:StepCounter) { $global:StepCounter = @{} }
|
if (-not $global:StepCounter) { $global:StepCounter = @{} }
|
||||||
@@ -169,16 +162,6 @@ function Write-Step {
|
|||||||
Write-Log -Message "[$num] $Name" -Level "INFO" -Category $Category
|
Write-Log -Message "[$num] $Name" -Level "INFO" -Category $Category
|
||||||
}
|
}
|
||||||
|
|
||||||
function Write-Success {
|
|
||||||
param([string]$Message, [string]$Category = "general")
|
|
||||||
Write-Log -Message $Message -Level "INFO" -Category $Category
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-DebugLog {
|
|
||||||
param([string]$Message, [string]$Category = "general")
|
|
||||||
Write-Log -Message $Message -Level "DEBUG" -Category $Category
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-Sep {
|
function Write-Sep {
|
||||||
param([string]$Title, [string]$Category = "general")
|
param([string]$Title, [string]$Category = "general")
|
||||||
$sep = "-" * 55
|
$sep = "-" * 55
|
||||||
@@ -191,26 +174,6 @@ function Write-Sep {
|
|||||||
Write-Host $msg -ForegroundColor DarkGray
|
Write-Host $msg -ForegroundColor DarkGray
|
||||||
}
|
}
|
||||||
|
|
||||||
$Script:LogIndent = 0
|
|
||||||
|
|
||||||
function Push-Indent {
|
|
||||||
$Script:LogIndent++
|
|
||||||
}
|
|
||||||
|
|
||||||
function Pop-Indent {
|
|
||||||
$Script:LogIndent = [Math]::Max(0, $Script:LogIndent - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-LogStyled {
|
|
||||||
param(
|
|
||||||
[string]$Message,
|
|
||||||
[string]$Level = "INFO",
|
|
||||||
[string]$Category = "general"
|
|
||||||
)
|
|
||||||
$prefix = if ($Script:LogIndent -gt 0) { " " * $Script:LogIndent } else { "" }
|
|
||||||
Write-Log -Message "$prefix$Message" -Level $Level -Category $Category
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Log Rotation & Cleanup ────────────────────────────────────────────
|
# ── Log Rotation & Cleanup ────────────────────────────────────────────
|
||||||
# Prevents logs from growing unbounded.
|
# Prevents logs from growing unbounded.
|
||||||
# - Deletes log files older than $LogRetentionDays
|
# - Deletes log files older than $LogRetentionDays
|
||||||
@@ -790,22 +753,6 @@ function Run-Diagnostics {
|
|||||||
}
|
}
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
# Backend dependencies check
|
|
||||||
Write-Host "[CHECK] New Dashboard Backend Dependencies..." -ForegroundColor Yellow
|
|
||||||
$backendReqs = Join-Path $ProjectRoot "backend\requirements.txt"
|
|
||||||
if (Test-Path $backendReqs) {
|
|
||||||
python -c "import pydantic, httpx, uvicorn" 2>$null
|
|
||||||
if ($LASTEXITCODE -eq 0) {
|
|
||||||
Write-Host " Backend deps: INSTALLED" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host " Backend deps: MISSING (run: pip install -r backend\requirements.txt)" -ForegroundColor Yellow
|
|
||||||
$issues++
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Write-Host " Backend deps: SKIPPED (no backend/requirements.txt)" -ForegroundColor DarkGray
|
|
||||||
}
|
|
||||||
Write-Host ""
|
|
||||||
|
|
||||||
# Offer port forward guide
|
# Offer port forward guide
|
||||||
Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan
|
Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan
|
||||||
$showGuide = Read-Host " "
|
$showGuide = Read-Host " "
|
||||||
@@ -939,11 +886,10 @@ function Reset-ToFactoryDefaults {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " [WARNING] This will permanently delete the following:" -ForegroundColor Red
|
Write-Host " [WARNING] This will permanently delete the following:" -ForegroundColor Red
|
||||||
Write-Host " - settings.yaml (all configuration)" -ForegroundColor Yellow
|
Write-Host " - settings.yaml (all configuration)" -ForegroundColor Yellow
|
||||||
Write-Host " - logs/, app/logs/, backend/logs/ (log files)" -ForegroundColor Yellow
|
Write-Host " - logs/, app/logs/ (log files)" -ForegroundColor Yellow
|
||||||
Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow
|
Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow
|
||||||
Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow
|
Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow
|
||||||
Write-Host " - __pycache__/ (Python cache in app/, backend/)" -ForegroundColor Yellow
|
Write-Host " - __pycache__/ (Python cache in app/)" -ForegroundColor Yellow
|
||||||
Write-Host " - frontend/node_modules/ (npm dependencies)" -ForegroundColor Yellow
|
|
||||||
Write-Host " - internal-scripts/ssh/ (copied SSH key)" -ForegroundColor Yellow
|
Write-Host " - internal-scripts/ssh/ (copied SSH key)" -ForegroundColor Yellow
|
||||||
Write-Host " - Temp scripts (read_settings*, hash_pw*, ssh_*, etc.)" -ForegroundColor Yellow
|
Write-Host " - Temp scripts (read_settings*, hash_pw*, ssh_*, etc.)" -ForegroundColor Yellow
|
||||||
Write-Host " - Test & build artifacts" -ForegroundColor Yellow
|
Write-Host " - Test & build artifacts" -ForegroundColor Yellow
|
||||||
@@ -985,7 +931,7 @@ function Reset-ToFactoryDefaults {
|
|||||||
if (Test-Path $sshKeyDir) { Remove-Item $sshKeyDir -Recurse -Force; Write-Host " Deleted internal-scripts/ssh/" -ForegroundColor Green; $count++ }
|
if (Test-Path $sshKeyDir) { Remove-Item $sshKeyDir -Recurse -Force; Write-Host " Deleted internal-scripts/ssh/" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- Python __pycache__ directories --
|
# -- Python __pycache__ directories --
|
||||||
$cacheSearchPaths = @("app", "backend")
|
$cacheSearchPaths = @("app")
|
||||||
$totalCacheDirs = 0
|
$totalCacheDirs = 0
|
||||||
foreach ($csp in $cacheSearchPaths) {
|
foreach ($csp in $cacheSearchPaths) {
|
||||||
$cspPath = Join-Path $ProjectRoot $csp
|
$cspPath = Join-Path $ProjectRoot $csp
|
||||||
@@ -997,10 +943,6 @@ function Reset-ToFactoryDefaults {
|
|||||||
if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force; $totalCacheDirs++ }
|
if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force; $totalCacheDirs++ }
|
||||||
if ($totalCacheDirs -gt 0) { Write-Host " Deleted $totalCacheDirs __pycache__ folder(s)" -ForegroundColor Green; $count++ }
|
if ($totalCacheDirs -gt 0) { Write-Host " Deleted $totalCacheDirs __pycache__ folder(s)" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- frontend/node_modules --
|
|
||||||
if (Test-Path (Join-Path $ProjectRoot "frontend\node_modules")) { Remove-Item (Join-Path $ProjectRoot "frontend\node_modules") -Recurse -Force; Write-Host " Deleted frontend/node_modules/" -ForegroundColor Green; $count++ }
|
|
||||||
if (Test-Path (Join-Path $ProjectRoot "frontend\package-lock.json")) { Remove-Item (Join-Path $ProjectRoot "frontend\package-lock.json") -Force; Write-Host " Deleted frontend/package-lock.json" -ForegroundColor Green; $count++ }
|
|
||||||
|
|
||||||
# -- Temp scripts generated during setup --
|
# -- Temp scripts generated during setup --
|
||||||
$tempPatterns = @("read_settings*.py", "hash_pw*.py", "ssh_cmd.bat", "ssh_pf_*.bat", "certbot-out.txt", "temp_*.py", "temp_*.ps1", "temp_*.sh", "check_*.py", "fix_*.py", "parse_*.ps1", "find_*.py")
|
$tempPatterns = @("read_settings*.py", "hash_pw*.py", "ssh_cmd.bat", "ssh_pf_*.bat", "certbot-out.txt", "temp_*.py", "temp_*.ps1", "temp_*.sh", "check_*.py", "fix_*.py", "parse_*.ps1", "find_*.py")
|
||||||
$tempDeleted = 0
|
$tempDeleted = 0
|
||||||
@@ -1011,7 +953,7 @@ function Reset-ToFactoryDefaults {
|
|||||||
if ($tempDeleted -gt 0) { Write-Host " Deleted $tempDeleted temp script(s)" -ForegroundColor Green; $count++ }
|
if ($tempDeleted -gt 0) { Write-Host " Deleted $tempDeleted temp script(s)" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- Test & build artifacts --
|
# -- Test & build artifacts --
|
||||||
$artifactDirs = @(".pytest_cache", "htmlcov", "build", "backups", "frontend\.vite")
|
$artifactDirs = @(".pytest_cache", "htmlcov", "build", "backups")
|
||||||
foreach ($ad in $artifactDirs) {
|
foreach ($ad in $artifactDirs) {
|
||||||
$ap = Join-Path $ProjectRoot $ad
|
$ap = Join-Path $ProjectRoot $ad
|
||||||
if (Test-Path $ap) { Remove-Item $ap -Recurse -Force; Write-Host " Deleted $ad/" -ForegroundColor Green; $count++ }
|
if (Test-Path $ap) { Remove-Item $ap -Recurse -Force; Write-Host " Deleted $ad/" -ForegroundColor Green; $count++ }
|
||||||
@@ -2461,7 +2403,32 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
Set-Location -LiteralPath $ProjectRoot
|
Set-Location -LiteralPath $ProjectRoot
|
||||||
|
# Exit code 42 = watchdog tripped (dashboard wedged) - restart it
|
||||||
|
# automatically, tunnels stay up. Anything else shuts down normally.
|
||||||
|
# The python check pins down $LASTEXITCODE so a failed launch can never
|
||||||
|
# inherit a stale 42 from an earlier command.
|
||||||
|
if (-not (Get-Command python -ErrorAction SilentlyContinue)) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [ERROR] Python not found on PATH. Cannot start dashboard." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
$watchdogRestarts = 0
|
||||||
|
while ($true) {
|
||||||
python run.py
|
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
|
||||||
@@ -2856,6 +2823,11 @@ function Rotate-SSHKey {
|
|||||||
|
|
||||||
Show-Banner
|
Show-Banner
|
||||||
|
|
||||||
|
if ($AutoStart) {
|
||||||
|
Start-Dashboard
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
}
|
||||||
|
|
||||||
while ($true) {
|
while ($true) {
|
||||||
Show-Menu
|
Show-Menu
|
||||||
$choice = Read-Host " Enter your choice"
|
$choice = Read-Host " Enter your choice"
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ Flask-WTF==1.2.2
|
|||||||
Flask-Limiter==3.5.0
|
Flask-Limiter==3.5.0
|
||||||
cryptography>=42.0.0
|
cryptography>=42.0.0
|
||||||
argon2-cffi==23.1.0
|
argon2-cffi==23.1.0
|
||||||
|
cheroot==10.0.1
|
||||||
@@ -30,6 +30,23 @@ if __name__ == '__main__':
|
|||||||
cert_path = str(ssl_cert).strip("'\"")
|
cert_path = str(ssl_cert).strip("'\"")
|
||||||
key_path = str(ssl_key).strip("'\"")
|
key_path = str(ssl_key).strip("'\"")
|
||||||
if os.path.exists(cert_path) and os.path.exists(key_path):
|
if os.path.exists(cert_path) and os.path.exists(key_path):
|
||||||
|
try:
|
||||||
|
with open(cert_path, 'rb'):
|
||||||
|
pass
|
||||||
|
with open(key_path, 'rb'):
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
print(f"\n [ERROR] Cannot read SSL files (permission denied):")
|
||||||
|
print(f" [ERROR] {cert_path}")
|
||||||
|
print(f" [ERROR] {key_path}")
|
||||||
|
print(f" [ERROR] The dashboard runs as '{os.environ.get('USERNAME', 'unknown')}'")
|
||||||
|
print(" [ERROR] but these files are only readable by an Administrator.")
|
||||||
|
print(" [ERROR] Fix with ONE of:")
|
||||||
|
print(" [ERROR] 1. Run the launcher as Administrator (right-click -> Run as administrator)")
|
||||||
|
print(" [ERROR] 2. Grant yourself read access, e.g. in an elevated terminal:")
|
||||||
|
print(f' [ERROR] icacls "{cert_path}" /grant "%USERNAME%:(R)"')
|
||||||
|
print(f' [ERROR] icacls "{key_path}" /grant "%USERNAME%:(R)"\n')
|
||||||
|
sys.exit(1)
|
||||||
ssl_context = (cert_path, key_path)
|
ssl_context = (cert_path, key_path)
|
||||||
protocol = "https"
|
protocol = "https"
|
||||||
else:
|
else:
|
||||||
@@ -67,6 +84,12 @@ if __name__ == '__main__':
|
|||||||
print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.")
|
print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.")
|
||||||
print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n")
|
print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n")
|
||||||
|
|
||||||
|
import signal
|
||||||
|
def _shutdown(sig, frame):
|
||||||
|
logging.getLogger(__name__).info("Shutdown signal received, exiting...")
|
||||||
|
os._exit(0)
|
||||||
|
signal.signal(signal.SIGINT, _shutdown)
|
||||||
|
|
||||||
# Start optional HTTP -> HTTPS redirect server when SSL is enabled.
|
# Start optional HTTP -> HTTPS redirect server when SSL is enabled.
|
||||||
# This is convenience only; the dashboard works without port 80 if users visit https://host:port.
|
# This is convenience only; the dashboard works without port 80 if users visit https://host:port.
|
||||||
if ssl_context and settings['dashboard'].get('http_redirect', False):
|
if ssl_context and settings['dashboard'].get('http_redirect', False):
|
||||||
@@ -95,6 +118,18 @@ if __name__ == '__main__':
|
|||||||
def log_message(self, format, *args):
|
def log_message(self, format, *args):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def handle_error(self, request, client_address):
|
||||||
|
# Scanners constantly connect and vanish mid-request. A reset
|
||||||
|
# or broken pipe on an already-dead socket is routine noise:
|
||||||
|
# debug-log it instead of dumping a traceback on the console.
|
||||||
|
exc = sys.exc_info()[1]
|
||||||
|
if isinstance(exc, (ConnectionResetError, BrokenPipeError)):
|
||||||
|
logging.getLogger(__name__).debug(
|
||||||
|
"Redirect: %s disconnected mid-request",
|
||||||
|
client_address[0] if client_address else '?')
|
||||||
|
return
|
||||||
|
super().handle_error(request, client_address)
|
||||||
|
|
||||||
# Try configured redirect port first, fall back to dashboard port+1.
|
# Try configured redirect port first, fall back to dashboard port+1.
|
||||||
# Try 0.0.0.0 first (all interfaces), fall back to 127.0.0.1 (localhost only)
|
# Try 0.0.0.0 first (all interfaces), fall back to 127.0.0.1 (localhost only)
|
||||||
http_port = None
|
http_port = None
|
||||||
@@ -130,4 +165,35 @@ if __name__ == '__main__':
|
|||||||
elif ssl_context:
|
elif ssl_context:
|
||||||
print(" HTTP redirect: Disabled (visit the HTTPS URL directly)\n")
|
print(" HTTP redirect: Disabled (visit the HTTPS URL directly)\n")
|
||||||
|
|
||||||
|
# Self-watchdog: exits with code 42 if the server stops answering,
|
||||||
|
# so the launcher can restart it (tunnels stay up).
|
||||||
|
from app.utils.watchdog import start_watchdog
|
||||||
|
start_watchdog(host, port, use_ssl=bool(ssl_context))
|
||||||
|
|
||||||
|
# Serve with cheroot (production WSGI) instead of the Flask dev server:
|
||||||
|
# per-connection socket timeouts plus bounded queues mean half-open
|
||||||
|
# scanner connections are reaped instead of wedging the dashboard.
|
||||||
|
# Socket.IO keeps working (threading mode = HTTP long-polling, which
|
||||||
|
# runs on any WSGI server).
|
||||||
|
try:
|
||||||
|
import cheroot
|
||||||
|
from app.utils.http_server import build_server
|
||||||
|
except ImportError:
|
||||||
|
logging.getLogger(__name__).warning(
|
||||||
|
"cheroot not installed - falling back to dev server "
|
||||||
|
"(no connection timeouts)")
|
||||||
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
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,6 +52,9 @@ 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,6 +192,78 @@ AUTH_USER="${AUTH_USER:-admin}"
|
|||||||
read -rsp " Admin Password: " AUTH_PASS
|
read -rsp " Admin Password: " AUTH_PASS
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
|
# RMQ tunnel ports
|
||||||
|
echo ""
|
||||||
|
echo " RabbitMQ tunnel ports (local forwards to the game server)"
|
||||||
|
read -rp " RMQ Admin Port [30325]: " RMQ_ADMIN_PORT
|
||||||
|
RMQ_ADMIN_PORT="${RMQ_ADMIN_PORT:-30325}"
|
||||||
|
read -rp " RMQ Game Port [32716]: " RMQ_GAME_PORT
|
||||||
|
RMQ_GAME_PORT="${RMQ_GAME_PORT:-32716}"
|
||||||
|
|
||||||
|
# Remote access
|
||||||
|
echo ""
|
||||||
|
echo " Remote access:"
|
||||||
|
echo " Local only (n) - access from this machine only (recommended)"
|
||||||
|
echo " Remote (y) - access from other devices on your network"
|
||||||
|
read -rp " Enable remote access? (y/N): " ENABLE_REMOTE
|
||||||
|
DASH_HOST="127.0.0.1"
|
||||||
|
SSL_CERT="null"
|
||||||
|
SSL_KEY="null"
|
||||||
|
SSL_DOMAIN="null"
|
||||||
|
SSL_EMAIL="null"
|
||||||
|
HTTP_REDIRECT="false"
|
||||||
|
if [ "$ENABLE_REMOTE" = "y" ] || [ "$ENABLE_REMOTE" = "Y" ]; then
|
||||||
|
DASH_HOST="0.0.0.0"
|
||||||
|
echo ""
|
||||||
|
echo " Remote access needs HTTPS. You can use a domain with Let's Encrypt"
|
||||||
|
echo " or fall back to a self-signed certificate (browser warning)."
|
||||||
|
read -rp " Domain name (leave blank to use a self-signed certificate): " SSL_DOMAIN_IN
|
||||||
|
if [ -n "$SSL_DOMAIN_IN" ]; then
|
||||||
|
read -rp " Email address (required by Let's Encrypt): " SSL_EMAIL_IN
|
||||||
|
if command -v certbot &>/dev/null && [ -n "$SSL_EMAIL_IN" ]; then
|
||||||
|
echo " Requesting Let's Encrypt certificate for $SSL_DOMAIN_IN..."
|
||||||
|
if sudo certbot certonly --standalone --non-interactive --agree-tos -m "$SSL_EMAIL_IN" -d "$SSL_DOMAIN_IN" 2>/dev/null; then
|
||||||
|
SSL_CERT="/etc/letsencrypt/live/${SSL_DOMAIN_IN}/fullchain.pem"
|
||||||
|
SSL_KEY="/etc/letsencrypt/live/${SSL_DOMAIN_IN}/privkey.pem"
|
||||||
|
SSL_DOMAIN="$SSL_DOMAIN_IN"
|
||||||
|
SSL_EMAIL="$SSL_EMAIL_IN"
|
||||||
|
echo " Let's Encrypt certificate issued."
|
||||||
|
else
|
||||||
|
echo " [WARN] Let's Encrypt failed (port 80 must be reachable). Falling back to self-signed."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " [WARN] certbot not found or no email given. Falling back to self-signed."
|
||||||
|
echo " Install with: sudo apt install certbot (Ubuntu/Debian)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$SSL_CERT" = "null" ]; then
|
||||||
|
echo ""
|
||||||
|
read -rp " This machine's IP for the certificate [127.0.0.1]: " HOST_IP
|
||||||
|
HOST_IP="${HOST_IP:-127.0.0.1}"
|
||||||
|
mkdir -p "$PROJECT_ROOT/ssl"
|
||||||
|
if $PYTHON -c "
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, '$PROJECT_ROOT')
|
||||||
|
from app.utils.ssl import generate_cert
|
||||||
|
generate_cert('$PROJECT_ROOT/ssl/cert.pem', '$PROJECT_ROOT/ssl/key.pem', common_name='$HOST_IP', san_ips=['$HOST_IP', '127.0.0.1'], san_dns=['localhost'])
|
||||||
|
" 2>/dev/null; then
|
||||||
|
SSL_CERT="$PROJECT_ROOT/ssl/cert.pem"
|
||||||
|
SSL_KEY="$PROJECT_ROOT/ssl/key.pem"
|
||||||
|
else
|
||||||
|
echo " [WARN] Could not generate a certificate. Remote access will be HTTP only."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$SSL_CERT" != "null" ]; then
|
||||||
|
echo ""
|
||||||
|
echo " Optional: redirect plain http://HOST to https automatically."
|
||||||
|
echo " Requires TCP port 80 to be free."
|
||||||
|
read -rp " Enable HTTP redirect on port 80? (y/N): " HTTP_REDIRECT_IN
|
||||||
|
if [ "$HTTP_REDIRECT_IN" = "y" ] || [ "$HTTP_REDIRECT_IN" = "Y" ]; then
|
||||||
|
HTTP_REDIRECT="true"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# [5/5] Generate settings
|
# [5/5] Generate settings
|
||||||
echo ""
|
echo ""
|
||||||
echo "[5/5] Generating settings.yaml..."
|
echo "[5/5] Generating settings.yaml..."
|
||||||
@@ -227,15 +299,15 @@ server:
|
|||||||
ssh_key: ${SSH_KEY_YAML}
|
ssh_key: ${SSH_KEY_YAML}
|
||||||
|
|
||||||
dashboard:
|
dashboard:
|
||||||
host: 127.0.0.1
|
host: ${DASH_HOST}
|
||||||
port: ${DASH_PORT}
|
port: ${DASH_PORT}
|
||||||
debug: false
|
debug: false
|
||||||
secret_key: ${SECRET_KEY}
|
secret_key: ${SECRET_KEY}
|
||||||
ssl_cert: null
|
ssl_cert: ${SSL_CERT}
|
||||||
ssl_key: null
|
ssl_key: ${SSL_KEY}
|
||||||
ssl_domain: null
|
ssl_domain: ${SSL_DOMAIN}
|
||||||
ssl_email: null
|
ssl_email: ${SSL_EMAIL}
|
||||||
http_redirect: false
|
http_redirect: ${HTTP_REDIRECT}
|
||||||
http_redirect_port: 80
|
http_redirect_port: 80
|
||||||
|
|
||||||
database:
|
database:
|
||||||
@@ -276,14 +348,11 @@ logging:
|
|||||||
max_bytes: 10485760
|
max_bytes: 10485760
|
||||||
backup_count: 5
|
backup_count: 5
|
||||||
|
|
||||||
rmq:
|
rabbitmq:
|
||||||
admin_host: 127.0.0.1
|
admin_port: ${RMQ_ADMIN_PORT}
|
||||||
admin_port: 32686
|
game_port: ${RMQ_GAME_PORT}
|
||||||
game_host: 127.0.0.1
|
username: dashboard_admin
|
||||||
game_port: 32021
|
|
||||||
username: admin
|
|
||||||
password: null
|
password: null
|
||||||
ttl: 15
|
|
||||||
YAML_EOF
|
YAML_EOF
|
||||||
|
|
||||||
echo " settings.yaml created!"
|
echo " settings.yaml created!"
|
||||||
@@ -298,16 +367,30 @@ if [ -n "$SSH_KEY" ] && [ "$VM_HOST" != "YOUR_SERVER_IP" ]; then
|
|||||||
echo " (Start the dashboard with option 1 or 7 first to set up tunnels)"
|
echo " (Start the dashboard with option 1 or 7 first to set up tunnels)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$DASH_HOST" = "0.0.0.0" ] && command -v ufw &>/dev/null; then
|
||||||
|
echo ""
|
||||||
|
echo " Remote access is on. This machine's firewall may block port ${DASH_PORT}."
|
||||||
|
read -rp " Allow TCP port ${DASH_PORT} through ufw now? (requires sudo) (y/N): " UFW_ALLOW
|
||||||
|
if [ "$UFW_ALLOW" = "y" ] || [ "$UFW_ALLOW" = "Y" ]; then
|
||||||
|
sudo ufw allow "${DASH_PORT}/tcp" 2>/dev/null && echo " Firewall rule added." || echo " [WARN] Could not add firewall rule."
|
||||||
|
else
|
||||||
|
echo " Skipped. If remote access fails, run: sudo ufw allow ${DASH_PORT}/tcp"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo " Setup Complete!"
|
echo " Setup Complete!"
|
||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo ""
|
echo ""
|
||||||
echo " Next steps:"
|
echo " Next steps:"
|
||||||
echo " 1. Start the dashboard: bash start.sh -> option 1 (classic)"
|
echo " 1. Start the dashboard: bash start.sh -> option 1"
|
||||||
echo " Or try the new UI: bash start.sh -> option 7 (React)"
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " 2. Open http://localhost:${DASH_PORT} in your browser"
|
if [ "$SSL_CERT" != "null" ]; then
|
||||||
|
echo " 2. Open https://localhost:${DASH_PORT} in your browser (or your domain/IP)"
|
||||||
|
else
|
||||||
|
echo " 2. Open http://localhost:${DASH_PORT} in your browser"
|
||||||
|
fi
|
||||||
echo ""
|
echo ""
|
||||||
echo " Username: ${AUTH_USER}"
|
echo " Username: ${AUTH_USER}"
|
||||||
echo " Password: (what you entered)"
|
echo " Password: (what you entered)"
|
||||||
|
|||||||
@@ -31,9 +31,23 @@ show_menu() {
|
|||||||
echo " [3] Run Diagnostics"
|
echo " [3] Run Diagnostics"
|
||||||
echo " Check your system for common issues that could block the dashboard."
|
echo " Check your system for common issues that could block the dashboard."
|
||||||
echo ""
|
echo ""
|
||||||
echo " [7] Start New Dashboard (React + ChakraUI)"
|
echo " [4] Start Dashboard (Debug Mode)"
|
||||||
echo " Launch the modern React dashboard with auto-install."
|
echo " Start with verbose debug logging. Only use when troubleshooting."
|
||||||
echo " Backend API + frontend dev server (http://localhost:5173)"
|
echo ""
|
||||||
|
echo " [5] Reset to Factory Defaults"
|
||||||
|
echo " Wipe settings, logs, SSL files and cached keys. You must run setup again."
|
||||||
|
echo ""
|
||||||
|
echo " [6] Repair Game Database"
|
||||||
|
echo " Fix dashboard schema ownership (fixes game servers not starting)."
|
||||||
|
echo ""
|
||||||
|
echo " [7] Clean Up Old Dashboard Schema"
|
||||||
|
echo " Drop the legacy dashboard schema from the game database."
|
||||||
|
echo ""
|
||||||
|
echo " [8] Rotate SSH Key"
|
||||||
|
echo " Find the newest SSH key on this machine and sync it into the project."
|
||||||
|
echo ""
|
||||||
|
echo " [9] Trust Server Certificate"
|
||||||
|
echo " Install/remove the dashboard's self-signed cert in the system store."
|
||||||
echo ""
|
echo ""
|
||||||
echo " [Q] Quit"
|
echo " [Q] Quit"
|
||||||
echo ""
|
echo ""
|
||||||
@@ -63,7 +77,7 @@ determine_python() {
|
|||||||
|
|
||||||
test_dependencies() {
|
test_dependencies() {
|
||||||
echo " Checking Python dependencies..."
|
echo " Checking Python dependencies..."
|
||||||
$PYTHON -c "import flask, flask_socketio, yaml, flask_login, flask_wtf, flask_limiter, paramiko, argon2, cryptography" 2>/dev/null
|
$PYTHON -c "import flask, flask_socketio, yaml, flask_login, flask_wtf, flask_limiter, paramiko, argon2, cryptography, cheroot" 2>/dev/null
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo " Installing dependencies..."
|
echo " Installing dependencies..."
|
||||||
$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null && echo " Dependencies installed." || echo " [WARN] Some packages may have failed."
|
$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null && echo " Dependencies installed." || echo " [WARN] Some packages may have failed."
|
||||||
@@ -98,7 +112,8 @@ if k and k != 'null':
|
|||||||
|
|
||||||
for kp in "${key_paths[@]}"; do
|
for kp in "${key_paths[@]}"; do
|
||||||
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
||||||
echo " SSH Key: Found at $kp"
|
# Status goes to stderr so command substitution callers get a clean path on stdout.
|
||||||
|
echo " SSH Key: Found at $kp" >&2
|
||||||
echo "$kp"
|
echo "$kp"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
@@ -262,7 +277,7 @@ run_diagnostics() {
|
|||||||
|
|
||||||
# Python
|
# Python
|
||||||
echo "[1/6] Checking Python..."
|
echo "[1/6] Checking Python..."
|
||||||
if ! determine_python; then ((issues++)); fi
|
if ! determine_python; then ((++issues)); fi
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Dependencies
|
# Dependencies
|
||||||
@@ -285,7 +300,7 @@ print(s.get('server', {}).get('host', 'NOT SET'))
|
|||||||
echo " Server Host: $server_host"
|
echo " Server Host: $server_host"
|
||||||
else
|
else
|
||||||
echo " Server Host: NOT CONFIGURED (edit settings.yaml)"
|
echo " Server Host: NOT CONFIGURED (edit settings.yaml)"
|
||||||
((issues++))
|
((++issues))
|
||||||
fi
|
fi
|
||||||
dash_info=$($PYTHON -c "
|
dash_info=$($PYTHON -c "
|
||||||
import yaml
|
import yaml
|
||||||
@@ -297,7 +312,7 @@ print(f\"{d.get('host', 'N/A')}:{d.get('port', 'N/A')}\")
|
|||||||
echo " Dashboard: $dash_info"
|
echo " Dashboard: $dash_info"
|
||||||
else
|
else
|
||||||
echo " settings.yaml: NOT FOUND - Run setup first"
|
echo " settings.yaml: NOT FOUND - Run setup first"
|
||||||
((issues++))
|
((++issues))
|
||||||
fi
|
fi
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
@@ -306,7 +321,8 @@ print(f\"{d.get('host', 'N/A')}:{d.get('port', 'N/A')}\")
|
|||||||
ssh_key=$(test_ssh_key) || ((issues++))
|
ssh_key=$(test_ssh_key) || ((issues++))
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# SSH Connection
|
# SSH Connection (only when a key file was actually found, otherwise the
|
||||||
|
# missing key above is the single issue worth reporting).
|
||||||
echo "[5/6] Checking SSH Connection..."
|
echo "[5/6] Checking SSH Connection..."
|
||||||
if [ -f "$settings_file" ]; then
|
if [ -f "$settings_file" ]; then
|
||||||
server_user=$($PYTHON -c "
|
server_user=$($PYTHON -c "
|
||||||
@@ -315,7 +331,11 @@ with open('$settings_file') as f:
|
|||||||
s = yaml.safe_load(f) or {}
|
s = yaml.safe_load(f) or {}
|
||||||
print(s.get('server', {}).get('user', 'dune'))
|
print(s.get('server', {}).get('user', 'dune'))
|
||||||
" 2>/dev/null)
|
" 2>/dev/null)
|
||||||
|
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
|
||||||
@@ -363,13 +383,13 @@ print(s.get('server', {}).get('host', 'NOT SET'))
|
|||||||
|
|
||||||
# Offer port forward guide
|
# Offer port forward guide
|
||||||
echo " Would you like to see the Port Forwarding & Firewall guide? (y/N)"
|
echo " Would you like to see the Port Forwarding & Firewall guide? (y/N)"
|
||||||
read -r show_guide
|
read -r show_guide || true
|
||||||
if [ "$show_guide" = "y" ] || [ "$show_guide" = "Y" ]; then
|
if [ "$show_guide" = "y" ] || [ "$show_guide" = "Y" ]; then
|
||||||
show_port_forward_guide
|
show_port_forward_guide
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo " Press Enter to return to the main menu..."
|
echo " Press Enter to return to the main menu..."
|
||||||
read -r
|
read -r || true
|
||||||
}
|
}
|
||||||
|
|
||||||
run_setup() {
|
run_setup() {
|
||||||
@@ -386,7 +406,7 @@ run_setup() {
|
|||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " Press Enter to return to the main menu..."
|
echo " Press Enter to return to the main menu..."
|
||||||
read -r
|
read -r || true
|
||||||
}
|
}
|
||||||
|
|
||||||
start_dashboard() {
|
start_dashboard() {
|
||||||
@@ -413,6 +433,21 @@ start_dashboard() {
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Normal start runs with debug logging off (debug entry point sets PRESERVE_DEBUG).
|
||||||
|
if [ -z "$PRESERVE_DEBUG" ]; then
|
||||||
|
$PYTHON -c "
|
||||||
|
import yaml
|
||||||
|
p = '$settings_file'
|
||||||
|
s = yaml.safe_load(open(p)) or {}
|
||||||
|
lg = s.setdefault('logging', {})
|
||||||
|
if lg.get('debug_enabled') is True:
|
||||||
|
lg['debug_enabled'] = False
|
||||||
|
lg['level'] = 'INFO'
|
||||||
|
yaml.safe_dump(s, open(p, 'w'), default_flow_style=False, sort_keys=False)
|
||||||
|
print(' Debug logging: disabled for normal start')
|
||||||
|
" 2>/dev/null
|
||||||
|
fi
|
||||||
|
|
||||||
# Read settings
|
# Read settings
|
||||||
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 2>/dev/null)
|
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 2>/dev/null)
|
||||||
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 2>/dev/null)
|
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 2>/dev/null)
|
||||||
@@ -420,6 +455,10 @@ start_dashboard() {
|
|||||||
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['kubernetes']['namespace'])" 2>/dev/null)
|
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['kubernetes']['namespace'])" 2>/dev/null)
|
||||||
dashboard_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['dashboard']['port'])" 2>/dev/null)
|
dashboard_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['dashboard']['port'])" 2>/dev/null)
|
||||||
director_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['director']['port'])" 2>/dev/null)
|
director_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['director']['port'])" 2>/dev/null)
|
||||||
|
rmq_admin_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s.get('rabbitmq',{}).get('admin_port',30325))" 2>/dev/null)
|
||||||
|
rmq_game_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s.get('rabbitmq',{}).get('game_port',32716))" 2>/dev/null)
|
||||||
|
[ -z "$rmq_admin_port" ] && rmq_admin_port=30325
|
||||||
|
[ -z "$rmq_game_port" ] && rmq_game_port=32716
|
||||||
|
|
||||||
# Find SSH key
|
# Find SSH key
|
||||||
ssh_key_src=$($PYTHON -c "
|
ssh_key_src=$($PYTHON -c "
|
||||||
@@ -476,14 +515,18 @@ if k and k != 'null':
|
|||||||
echo "============================================================"
|
echo "============================================================"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Kill existing SSH tunnels on the DB/Director ports
|
# Kill existing SSH tunnels on the DB/Director/RMQ ports.
|
||||||
pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
# Each kill is guarded so an empty port can never widen the pattern
|
||||||
pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
|
# into matching unrelated SSH processes.
|
||||||
|
[ -n "$local_port" ] && pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
||||||
|
[ -n "$director_port" ] && pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
|
||||||
|
[ -n "$rmq_admin_port" ] && pkill -f "ssh.*-L.*${rmq_admin_port}" 2>/dev/null || true
|
||||||
|
[ -n "$rmq_game_port" ] && pkill -f "ssh.*-L.*${rmq_game_port}" 2>/dev/null || true
|
||||||
sleep 1
|
sleep 1
|
||||||
|
|
||||||
# [1/4] SSH Tunnel
|
# [1/4] SSH Tunnel
|
||||||
echo "[1/4] Starting SSH tunnel (localhost:$local_port -> VM)..."
|
echo "[1/4] Starting SSH tunnel (localhost:$local_port -> VM)..."
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -N "${ssh_user}@${server_host}" &
|
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -L "${rmq_admin_port}:localhost:${rmq_admin_port}" -L "${rmq_game_port}:localhost:${rmq_game_port}" -N "${ssh_user}@${server_host}" &
|
||||||
ssh_tunnel_pid=$!
|
ssh_tunnel_pid=$!
|
||||||
|
|
||||||
connected=false
|
connected=false
|
||||||
@@ -518,7 +561,7 @@ if k and k != 'null':
|
|||||||
kill $ssh_tunnel_pid 2>/dev/null
|
kill $ssh_tunnel_pid 2>/dev/null
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
echo "[OK] SSH tunnel up on localhost:$local_port"
|
echo "[OK] SSH tunnel up on localhost:$local_port (DB), localhost:$director_port (Director), localhost:$rmq_admin_port (RMQ Admin), localhost:$rmq_game_port (RMQ Game)"
|
||||||
|
|
||||||
# [2/4] DB Port-Forward
|
# [2/4] DB Port-Forward
|
||||||
echo "[2/4] Starting DB port-forward on VM..."
|
echo "[2/4] Starting DB port-forward on VM..."
|
||||||
@@ -620,7 +663,25 @@ if k and k != 'null':
|
|||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
cd "$PROJECT_ROOT"
|
cd "$PROJECT_ROOT"
|
||||||
|
# Exit code 42 = watchdog tripped (dashboard wedged) - restart it
|
||||||
|
# automatically, tunnels stay up. Anything else shuts down normally.
|
||||||
|
watchdog_restarts=0
|
||||||
|
while true; do
|
||||||
$PYTHON run.py
|
$PYTHON run.py
|
||||||
|
code=$?
|
||||||
|
if [ "$code" -eq 42 ] && [ "$watchdog_restarts" -lt 5 ]; then
|
||||||
|
watchdog_restarts=$((watchdog_restarts + 1))
|
||||||
|
echo ""
|
||||||
|
echo " [WARN] Dashboard stopped responding (watchdog) - restarting ($watchdog_restarts/5)..."
|
||||||
|
sleep 5
|
||||||
|
else
|
||||||
|
if [ "$code" -eq 42 ]; then
|
||||||
|
echo ""
|
||||||
|
echo " [ERROR] Dashboard keeps freezing - giving up auto-restart. Check the setup and start manually."
|
||||||
|
fi
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "Stopping tunnels..."
|
echo "Stopping tunnels..."
|
||||||
@@ -628,267 +689,382 @@ if k and k != 'null':
|
|||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
|
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
|
||||||
}
|
}
|
||||||
|
|
||||||
start_new_dashboard() {
|
|
||||||
echo ""
|
|
||||||
echo " Starting NEW dashboard (React + ChakraUI)..."
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Check Python
|
# ── Shared Server Helpers ───────────────────────────────────────────────
|
||||||
if ! determine_python; then
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check Node.js
|
# Load server connection details from settings.yaml.
|
||||||
if ! command -v node &>/dev/null; then
|
# Sets: server_host ssh_user namespace ssh_key. Returns non-zero on error.
|
||||||
echo " Node.js: NOT FOUND"
|
load_server_settings() {
|
||||||
echo ""
|
|
||||||
echo " Node.js 18+ is required for the new frontend."
|
|
||||||
echo " Install: https://nodejs.org/ or use nvm"
|
|
||||||
echo ""
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
echo " Node.js: $(node --version)"
|
|
||||||
|
|
||||||
# Check dependencies
|
|
||||||
test_dependencies
|
|
||||||
|
|
||||||
# Check settings
|
|
||||||
settings_file="$PROJECT_ROOT/settings.yaml"
|
settings_file="$PROJECT_ROOT/settings.yaml"
|
||||||
if [ ! -f "$settings_file" ]; then
|
if [ ! -f "$settings_file" ]; then
|
||||||
echo ""
|
echo " [ERROR] settings.yaml not found. Run setup first."
|
||||||
echo " [ERROR] settings.yaml not found. You need to run setup first."
|
return 1
|
||||||
echo ""
|
|
||||||
return
|
|
||||||
fi
|
fi
|
||||||
|
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; print(s.get('server',{}).get('host',''))" 2>/dev/null)
|
||||||
# Read settings
|
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')) or {}; print(s.get('server',{}).get('user','dune'))" 2>/dev/null)
|
||||||
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 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_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 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)
|
||||||
local_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['database']['port'])" 2>/dev/null)
|
if [ -z "$ssh_key" ] || [ ! -f "$ssh_key" ]; then
|
||||||
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
|
|
||||||
with open('$settings_file') as f:
|
|
||||||
s = yaml.safe_load(f) or {}
|
|
||||||
k = s.get('server', {}).get('ssh_key', '')
|
|
||||||
if k and k != 'null':
|
|
||||||
print(k)
|
|
||||||
" 2>/dev/null)
|
|
||||||
|
|
||||||
ssh_key=""
|
ssh_key=""
|
||||||
key_paths=(
|
for kp in "$HOME/.ssh/dune-dashboard-key" "$PROJECT_ROOT/internal-scripts/ssh/sshKey" "$HOME/.ssh/id_ed25519" "$HOME/.ssh/id_rsa"; do
|
||||||
"$ssh_key_src"
|
if [ -f "$kp" ]; then ssh_key="$kp"; break; fi
|
||||||
"$HOME/.ssh/dune-dashboard-key"
|
|
||||||
"$PROJECT_ROOT/internal-scripts/ssh/sshKey"
|
|
||||||
"/tmp/dune-tunnel-key"
|
|
||||||
"$HOME/.ssh/id_ed25519"
|
|
||||||
"$HOME/.ssh/id_rsa"
|
|
||||||
)
|
|
||||||
|
|
||||||
for kp in "${key_paths[@]}"; do
|
|
||||||
if [ -n "$kp" ] && [ -f "$kp" ]; then
|
|
||||||
if ssh -i "$kp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes "${ssh_user}@${server_host}" "echo ok" &>/dev/null; then
|
|
||||||
ssh_key="$kp"
|
|
||||||
echo " SSH Key: Found working key at $kp"
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
done
|
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
|
||||||
|
}
|
||||||
|
|
||||||
if [ -z "$ssh_key" ]; then
|
start_dashboard_debug() {
|
||||||
echo ""
|
echo ""
|
||||||
echo " [ERROR] No working SSH key found."
|
echo " ============================================================"
|
||||||
return
|
echo " Starting Dashboard with DEBUG LOGGING enabled"
|
||||||
fi
|
echo " ============================================================"
|
||||||
|
|
||||||
ssh_key_tmp="/tmp/dune-tunnel-key"
|
|
||||||
cp "$ssh_key" "$ssh_key_tmp" 2>/dev/null
|
|
||||||
chmod 600 "$ssh_key_tmp"
|
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "============================================================"
|
echo " WARNING: Debug logging can significantly impact performance!"
|
||||||
echo " Dune Awakening Dashboard (React Edition)"
|
echo " - Logs every HTTP request/response"
|
||||||
echo "============================================================"
|
echo " - Logs all SSH commands and results"
|
||||||
|
echo " - Logs all database queries"
|
||||||
|
echo " - Only use this when troubleshooting, not for regular use"
|
||||||
echo ""
|
echo ""
|
||||||
|
read -rp " Continue with debug mode? (y/N) " confirm
|
||||||
# Kill existing SSH tunnels
|
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
|
||||||
pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
|
echo " Cancelled."
|
||||||
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
|
return
|
||||||
fi
|
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
|
settings_file="$PROJECT_ROOT/settings.yaml"
|
||||||
connected=true
|
if [ ! -f "$settings_file" ]; then
|
||||||
break
|
echo " [ERROR] settings.yaml not found. Run setup first."
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$connected" = false ]; then
|
|
||||||
echo "[ERROR] SSH tunnel did not connect within 30 seconds"
|
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
echo "[OK] SSH tunnel up on localhost:$local_port"
|
$PYTHON -c "
|
||||||
|
import yaml
|
||||||
|
p = '$settings_file'
|
||||||
|
s = yaml.safe_load(open(p)) or {}
|
||||||
|
s.setdefault('logging', {})['debug_enabled'] = True
|
||||||
|
yaml.safe_dump(s, open(p, 'w'), default_flow_style=False, sort_keys=False)
|
||||||
|
" 2>/dev/null
|
||||||
|
echo " Debug logging enabled for this run."
|
||||||
|
echo ""
|
||||||
|
PRESERVE_DEBUG=1 start_dashboard
|
||||||
|
}
|
||||||
|
|
||||||
# [2/5] DB Port-Forward
|
reset_to_factory() {
|
||||||
echo "[2/5] Starting DB port-forward on VM..."
|
echo ""
|
||||||
|
echo " Reset to Factory Defaults"
|
||||||
if [ -z "$namespace" ] || [ "$namespace" = "" ]; then
|
echo ""
|
||||||
echo "[ERROR] Kubernetes namespace is empty."
|
echo " WARNING: This will permanently delete the following:"
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
echo " - settings.yaml (all configuration)"
|
||||||
|
echo " - logs/, app/logs/ (log files)"
|
||||||
|
echo " - instance/ (local data)"
|
||||||
|
echo " - ssl/ (SSL certificates)"
|
||||||
|
echo " - internal-scripts/ssh/ (copied SSH key)"
|
||||||
|
echo " - Python __pycache__ directories"
|
||||||
|
echo ""
|
||||||
|
echo " This cannot be undone. You will need to run setup again."
|
||||||
|
echo ""
|
||||||
|
read -rp " Type 'yes' to confirm: " confirmation
|
||||||
|
if [ "$confirmation" != "yes" ]; then
|
||||||
|
echo ""
|
||||||
|
echo " Reset cancelled. No changes made."
|
||||||
return
|
return
|
||||||
fi
|
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
|
||||||
|
}
|
||||||
|
|
||||||
db_svc="${namespace}-db-dbdepl-svc"
|
repair_game_database() {
|
||||||
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
|
echo ""
|
||||||
sleep 2
|
echo " Game Database Repair"
|
||||||
|
echo " ====================="
|
||||||
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
|
echo ""
|
||||||
|
if ! load_server_settings; then
|
||||||
bgd_svc="${namespace}-bgd-svc"
|
echo ""
|
||||||
bgd_deploy="${namespace}-bgd-deploy"
|
read -rp " Press Enter to return..." || true
|
||||||
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
|
return
|
||||||
fi
|
fi
|
||||||
echo "[OK] Database connected"
|
echo " Server: $server_host"
|
||||||
|
echo " Namespace: $namespace"
|
||||||
# [4/5] Install Dependencies
|
echo ""
|
||||||
echo "[4/5] Installing dependencies..."
|
read -rp " This will transfer dashboard schema ownership to the dune user. Continue? (y/N) " confirm
|
||||||
|
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
|
||||||
# Backend Python deps
|
echo " Cancelled."
|
||||||
if [ -f "$PROJECT_ROOT/requirements.txt" ]; then
|
return
|
||||||
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
|
fi
|
||||||
|
echo ""
|
||||||
# Frontend npm deps
|
echo "[1/4] Finding database pod..."
|
||||||
frontend_dir="$PROJECT_ROOT/frontend"
|
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 [ -f "$frontend_dir/package.json" ]; then
|
if [ -z "$db_pod" ]; then
|
||||||
if [ ! -d "$frontend_dir/node_modules" ]; then
|
echo "[ERROR] Could not find database pod."
|
||||||
echo " Installing frontend npm dependencies..."
|
return
|
||||||
(cd "$frontend_dir" && npm install --silent 2>/dev/null)
|
fi
|
||||||
echo " Frontend dependencies installed"
|
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
|
else
|
||||||
echo " Frontend dependencies OK"
|
echo " [OK] No failed util pods found"
|
||||||
fi
|
fi
|
||||||
fi
|
echo "[4/4] Done!"
|
||||||
|
|
||||||
# [5/5] Start Backend + Frontend
|
|
||||||
echo "[5/5] Starting dashboard..."
|
|
||||||
echo ""
|
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
|
||||||
|
}
|
||||||
|
|
||||||
# Start backend in background
|
cleanup_old_dashboard_schema() {
|
||||||
echo " Starting backend API (port $dashboard_port)..."
|
echo ""
|
||||||
backend_dir="$PROJECT_ROOT/backend"
|
echo " Clean Up Old Dashboard Schema"
|
||||||
(cd "$backend_dir" && $PYTHON run.py) &
|
echo " ==============================="
|
||||||
backend_pid=$!
|
echo ""
|
||||||
sleep 3
|
if ! load_server_settings; then
|
||||||
|
echo ""
|
||||||
# Verify backend started
|
read -rp " Press Enter to return..." || true
|
||||||
backend_alive=false
|
return
|
||||||
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
|
fi
|
||||||
sleep 2
|
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)
|
||||||
done
|
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
|
||||||
|
}
|
||||||
|
|
||||||
if [ "$backend_alive" = true ]; then
|
trust_server_cert() {
|
||||||
echo " [OK] Backend API running on port $dashboard_port"
|
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
|
else
|
||||||
echo " [WARN] Backend may not have started yet"
|
echo " Cancelled."
|
||||||
fi
|
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
|
||||||
|
}
|
||||||
|
|
||||||
# Start frontend in background
|
rotate_ssh_key() {
|
||||||
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 "============================================================"
|
echo " Rotate SSH Key"
|
||||||
echo " New Dashboard Started!"
|
echo " ==============="
|
||||||
echo "============================================================"
|
|
||||||
echo ""
|
echo ""
|
||||||
echo " Frontend: http://localhost:5173"
|
target_key="$PROJECT_ROOT/internal-scripts/ssh/sshKey"
|
||||||
echo " Backend: http://localhost:${dashboard_port}"
|
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
|
||||||
|
done
|
||||||
|
if [ -z "$newest" ]; then
|
||||||
echo ""
|
echo ""
|
||||||
echo " Press Ctrl+C to stop all services."
|
echo " No SSH keys found in any search location."
|
||||||
echo ""
|
echo ""
|
||||||
|
read -rp " Press Enter to return..." || true
|
||||||
# Cleanup on exit
|
return
|
||||||
cleanup() {
|
fi
|
||||||
|
mkdir -p "$(dirname "$target_key")"
|
||||||
|
if [ "$newest" = "$target_key" ]; then
|
||||||
echo ""
|
echo ""
|
||||||
echo " Stopping services..."
|
echo " The newest key is already at the target location."
|
||||||
kill $frontend_pid 2>/dev/null
|
echo " No rotation needed."
|
||||||
kill $backend_pid 2>/dev/null
|
else
|
||||||
kill $ssh_tunnel_pid 2>/dev/null
|
cp "$newest" "$target_key"
|
||||||
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
|
chmod 600 "$target_key"
|
||||||
echo " All services stopped."
|
|
||||||
echo ""
|
echo ""
|
||||||
}
|
echo " [OK] Synced newest key ($newest) to $target_key"
|
||||||
trap cleanup EXIT INT TERM
|
fi
|
||||||
|
echo ""
|
||||||
# Wait for any process to exit
|
read -rp " Press Enter to return..." || true
|
||||||
wait $ssh_tunnel_pid $backend_pid $frontend_pid 2>/dev/null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Main Loop ───────────────────────────────────────────────────────────
|
# ── Main Loop ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# --auto-start skips the menu and starts the dashboard straight away
|
||||||
|
# (used after self-updates so the panel comes back up unattended).
|
||||||
|
if [ "$1" = "--auto-start" ] || [ "$1" = "--autostart" ]; then
|
||||||
|
start_dashboard
|
||||||
|
exit $?
|
||||||
|
fi
|
||||||
|
|
||||||
show_banner
|
show_banner
|
||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
show_menu
|
show_menu
|
||||||
read -rp " Enter your choice: " choice
|
read -rp " Enter your choice: " choice || { echo ""; echo " Goodbye!"; echo ""; exit 0; }
|
||||||
|
|
||||||
case "$choice" in
|
case "$choice" in
|
||||||
1) start_dashboard ;;
|
1) start_dashboard ;;
|
||||||
2) run_setup ;;
|
2) run_setup ;;
|
||||||
3) run_diagnostics ;;
|
3) run_diagnostics ;;
|
||||||
7) start_new_dashboard ;;
|
4) start_dashboard_debug ;;
|
||||||
|
5) reset_to_factory ;;
|
||||||
|
6) repair_game_database ;;
|
||||||
|
7) cleanup_old_dashboard_schema ;;
|
||||||
|
8) rotate_ssh_key ;;
|
||||||
|
9) trust_server_cert ;;
|
||||||
[Qq]) echo ""; echo " Goodbye!"; echo ""; exit 0 ;;
|
[Qq]) echo ""; echo " Goodbye!"; echo ""; exit 0 ;;
|
||||||
*) echo ""; echo " Invalid choice. Please enter 1, 2, 3, 7, or Q."; echo "" ;;
|
*) echo ""; echo " Invalid choice. Please enter 1-9 or Q."; echo "" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
|
|||||||
@@ -71,6 +71,50 @@ nav a.active {
|
|||||||
|
|
||||||
nav .spacer { flex: 1; }
|
nav .spacer { flex: 1; }
|
||||||
|
|
||||||
|
/* Horizontal vs vertical nav link visibility */
|
||||||
|
.nav-links-h { display: flex; align-items: center; gap: 2px; }
|
||||||
|
.nav-links-v { display: none; }
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] .nav-links-h { display: none; }
|
||||||
|
body[data-nav-layout="vertical"] .nav-links-v { display: flex; flex-direction: column; width: 100%; flex: 1; overflow-y: auto; }
|
||||||
|
|
||||||
|
/* Horizontal nav dropdowns */
|
||||||
|
.nav-dropdown {
|
||||||
|
position: relative;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
.nav-dropdown-toggle {
|
||||||
|
cursor: default;
|
||||||
|
padding: 0 10px;
|
||||||
|
}
|
||||||
|
.nav-dropdown-content {
|
||||||
|
display: none;
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
background: var(--nav-bg);
|
||||||
|
min-width: 140px;
|
||||||
|
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
||||||
|
border-radius: 6px;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 4px 0;
|
||||||
|
border: 1px solid rgba(255,255,255,0.1);
|
||||||
|
}
|
||||||
|
.nav-dropdown-content a {
|
||||||
|
color: var(--nav-text);
|
||||||
|
padding: 8px 16px;
|
||||||
|
height: auto;
|
||||||
|
border-bottom: none;
|
||||||
|
font-size: 12px;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.nav-dropdown-content a:hover { color: #fff; background: rgba(255,255,255,0.06); }
|
||||||
|
.nav-dropdown-content a.active {
|
||||||
|
color: var(--nav-active);
|
||||||
|
border-left: 3px solid var(--nav-active);
|
||||||
|
}
|
||||||
|
.nav-dropdown:hover .nav-dropdown-content { display: block; }
|
||||||
|
|
||||||
.conn-dot {
|
.conn-dot {
|
||||||
width: 8px;
|
width: 8px;
|
||||||
height: 8px;
|
height: 8px;
|
||||||
@@ -939,6 +983,32 @@ td a:hover { text-decoration: underline; }
|
|||||||
border-radius: 3px;
|
border-radius: 3px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Resource charts */
|
||||||
|
.chart-panel .chart-hint {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
.chart-panel-body {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.chart-box {
|
||||||
|
position: relative;
|
||||||
|
height: 140px;
|
||||||
|
}
|
||||||
|
.chart-box canvas {
|
||||||
|
width: 100% !important;
|
||||||
|
height: 100% !important;
|
||||||
|
}
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.chart-panel-body {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.chart-box { height: 120px; }
|
||||||
|
}
|
||||||
|
|
||||||
/* Empty state */
|
/* Empty state */
|
||||||
.empty {
|
.empty {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
@@ -1071,6 +1141,11 @@ td a:hover { text-decoration: underline; }
|
|||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.modal-wide {
|
||||||
|
max-width: 900px;
|
||||||
|
width: 95%;
|
||||||
|
}
|
||||||
|
|
||||||
.modal h3 {
|
.modal h3 {
|
||||||
margin: 0 0 16px 0;
|
margin: 0 0 16px 0;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
@@ -1144,3 +1219,274 @@ td a:hover { text-decoration: underline; }
|
|||||||
font-family: monospace;
|
font-family: monospace;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Nav Layout Toggle */
|
||||||
|
.nav-toggle {
|
||||||
|
position: fixed;
|
||||||
|
top: 56px;
|
||||||
|
left: 6px;
|
||||||
|
z-index: 101;
|
||||||
|
background: var(--nav-bg);
|
||||||
|
color: var(--nav-text);
|
||||||
|
border: 1px solid rgba(255,255,255,0.15);
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 3px 7px;
|
||||||
|
font-size: 15px;
|
||||||
|
cursor: pointer;
|
||||||
|
line-height: 1;
|
||||||
|
opacity: 0.5;
|
||||||
|
transition: opacity 0.15s;
|
||||||
|
}
|
||||||
|
.nav-toggle:hover { opacity: 1; color: #fff; }
|
||||||
|
|
||||||
|
/* Vertical sidebar layout */
|
||||||
|
body[data-nav-layout="vertical"] {
|
||||||
|
padding-left: 216px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] .nav-toggle {
|
||||||
|
left: 204px;
|
||||||
|
top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav {
|
||||||
|
position: fixed;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
width: 200px;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100vh;
|
||||||
|
padding: 0;
|
||||||
|
align-items: stretch;
|
||||||
|
box-shadow: 1px 0 4px rgba(0,0,0,0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav .brand {
|
||||||
|
padding: 20px 16px 12px;
|
||||||
|
margin-right: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
text-align: center;
|
||||||
|
border-bottom: 1px solid rgba(255,255,255,0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav a {
|
||||||
|
padding: 10px 16px;
|
||||||
|
height: auto;
|
||||||
|
border-bottom: none;
|
||||||
|
border-left: 3px solid transparent;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav a:hover {
|
||||||
|
background: rgba(255,255,255,0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav a.active {
|
||||||
|
border-bottom-color: transparent;
|
||||||
|
border-left-color: var(--nav-active);
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav .spacer {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav .theme-dropdown {
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-top: 1px solid rgba(255,255,255,0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav .theme-dropdown .theme-dropdown-content {
|
||||||
|
bottom: 100%;
|
||||||
|
top: auto;
|
||||||
|
left: 0;
|
||||||
|
right: auto;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav .theme-dropdown .theme-btn {
|
||||||
|
width: 100%;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] nav .nav-conn,
|
||||||
|
body[data-nav-layout="vertical"] nav .nav-logout {
|
||||||
|
padding: 10px 16px;
|
||||||
|
justify-content: center;
|
||||||
|
border-top: 1px solid rgba(255,255,255,0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] .container {
|
||||||
|
max-width: none;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body[data-nav-layout="vertical"] .site-footer {
|
||||||
|
margin-left: 216px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Update widget: lives in the nav next to the theme button, styled like
|
||||||
|
the theme dropdown (nav-bg surface, nav-text tones) in every theme. */
|
||||||
|
.nav-tools { display: flex; align-items: center; gap: 2px; }
|
||||||
|
.update-banner { display: none; position: relative; }
|
||||||
|
.update-banner .ub-bellwrap { position: relative; display: inline-block; }
|
||||||
|
.update-banner .ub-dot {
|
||||||
|
position: absolute; top: 2px; right: 6px; width: 8px; height: 8px;
|
||||||
|
border-radius: 50%; background: var(--warn);
|
||||||
|
}
|
||||||
|
.update-banner .ub-panel {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 8px);
|
||||||
|
right: 0;
|
||||||
|
width: 320px;
|
||||||
|
max-width: calc(100vw - 32px);
|
||||||
|
max-height: 70vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
background: var(--nav-bg);
|
||||||
|
border: 1px solid rgba(255,255,255,0.1);
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--nav-text);
|
||||||
|
}
|
||||||
|
.update-banner .ub-title { font-weight: 700; margin-bottom: 2px; color: #fff; }
|
||||||
|
.update-banner .ub-sub { color: var(--nav-text); opacity: 0.75; font-size: 11px; margin-bottom: 6px; }
|
||||||
|
.update-banner .ub-preview-tag {
|
||||||
|
font-size: 10px; font-weight: 700; color: #fff; background: var(--warn);
|
||||||
|
border-radius: 8px; padding: 0 6px; margin-left: 4px;
|
||||||
|
}
|
||||||
|
.update-banner .ub-notes { margin: 4px 0 6px; }
|
||||||
|
.update-banner .ub-notes summary { cursor: pointer; font-size: 11px; color: var(--nav-text); opacity: 0.75; }
|
||||||
|
.update-banner .ub-notes pre {
|
||||||
|
white-space: pre-wrap; font-size: 11px; max-height: 160px; overflow-y: auto;
|
||||||
|
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1);
|
||||||
|
border-radius: 6px; padding: 8px; margin-top: 4px; color: var(--nav-text);
|
||||||
|
}
|
||||||
|
.update-banner .ub-actions { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; }
|
||||||
|
.update-banner .ub-actions button {
|
||||||
|
padding: 4px 12px; font-size: 12px; cursor: pointer;
|
||||||
|
background: var(--primary); color: #fff; border: none; border-radius: 4px;
|
||||||
|
}
|
||||||
|
.update-banner .ub-actions button.ub-ghost {
|
||||||
|
background: transparent; color: var(--nav-text);
|
||||||
|
border: 1px solid rgba(255,255,255,0.25);
|
||||||
|
}
|
||||||
|
.update-banner .ub-mute { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--nav-text); opacity: 0.75; cursor: pointer; }
|
||||||
|
.update-banner .ub-status { font-size: 11px; color: var(--nav-text); opacity: 0.75; margin-top: 4px; }
|
||||||
|
.update-banner .ub-panel-head { font-weight: 700; margin-bottom: 6px; color: #fff; cursor: pointer; }
|
||||||
|
.update-banner .ub-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-bottom: 6px; font-size: 12px; }
|
||||||
|
.update-banner .ub-row select {
|
||||||
|
padding: 4px 8px; font-size: 12px; color: var(--nav-text);
|
||||||
|
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.15); border-radius: 4px;
|
||||||
|
}
|
||||||
|
.update-banner .ub-row button {
|
||||||
|
padding: 4px 12px; font-size: 12px; cursor: pointer;
|
||||||
|
background: transparent; color: var(--nav-text);
|
||||||
|
border: 1px solid rgba(255,255,255,0.25); border-radius: 4px;
|
||||||
|
}
|
||||||
|
#ub-overlay {
|
||||||
|
position: fixed; inset: 0; z-index: 2000;
|
||||||
|
background: rgba(0,0,0,0.6);
|
||||||
|
display: flex; align-items: center; justify-content: center; padding: 24px;
|
||||||
|
}
|
||||||
|
#ub-overlay .ub-overlay-box {
|
||||||
|
max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto;
|
||||||
|
background: var(--card-bg); color: var(--text);
|
||||||
|
border-radius: 12px; box-shadow: var(--shadow); padding: 16px 18px;
|
||||||
|
}
|
||||||
|
#ub-overlay .ub-overlay-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
|
||||||
|
#ub-overlay .ub-overlay-head button {
|
||||||
|
padding: 4px 14px; font-size: 12px; cursor: pointer;
|
||||||
|
background: var(--primary); color: #fff; border: none; border-radius: 4px;
|
||||||
|
}
|
||||||
|
#ub-overlay pre { white-space: pre-wrap; font-size: 12px; }
|
||||||
|
|
||||||
|
/* Vertical sidebar: tools row sits with the theme button; panel pops upward
|
||||||
|
like the theme dropdown content does. */
|
||||||
|
body[data-nav-layout="vertical"] .nav-tools {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-top: 1px solid rgba(255,255,255,0.08);
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .nav-tools .theme-dropdown {
|
||||||
|
padding: 0;
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .nav-tools .theme-btn {
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .update-banner .ub-panel {
|
||||||
|
top: auto;
|
||||||
|
bottom: calc(100% + 8px);
|
||||||
|
left: 0;
|
||||||
|
right: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
body[data-nav-layout="vertical"] {
|
||||||
|
padding-left: 0;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .nav-toggle {
|
||||||
|
top: 8px;
|
||||||
|
left: 8px;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] nav {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] nav.nav-open {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .container {
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .site-footer {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Native dropdowns: readable closed box in every theme. Several templates
|
||||||
|
reference background vars that were never defined, so be explicit here.
|
||||||
|
The color-scheme lines make the browser render the native options popup
|
||||||
|
to match (otherwise it pops up white while inheriting light text). */
|
||||||
|
select {
|
||||||
|
background-color: var(--card-bg);
|
||||||
|
color: var(--text);
|
||||||
|
border-color: var(--border);
|
||||||
|
}
|
||||||
|
[data-theme$="-dark"] select {
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
/* Explicit option colors: some browsers ignore color-scheme for the
|
||||||
|
native popup, so paint the rows directly (light text on card bg). */
|
||||||
|
[data-theme$="-dark"] select option {
|
||||||
|
background-color: var(--card-bg);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
[data-theme]:not([data-theme$="-dark"]) select {
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Theme dropdown: invisible hover bridge so moving the mouse from the
|
||||||
|
button down to the menu never drops hover (no more racing the cursor). */
|
||||||
|
.theme-dropdown::after {
|
||||||
|
content: '';
|
||||||
|
display: none;
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
.theme-dropdown:hover::after {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
body[data-nav-layout="vertical"] .theme-dropdown::after {
|
||||||
|
top: auto;
|
||||||
|
bottom: 100%;
|
||||||
|
}
|
||||||
+2
-2
@@ -367,7 +367,7 @@
|
|||||||
display: none;
|
display: none;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
right: 0;
|
right: 0;
|
||||||
background: #252530;
|
background: var(--nav-bg);
|
||||||
min-width: 290px;
|
min-width: 290px;
|
||||||
max-height: 80vh;
|
max-height: 80vh;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
@@ -375,7 +375,7 @@
|
|||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
border: 1px solid #404050;
|
border: 1px solid rgba(255,255,255,0.1);
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-grid {
|
.theme-grid {
|
||||||
|
|||||||
@@ -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 '—'|safe }}</td>
|
<td>{{ a.character_name or '-' }}</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
@@ -0,0 +1,808 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Backup - Dune Awakening Dashboard{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<div class="page-header">
|
||||||
|
<h1>Backup & Restore</h1>
|
||||||
|
<p>Create full server backups and restore to a new VM</p>
|
||||||
|
</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="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;">
|
||||||
|
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.
|
||||||
|
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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" style="margin-bottom:20px;">
|
||||||
|
<div class="card-header">
|
||||||
|
<span>Backups</span>
|
||||||
|
<button onclick="createBackup()" id="create-btn" style="padding:6px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Create Backup</button>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:12px;">
|
||||||
|
Creates a full snapshot: game database, K8s resources, RMQ definitions, and dashboard settings.
|
||||||
|
Backups are stored locally in <code>./backups/</code>.
|
||||||
|
</p>
|
||||||
|
<div id="backup-list">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;">Loading backups...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" style="margin-bottom:20px;">
|
||||||
|
<div class="card-header">
|
||||||
|
<span>Scheduled Backups</span>
|
||||||
|
<button onclick="runScheduledNow()" id="run-sched-btn" style="padding:6px 16px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:13px;">Run Now</button>
|
||||||
|
<button onclick="saveSchedule()" id="save-sched-btn" style="padding:6px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Save</button>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:12px;">
|
||||||
|
Automatically create backups on a schedule. Old backups beyond the keep limit are deleted.
|
||||||
|
</p>
|
||||||
|
<div id="schedule-status" style="font-size:13px;margin-bottom:10px;color:var(--text-muted);">Loading schedule...</div>
|
||||||
|
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
|
||||||
|
<div>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;margin-bottom:8px;">
|
||||||
|
<input type="checkbox" id="sched-enabled"> <span>Enable scheduled backups</span>
|
||||||
|
</label>
|
||||||
|
<div style="margin-bottom:8px;">
|
||||||
|
<div style="display:flex;gap:8px;margin-bottom:8px;">
|
||||||
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="radio" name="sched-mode" value="interval" checked onchange="toggleSchedMode()">
|
||||||
|
Interval
|
||||||
|
</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="radio" name="sched-mode" value="schedule" onchange="toggleSchedMode()">
|
||||||
|
Specific days & time
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div id="sched-interval-fields" style="display:flex;gap:6px;align-items:center;">
|
||||||
|
<input type="number" id="sched-days" value="1" min="0" max="365"
|
||||||
|
style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
<span style="font-size:12px;color:var(--text-muted);">days</span>
|
||||||
|
<input type="number" id="sched-hours" value="0" min="0" max="23"
|
||||||
|
style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
<span style="font-size:12px;color:var(--text-muted);">hours</span>
|
||||||
|
<input type="number" id="sched-mins" value="0" min="0" max="59"
|
||||||
|
style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
<span style="font-size:12px;color:var(--text-muted);">mins</span>
|
||||||
|
</div>
|
||||||
|
<div id="sched-schedule-fields" style="display:none;">
|
||||||
|
<div style="display:flex;gap:6px;margin-bottom:6px;flex-wrap:wrap;">
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="0"> Mon
|
||||||
|
</label>
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="1"> Tue
|
||||||
|
</label>
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="2"> Wed
|
||||||
|
</label>
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="3"> Thu
|
||||||
|
</label>
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="4"> Fri
|
||||||
|
</label>
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="5"> Sat
|
||||||
|
</label>
|
||||||
|
<label style="font-size:12px;color:var(--text-muted);display:flex;align-items:center;gap:3px;cursor:pointer;">
|
||||||
|
<input type="checkbox" class="sched-day" value="6"> Sun
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:4px;">Times</label>
|
||||||
|
<div id="sched-times-list">
|
||||||
|
<div style="display:flex;gap:6px;margin-bottom:4px;">
|
||||||
|
<input type="time" class="sched-time" value="05:00"
|
||||||
|
style="padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">×</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button onclick="addSchedTime()" style="margin-top:4px;padding:4px 12px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:12px;">+ Add time</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div style="margin-bottom:8px;">
|
||||||
|
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Keep last N backups (0 = unlimited)</label>
|
||||||
|
<input type="number" id="sched-keep" value="5" min="0" max="100"
|
||||||
|
style="width:100%;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
</div>
|
||||||
|
<div style="margin-bottom:8px;">
|
||||||
|
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Encryption password (leave blank for no encryption)</label>
|
||||||
|
<input type="password" id="sched-password" placeholder="Leave blank to keep existing password"
|
||||||
|
style="width:100%;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="sched-next-run" style="font-size:12px;color:var(--text-muted);margin-top:8px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">
|
||||||
|
<span>Restore to Configured VM</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:16px;">
|
||||||
|
Restore a backup onto a <strong>freshly provisioned VM</strong> (Alpine Linux + K3s already installed).
|
||||||
|
The dashboard will guide you through each step.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div id="restore-steps">
|
||||||
|
<div class="restore-step" data-step="1">
|
||||||
|
<div class="step-number">1</div>
|
||||||
|
<div class="step-content">
|
||||||
|
<div class="step-title">Select Backup</div>
|
||||||
|
<div class="step-body">
|
||||||
|
<select id="restore-backup-select" style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;margin-bottom:8px;">
|
||||||
|
<option value="">-- Select a backup --</option>
|
||||||
|
</select>
|
||||||
|
<div id="restore-preview" style="display:none;font-size:13px;color:var(--text-muted);"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="restore-step" data-step="2">
|
||||||
|
<div class="step-number">2</div>
|
||||||
|
<div class="step-content">
|
||||||
|
<div class="step-title">Verify Connection</div>
|
||||||
|
<div class="step-body">
|
||||||
|
<p style="font-size:12px;color:var(--text-muted);margin-bottom:8px;">
|
||||||
|
Uses the SSH key and host configured in <code>settings.yaml</code>.
|
||||||
|
Ensure the dashboard is already set up to manage the target VM before restoring.
|
||||||
|
</p>
|
||||||
|
<button onclick="testConnection()" id="test-conn-btn" style="padding:8px 20px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Test Connection</button>
|
||||||
|
<div id="conn-result" style="margin-top:8px;font-size:13px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="restore-step" data-step="3">
|
||||||
|
<div class="step-number">3</div>
|
||||||
|
<div class="step-content">
|
||||||
|
<div class="step-title">Restore Options</div>
|
||||||
|
<div class="step-body">
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-db" checked> <span>Game database (from battlegroup backup)</span>
|
||||||
|
</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-dash-db" checked> <span>Dashboard database (bans, audit log, chat history, player IPs, settings)</span>
|
||||||
|
</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-k8s" checked> <span>K8s secrets & configmaps</span>
|
||||||
|
</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-battlegroup" checked> <span>Battlegroup CRD (triggers pod provisioning)</span>
|
||||||
|
</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-rmq" checked> <span>Re-create RMQ dashboard_admin user</span>
|
||||||
|
</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-ping-fix" checked> <span>Apply HOST_DATACENTER ping fix</span>
|
||||||
|
</label>
|
||||||
|
<div id="new-ip-group" style="margin:8px 0 0 24px;display:none;">
|
||||||
|
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">New public IP for ping fix</label>
|
||||||
|
<input type="text" id="restore-new-ip" placeholder="Same as VM IP if unchanged"
|
||||||
|
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
</div>
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="opt-settings" checked> <span>Restore dashboard settings.yaml</span>
|
||||||
|
</label>
|
||||||
|
<div style="margin:12px 0 0 0;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;">
|
||||||
|
<div style="font-size:12px;color:var(--text-muted);margin-bottom:4px;">Backup password (if encrypted)</div>
|
||||||
|
<input type="password" id="restore-password" placeholder="Leave blank if not password-protected"
|
||||||
|
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="restore-step" data-step="4">
|
||||||
|
<div class="step-number">4</div>
|
||||||
|
<div class="step-content">
|
||||||
|
<div class="step-title">Execute Restore</div>
|
||||||
|
<div class="step-body">
|
||||||
|
<p style="font-size:13px;color:var(--text-muted);margin-bottom:12px;">
|
||||||
|
This will <strong>overwrite all data</strong> on the target VM. Ensure you have selected the correct backup and VM.
|
||||||
|
</p>
|
||||||
|
<button onclick="startRestore()" id="restore-btn" style="padding:10px 24px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:14px;font-weight:bold;">
|
||||||
|
Start Restore
|
||||||
|
</button>
|
||||||
|
<div id="restore-progress" style="display:none;margin-top:16px;">
|
||||||
|
<div style="background:var(--border);border-radius:4px;height:20px;overflow:hidden;margin-bottom:12px;">
|
||||||
|
<div id="progress-bar" style="height:100%;background:var(--accent);border-radius:4px;width:0%;transition:width 0.5s;"></div>
|
||||||
|
</div>
|
||||||
|
<div id="progress-steps" style="font-size:13px;"></div>
|
||||||
|
<div id="restore-complete" style="display:none;margin-top:12px;padding:12px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;font-size:13px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.restore-step {
|
||||||
|
display:flex;gap:16px;padding:16px 0;
|
||||||
|
border-bottom:1px solid var(--border);
|
||||||
|
}
|
||||||
|
.restore-step:last-child { border-bottom:none; }
|
||||||
|
.step-number {
|
||||||
|
width:32px;height:32px;border-radius:50%;
|
||||||
|
background:var(--accent);color:#fff;
|
||||||
|
display:flex;align-items:center;justify-content:center;
|
||||||
|
font-weight:bold;font-size:14px;flex-shrink:0;
|
||||||
|
}
|
||||||
|
.step-content { flex:1; }
|
||||||
|
.step-title { font-weight:bold;font-size:14px;margin-bottom:8px;color:var(--text); }
|
||||||
|
.step-body { padding-left:0; }
|
||||||
|
#restore-steps .restore-step.disabled { opacity:0.4;pointer-events:none; }
|
||||||
|
.backup-row {
|
||||||
|
display:flex;align-items:center;padding:8px 12px;
|
||||||
|
border-bottom:1px solid var(--border);font-size:13px;
|
||||||
|
}
|
||||||
|
.backup-row:last-child { border-bottom:none; }
|
||||||
|
.backup-row:hover { background:var(--bg-hover); }
|
||||||
|
.backup-name { flex:1;font-weight:bold; }
|
||||||
|
.backup-size { width:80px;text-align:right;color:var(--text-muted); }
|
||||||
|
.backup-date { width:160px;color:var(--text-muted); }
|
||||||
|
.backup-actions { width:120px;text-align:right; }
|
||||||
|
.backup-actions button {
|
||||||
|
padding:4px 10px;font-size:12px;border:none;border-radius:3px;
|
||||||
|
cursor:pointer;margin-left:4px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- Create Backup Password Modal -->
|
||||||
|
<div id="create-pw-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('create-pw-modal')">
|
||||||
|
<div class="modal" style="max-width:400px;">
|
||||||
|
<div class="modal-header"><h3>Encrypt Backup (optional)</h3></div>
|
||||||
|
<div class="modal-body" style="padding:20px;">
|
||||||
|
<label style="display:block;margin-bottom:12px;font-size:13px;color:var(--text-light);">
|
||||||
|
Password
|
||||||
|
<input type="password" id="create-pw" placeholder="Leave blank for no encryption"
|
||||||
|
style="display:block;width:100%;margin-top:4px;padding:8px 10px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--card-bg);color:var(--text);">
|
||||||
|
</label>
|
||||||
|
<label style="display:block;font-size:13px;color:var(--text-light);">
|
||||||
|
Confirm password
|
||||||
|
<input type="password" id="create-pw-confirm" placeholder="Repeat password"
|
||||||
|
style="display:block;width:100%;margin-top:4px;padding:8px 10px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--card-bg);color:var(--text);">
|
||||||
|
</label>
|
||||||
|
<div id="create-pw-error" style="color:#c0392b;font-size:12px;margin-top:8px;display:none;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
|
<button onclick="closeModal('create-pw-modal')" class="btn-cancel">Cancel</button>
|
||||||
|
<button id="create-pw-confirm-btn" onclick="confirmCreateBackup()" class="btn-save" style="margin-left:8px;">Create Backup</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 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 class="modal" style="max-width:380px;">
|
||||||
|
<div class="modal-header"><h3>Verify Backup - <span id="verify-pw-label"></span></h3></div>
|
||||||
|
<div class="modal-body" style="padding:20px;">
|
||||||
|
<label style="display:block;font-size:13px;color:var(--text-light);">
|
||||||
|
Password
|
||||||
|
<input type="password" id="verify-pw" placeholder="Leave blank if not encrypted"
|
||||||
|
style="display:block;width:100%;margin-top:4px;padding:8px 10px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--card-bg);color:var(--text);">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
|
<button onclick="closeModal('verify-pw-modal')" class="btn-cancel">Cancel</button>
|
||||||
|
<button id="verify-pw-confirm-btn" onclick="confirmVerifyBackup()" class="btn-save" style="margin-left:8px;">Verify</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let restorePollInterval = null;
|
||||||
|
let _pendingVerifyBackup = null;
|
||||||
|
|
||||||
|
function showStatus(msg, type) {
|
||||||
|
const el = document.getElementById('backup-status');
|
||||||
|
el.textContent = msg;
|
||||||
|
el.className = 'error-banner ' + (type || 'info');
|
||||||
|
el.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideStatus() {
|
||||||
|
document.getElementById('backup-status').style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
function bytesStr(bytes) {
|
||||||
|
if (!bytes) return '0 B';
|
||||||
|
const u = ['B', 'KB', 'MB', 'GB'];
|
||||||
|
let i = 0;
|
||||||
|
let v = bytes;
|
||||||
|
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
|
||||||
|
return v.toFixed(1) + ' ' + u[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
if (!s) return '';
|
||||||
|
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Backup Management ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function loadBackups() {
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/list');
|
||||||
|
const d = await r.json();
|
||||||
|
const container = document.getElementById('backup-list');
|
||||||
|
if (!d.success || !d.backups || d.backups.length === 0) {
|
||||||
|
container.innerHTML = '<p style="color:var(--text-muted);font-size:13px;">No backups found. Click "Create Backup" to create one.</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let html = '<div style="background:var(--card-bg);border:1px solid var(--border);border-radius:4px;">';
|
||||||
|
html += '<div class="backup-row" style="font-weight:bold;color:var(--text-muted);font-size:12px;">';
|
||||||
|
html += '<div class="backup-name">Name</div><div class="backup-date">Created</div><div class="backup-size">Size</div><div class="backup-actions">Actions</div></div>';
|
||||||
|
for (const b of d.backups) {
|
||||||
|
html += '<div class="backup-row">';
|
||||||
|
const lock = b.password_protected ? ' 🔒' : '';
|
||||||
|
html += '<div class="backup-name">' + esc(b.name) + lock + '</div>';
|
||||||
|
html += '<div class="backup-date">' + esc(b.created) + '</div>';
|
||||||
|
html += '<div class="backup-size">' + bytesStr(b.size) + '</div>';
|
||||||
|
html += '<div class="backup-actions">';
|
||||||
|
html += '<button onclick="verifyBackup(\'' + esc(b.name) + '\')" title="Verify">✓</button>';
|
||||||
|
html += '<button onclick="deleteBackup(\'' + esc(b.name) + '\')" title="Delete" style="background:#c0392b;color:#fff;">✕</button>';
|
||||||
|
html += '</div></div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
container.innerHTML = html;
|
||||||
|
populateRestoreSelect(d.backups);
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('backup-list').innerHTML = '<p style="color:red;font-size:13px;">Failed to load backups: ' + esc(e.message) + '</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function populateRestoreSelect(backups) {
|
||||||
|
const sel = document.getElementById('restore-backup-select');
|
||||||
|
sel.innerHTML = '<option value="">-- Select a backup --</option>';
|
||||||
|
for (const b of backups) {
|
||||||
|
sel.innerHTML += '<option value="' + esc(b.name) + '">' + esc(b.name) + ' (' + bytesStr(b.size) + ')</option>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openModal(id) {
|
||||||
|
document.getElementById(id).style.display = '';
|
||||||
|
}
|
||||||
|
function closeModal(id) {
|
||||||
|
document.getElementById(id).style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createBackup() {
|
||||||
|
document.getElementById('create-pw').value = '';
|
||||||
|
document.getElementById('create-pw-confirm').value = '';
|
||||||
|
document.getElementById('create-pw-error').style.display = 'none';
|
||||||
|
openModal('create-pw-modal');
|
||||||
|
document.getElementById('create-pw').focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmCreateBackup() {
|
||||||
|
const pw = document.getElementById('create-pw').value;
|
||||||
|
const confirm = document.getElementById('create-pw-confirm').value;
|
||||||
|
const errEl = document.getElementById('create-pw-error');
|
||||||
|
if (pw !== confirm) {
|
||||||
|
errEl.textContent = 'Passwords do not match.';
|
||||||
|
errEl.style.display = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
errEl.style.display = 'none';
|
||||||
|
closeModal('create-pw-modal');
|
||||||
|
const btn = document.getElementById('create-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Creating...';
|
||||||
|
showStatus('Creating backup... this may take several minutes.', 'info');
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/create', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({password: pw || ''})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) {
|
||||||
|
const note = pw ? ' (password protected)' : '';
|
||||||
|
showStatus('Backup created successfully (' + bytesStr(d.size) + ')' + note, 'success');
|
||||||
|
} else {
|
||||||
|
showStatus('Backup failed: ' + esc(d.error), 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('Error: ' + esc(e.message), 'error');
|
||||||
|
}
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Create Backup';
|
||||||
|
loadBackups();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyBackup(name) {
|
||||||
|
_pendingVerifyBackup = name;
|
||||||
|
document.getElementById('verify-pw-label').textContent = name;
|
||||||
|
document.getElementById('verify-pw').value = '';
|
||||||
|
openModal('verify-pw-modal');
|
||||||
|
document.getElementById('verify-pw').focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmVerifyBackup() {
|
||||||
|
const name = _pendingVerifyBackup;
|
||||||
|
const pw = document.getElementById('verify-pw').value;
|
||||||
|
closeModal('verify-pw-modal');
|
||||||
|
showStatus('Verifying ' + name + '...', 'info');
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/verify', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({name, password: pw || ''})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success && d.valid) {
|
||||||
|
if (d.encrypted && d.files === 0) {
|
||||||
|
showStatus(name + ' is encrypted. ' + esc(d.note || 'Enter password to verify contents.'), 'info');
|
||||||
|
} else {
|
||||||
|
showStatus(name + ' verified: ' + d.files + ' files, ' + bytesStr(d.size), 'success');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showStatus('Verification failed: ' + esc(d.error || 'Unknown error'), 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('Error: ' + esc(e.message), 'error');
|
||||||
|
}
|
||||||
|
_pendingVerifyBackup = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteBackup(name) {
|
||||||
|
if (!confirm('Delete backup "' + name + '"? This cannot be undone.')) return;
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/delete', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({name})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) {
|
||||||
|
showStatus('Backup deleted.', 'info');
|
||||||
|
loadBackups();
|
||||||
|
} else {
|
||||||
|
showStatus('Delete failed.', 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('Error: ' + esc(e.message), 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Schedule ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function toggleSchedMode() {
|
||||||
|
const isInterval = document.querySelector('input[name="sched-mode"]:checked').value === 'interval';
|
||||||
|
document.getElementById('sched-interval-fields').style.display = isInterval ? 'flex' : 'none';
|
||||||
|
document.getElementById('sched-schedule-fields').style.display = isInterval ? 'none' : 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function schedDaysArray() {
|
||||||
|
const days = [];
|
||||||
|
document.querySelectorAll('.sched-day:checked').forEach(cb => days.push(parseInt(cb.value)));
|
||||||
|
return days;
|
||||||
|
}
|
||||||
|
|
||||||
|
function schedTimesArray() {
|
||||||
|
const times = [];
|
||||||
|
document.querySelectorAll('.sched-time').forEach(inp => { if (inp.value) times.push(inp.value); });
|
||||||
|
return times;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSchedTime() {
|
||||||
|
const list = document.getElementById('sched-times-list');
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.style.cssText = 'display:flex;gap:6px;margin-bottom:4px;';
|
||||||
|
div.innerHTML = '<input type="time" class="sched-time" value="05:00" style="padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
|
||||||
|
+ '<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">×</button>';
|
||||||
|
list.appendChild(div);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeSchedTime(btn) {
|
||||||
|
const list = document.getElementById('sched-times-list');
|
||||||
|
if (list.children.length > 1) {
|
||||||
|
btn.parentElement.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSchedule() {
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/schedule');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) return;
|
||||||
|
const s = d.schedule;
|
||||||
|
document.getElementById('sched-enabled').checked = s.enabled;
|
||||||
|
const mode = s.mode || 'interval';
|
||||||
|
const radio = document.querySelector('input[name="sched-mode"][value="' + mode + '"]');
|
||||||
|
if (radio) radio.checked = true;
|
||||||
|
toggleSchedMode();
|
||||||
|
if (s.interval_minutes) {
|
||||||
|
const total = s.interval_minutes;
|
||||||
|
document.getElementById('sched-days').value = Math.floor(total / 1440);
|
||||||
|
document.getElementById('sched-hours').value = Math.floor((total % 1440) / 60);
|
||||||
|
document.getElementById('sched-mins').value = total % 60;
|
||||||
|
}
|
||||||
|
(s.schedule_days || []).forEach(v => {
|
||||||
|
const cb = document.querySelector('.sched-day[value="' + v + '"]');
|
||||||
|
if (cb) cb.checked = true;
|
||||||
|
});
|
||||||
|
const times = s.schedule_times || ['05:00'];
|
||||||
|
const list = document.getElementById('sched-times-list');
|
||||||
|
list.innerHTML = '';
|
||||||
|
times.forEach(t => {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.style.cssText = 'display:flex;gap:6px;margin-bottom:4px;';
|
||||||
|
div.innerHTML = '<input type="time" class="sched-time" value="' + t + '" style="padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
|
||||||
|
+ '<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">×</button>';
|
||||||
|
list.appendChild(div);
|
||||||
|
});
|
||||||
|
document.getElementById('sched-keep').value = s.keep;
|
||||||
|
document.getElementById('sched-password').value = '';
|
||||||
|
const status = document.getElementById('schedule-status');
|
||||||
|
status.innerHTML = s.enabled
|
||||||
|
? '<span style="color:#27ae60;">● Active</span>'
|
||||||
|
: '<span style="color:var(--text-muted);">● Disabled</span>';
|
||||||
|
const nextEl = document.getElementById('sched-next-run');
|
||||||
|
if (s.enabled && s.next_run) {
|
||||||
|
const dt = new Date(s.next_run);
|
||||||
|
const pad = n => String(n).padStart(2,'0');
|
||||||
|
const fmt = pad(dt.getDate())+'-'+pad(dt.getMonth()+1)+'-'+dt.getFullYear()+' '+pad(dt.getHours())+':'+pad(dt.getMinutes());
|
||||||
|
nextEl.textContent = 'Next run: ' + fmt;
|
||||||
|
} else {
|
||||||
|
nextEl.textContent = '';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('schedule-status').textContent = 'Failed to load schedule';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveSchedule() {
|
||||||
|
const btn = document.getElementById('save-sched-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Saving...';
|
||||||
|
const mode = document.querySelector('input[name="sched-mode"]:checked').value;
|
||||||
|
const body = {
|
||||||
|
enabled: document.getElementById('sched-enabled').checked,
|
||||||
|
mode: mode,
|
||||||
|
keep: parseInt(document.getElementById('sched-keep').value),
|
||||||
|
password: document.getElementById('sched-password').value,
|
||||||
|
};
|
||||||
|
if (mode === 'interval') {
|
||||||
|
body.interval_minutes = parseInt(document.getElementById('sched-days').value) * 1440
|
||||||
|
+ parseInt(document.getElementById('sched-hours').value) * 60
|
||||||
|
+ parseInt(document.getElementById('sched-mins').value);
|
||||||
|
} else {
|
||||||
|
body.schedule_days = schedDaysArray();
|
||||||
|
body.schedule_times = schedTimesArray();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/schedule', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) {
|
||||||
|
showStatus('Schedule saved.', 'success');
|
||||||
|
loadSchedule();
|
||||||
|
} else {
|
||||||
|
showStatus('Failed to save schedule.', 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('Error: ' + esc(e.message), 'error');
|
||||||
|
}
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Save';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runScheduledNow() {
|
||||||
|
if (!confirm('Run a scheduled backup now? This will also apply retention.')) return;
|
||||||
|
const btn = document.getElementById('run-sched-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Running...';
|
||||||
|
showStatus('Running scheduled backup...', 'info');
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/run-scheduled', {method:'POST'});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) {
|
||||||
|
showStatus('Scheduled backup completed (' + bytesStr(d.size) + ')', 'success');
|
||||||
|
loadBackups();
|
||||||
|
loadSchedule();
|
||||||
|
} else {
|
||||||
|
showStatus('Scheduled backup failed: ' + esc(d.error), 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('Error: ' + esc(e.message), 'error');
|
||||||
|
}
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Run Now';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Restore Wizard ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
document.getElementById('restore-backup-select').addEventListener('change', async function() {
|
||||||
|
const name = this.value;
|
||||||
|
const preview = document.getElementById('restore-preview');
|
||||||
|
if (!name) { preview.style.display = 'none'; return; }
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/restore/preview', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({name})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) {
|
||||||
|
preview.style.display = 'block';
|
||||||
|
let html = '<div style="margin-top:8px;padding:8px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;">';
|
||||||
|
html += '<strong>Backup contents:</strong><br>';
|
||||||
|
html += 'Created: ' + esc(d.created) + '<br>';
|
||||||
|
const comps = d.components || [];
|
||||||
|
if (comps.length > 0) {
|
||||||
|
html += '<ul style="margin:4px 0 0 16px;padding:0;">';
|
||||||
|
for (const c of comps) {
|
||||||
|
html += '<li>' + esc(c.name) + ' (' + bytesStr(c.size) + ')</li>';
|
||||||
|
}
|
||||||
|
html += '</ul>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
preview.innerHTML = html;
|
||||||
|
}
|
||||||
|
} catch(e) { preview.innerHTML = '<span style="color:red;">Error loading preview</span>'; }
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('opt-ping-fix').addEventListener('change', function() {
|
||||||
|
document.getElementById('new-ip-group').style.display = this.checked ? 'block' : 'none';
|
||||||
|
});
|
||||||
|
|
||||||
|
async function testConnection() {
|
||||||
|
const resultDiv = document.getElementById('conn-result');
|
||||||
|
const btn = document.getElementById('test-conn-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Testing...';
|
||||||
|
resultDiv.innerHTML = 'Testing connection...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/restore/test-connection', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'}
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) {
|
||||||
|
let html = '<span style="color:#27ae60;">✓ Connected to ' + esc(d.hostname) + '</span>';
|
||||||
|
if (d.k8s_ok) html += '<br><span style="color:#27ae60;">✓ kubectl accessible</span>';
|
||||||
|
else html += '<br><span style="color:#f39c12;">⚠ kubectl not detected (is K3s installed?)</span>';
|
||||||
|
resultDiv.innerHTML = html;
|
||||||
|
} else {
|
||||||
|
resultDiv.innerHTML = '<span style="color:red;">✕ ' + esc(d.error) + '</span>';
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
resultDiv.innerHTML = '<span style="color:red;">Error: ' + esc(e.message) + '</span>';
|
||||||
|
}
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Test Connection';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startRestore() {
|
||||||
|
const name = document.getElementById('restore-backup-select').value;
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
showStatus('Please select a backup.', 'error');
|
||||||
|
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;
|
||||||
|
|
||||||
|
const password = document.getElementById('restore-password').value;
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
restore_db: document.getElementById('opt-db').checked,
|
||||||
|
restore_dash_db: document.getElementById('opt-dash-db').checked,
|
||||||
|
restore_k8s: document.getElementById('opt-k8s').checked,
|
||||||
|
restore_battlegroup: document.getElementById('opt-battlegroup').checked,
|
||||||
|
restore_rmq: document.getElementById('opt-rmq').checked,
|
||||||
|
restore_ping_fix: document.getElementById('opt-ping-fix').checked,
|
||||||
|
restore_settings: document.getElementById('opt-settings').checked,
|
||||||
|
new_ip: document.getElementById('restore-new-ip').value.trim() || '',
|
||||||
|
password: password || '',
|
||||||
|
};
|
||||||
|
|
||||||
|
const btn = document.getElementById('restore-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Restoring...';
|
||||||
|
|
||||||
|
document.getElementById('restore-progress').style.display = 'block';
|
||||||
|
document.getElementById('progress-bar').style.width = '0%';
|
||||||
|
document.getElementById('progress-steps').innerHTML = '';
|
||||||
|
document.getElementById('restore-complete').style.display = 'none';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/restore/start', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({name, options})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) {
|
||||||
|
showStatus('Restore failed to start: ' + esc(d.error), 'error');
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Start Restore';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
restorePollInterval = setInterval(() => pollRestore(d.restore_id), 2000);
|
||||||
|
} catch(e) {
|
||||||
|
showStatus('Error: ' + esc(e.message), 'error');
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Start Restore';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollRestore(restoreId) {
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/backup/restore/status', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({restore_id: restoreId})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) {
|
||||||
|
clearInterval(restorePollInterval);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('progress-bar').style.width = d.progress + '%';
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
for (let i = 0; i < d.steps.length; i++) {
|
||||||
|
const step = d.steps[i];
|
||||||
|
const completed = d.completed_steps.find(s => s.label === step);
|
||||||
|
if (completed) {
|
||||||
|
const icon = completed.success ? '✓' : '✕';
|
||||||
|
const color = completed.success ? '#27ae60' : '#c0392b';
|
||||||
|
html += '<div style="padding:4px 0;"><span style="color:' + color + ';">' + icon + '</span> ' + esc(step) + '</div>';
|
||||||
|
} else if (i < d.current_step) {
|
||||||
|
html += '<div style="padding:4px 0;color:var(--text-muted);">● ' + esc(step) + '</div>';
|
||||||
|
} else if (i === d.current_step) {
|
||||||
|
html += '<div style="padding:4px 0;color:var(--accent);font-weight:bold;">▶ ' + esc(step) + '</div>';
|
||||||
|
} else {
|
||||||
|
html += '<div style="padding:4px 0;color:var(--text-muted);opacity:0.5;">' + esc(step) + '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.getElementById('progress-steps').innerHTML = html;
|
||||||
|
|
||||||
|
if (d.status === 'completed' || d.status === 'completed_with_errors') {
|
||||||
|
clearInterval(restorePollInterval);
|
||||||
|
const completeDiv = document.getElementById('restore-complete');
|
||||||
|
completeDiv.style.display = 'block';
|
||||||
|
if (d.errors && d.errors.length > 0) {
|
||||||
|
completeDiv.innerHTML = '<strong style="color:#f39c12;">Restore completed with warnings:</strong><br>' +
|
||||||
|
d.errors.map(e => '<div style="color:#c0392b;font-size:12px;">⚠ ' + esc(e) + '</div>').join('');
|
||||||
|
} else {
|
||||||
|
completeDiv.innerHTML = '<strong style="color:#27ae60;">✓ Restore completed successfully!</strong>';
|
||||||
|
}
|
||||||
|
document.getElementById('restore-btn').disabled = false;
|
||||||
|
document.getElementById('restore-btn').textContent = 'Start Restore';
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
clearInterval(restorePollInterval);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadBackups();
|
||||||
|
loadSchedule();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
+363
-10
@@ -7,15 +7,47 @@
|
|||||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
|
||||||
|
<script>
|
||||||
|
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
||||||
|
async function csrfFetch(url, options = {}) {
|
||||||
|
options.headers = options.headers || {};
|
||||||
|
options.headers['X-CSRFToken'] = csrfToken;
|
||||||
|
return fetch(url, options);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
{% block head_extra %}{% endblock %}
|
{% block head_extra %}{% endblock %}
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<button class="nav-toggle" id="navToggle" title="Toggle nav layout" onclick="toggleNavLayout()">☰</button>
|
||||||
<nav>
|
<nav>
|
||||||
<div class="brand">DUNE DASHBOARD</div>
|
<div class="brand">DUNE DASHBOARD</div>
|
||||||
|
<!-- Horizontal: use grouped nav -->
|
||||||
|
<div class="nav-links-h">
|
||||||
|
{% for item in nav_groups %}
|
||||||
|
{% if item|length == 2 and item[1] is string %}
|
||||||
|
{# Simple link #}
|
||||||
|
<a href="{{ item[0] }}" class="{% if current_path == item[0] %}active{% endif %}">{{ item[1] }}</a>
|
||||||
|
{% else %}
|
||||||
|
{# Dropdown group: item[0] is label, item[1] is list of (href, label) #}
|
||||||
|
<div class="nav-dropdown">
|
||||||
|
<a class="nav-dropdown-toggle {% for ih, il in item[1] %}{% if current_path == ih %}active{% endif %}{% endfor %}">{{ item[0] }} ▾</a>
|
||||||
|
<div class="nav-dropdown-content">
|
||||||
|
{% for ih, il in item[1] %}
|
||||||
|
<a href="{{ ih }}" class="{% if current_path == ih %}active{% endif %}">{{ il }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<!-- Vertical nav links (flat list) -->
|
||||||
|
<div class="nav-links-v">
|
||||||
{% for href, label in nav_pages %}
|
{% for href, label in nav_pages %}
|
||||||
<a href="{{ href }}" class="{% if current_path == href %}active{% endif %}">{{ label }}</a>
|
<a href="{{ href }}" class="{% if current_path == href %}active{% endif %}">{{ label }}</a>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
</div>
|
||||||
<div class="spacer"></div>
|
<div class="spacer"></div>
|
||||||
|
<div class="nav-tools">
|
||||||
<div class="theme-dropdown">
|
<div class="theme-dropdown">
|
||||||
<button class="theme-btn" title="Theme">🎨</button>
|
<button class="theme-btn" title="Theme">🎨</button>
|
||||||
<div class="theme-dropdown-content">
|
<div class="theme-dropdown-content">
|
||||||
@@ -93,12 +125,14 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<span style="font-size:12px;color:var(--nav-text);display:flex;align-items:center;">
|
<div class="update-banner" id="update-banner" style="display:none;"></div>
|
||||||
|
</div>
|
||||||
|
<span class="nav-conn">
|
||||||
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
||||||
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
||||||
</span>
|
</span>
|
||||||
{% if current_user and current_user.is_authenticated %}
|
{% if current_user and current_user.is_authenticated %}
|
||||||
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
|
<a href="/logout" class="nav-logout">Logout</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</nav>
|
</nav>
|
||||||
<main class="container">
|
<main class="container">
|
||||||
@@ -108,14 +142,6 @@
|
|||||||
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
|
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
|
||||||
</footer>
|
</footer>
|
||||||
<script>
|
<script>
|
||||||
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
|
||||||
|
|
||||||
async function csrfFetch(url, options = {}) {
|
|
||||||
options.headers = options.headers || {};
|
|
||||||
options.headers['X-CSRFToken'] = csrfToken;
|
|
||||||
return fetch(url, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Theme System
|
// Theme System
|
||||||
function setTheme(themeName) {
|
function setTheme(themeName) {
|
||||||
document.documentElement.setAttribute('data-theme', themeName);
|
document.documentElement.setAttribute('data-theme', themeName);
|
||||||
@@ -135,7 +161,334 @@
|
|||||||
updateThemeUI(savedTheme);
|
updateThemeUI(savedTheme);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Nav Layout System (experimental vertical toggle)
|
||||||
|
function toggleNavLayout() {
|
||||||
|
const body = document.body;
|
||||||
|
const isMobile = window.innerWidth <= 768;
|
||||||
|
if (isMobile) {
|
||||||
|
document.querySelector('nav').classList.toggle('nav-open');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const current = body.getAttribute('data-nav-layout') || 'horizontal';
|
||||||
|
const next = current === 'horizontal' ? 'vertical' : 'horizontal';
|
||||||
|
body.setAttribute('data-nav-layout', next);
|
||||||
|
localStorage.setItem('dune-nav-layout', next);
|
||||||
|
}
|
||||||
|
|
||||||
|
function initNavLayout() {
|
||||||
|
const isMobile = window.innerWidth <= 768;
|
||||||
|
if (isMobile) {
|
||||||
|
document.body.setAttribute('data-nav-layout', 'vertical');
|
||||||
|
localStorage.removeItem('dune-nav-layout');
|
||||||
|
} else {
|
||||||
|
const saved = localStorage.getItem('dune-nav-layout') || 'horizontal';
|
||||||
|
document.body.setAttribute('data-nav-layout', saved);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('resize', function() {
|
||||||
|
const isMobile = window.innerWidth <= 768;
|
||||||
|
const current = document.body.getAttribute('data-nav-layout');
|
||||||
|
if (isMobile && current !== 'vertical') {
|
||||||
|
document.body.setAttribute('data-nav-layout', 'vertical');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
initTheme();
|
initTheme();
|
||||||
|
initNavLayout();
|
||||||
|
|
||||||
|
// Update banner (channel-aware self updates)
|
||||||
|
function escHtml(s) {
|
||||||
|
return String(s == null ? '' : s)
|
||||||
|
.replace(/&/g, '&').replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>').replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update widget: always-visible bell. Expands into a panel with a
|
||||||
|
// channel dropdown, manual check, patch notes overlay, update and
|
||||||
|
// silence controls. Auto-expands only for a new, non-silenced update.
|
||||||
|
let ubData = null;
|
||||||
|
let ubViewChannel = null; // channel shown in the panel; null = own channel
|
||||||
|
let ubViewVersion = null; // version picked in the dropdown; null = newest
|
||||||
|
let ubExpanded = false;
|
||||||
|
|
||||||
|
function ubChannelLatest(channel) {
|
||||||
|
if (!ubData) return null;
|
||||||
|
if (channel === ubData.channel) {
|
||||||
|
return ubData.latest ? { ...ubData.latest, available: ubData.available } : null;
|
||||||
|
}
|
||||||
|
const other = ubData.other_channel;
|
||||||
|
if (other && other.channel === channel) {
|
||||||
|
return other.latest ? { ...other.latest, available: other.available } : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// All known releases for a channel, newest first. Falls back to the
|
||||||
|
// single latest entry when the server payload predates release lists.
|
||||||
|
function ubChannelReleases(channel) {
|
||||||
|
if (!ubData) return [];
|
||||||
|
const lists = ubData.releases || {};
|
||||||
|
if (Array.isArray(lists[channel]) && lists[channel].length) {
|
||||||
|
return lists[channel];
|
||||||
|
}
|
||||||
|
const entry = ubChannelLatest(channel);
|
||||||
|
return entry ? [entry] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Numeric version compare mirroring the server's compare_versions:
|
||||||
|
// compares the X.Y.Z numbers only, so stable and experimental versions
|
||||||
|
// are comparable across channels. Returns -1, 0 or 1.
|
||||||
|
function ubCmpVer(a, b) {
|
||||||
|
const parse = (v) => {
|
||||||
|
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$/.exec(String(v || '').trim());
|
||||||
|
return m ? [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)] : null;
|
||||||
|
};
|
||||||
|
const pa = parse(a), pb = parse(b);
|
||||||
|
if (!pa && !pb) return 0;
|
||||||
|
if (!pa) return -1;
|
||||||
|
if (!pb) return 1;
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
if (pa[i] < pb[i]) return -1;
|
||||||
|
if (pa[i] > pb[i]) return 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ubHasNews() {
|
||||||
|
if (!ubData || ubData.silence_all) return false;
|
||||||
|
if (ubData.preview) return true;
|
||||||
|
const silenced = ubData.silenced_versions || [];
|
||||||
|
const cur = ubChannelLatest(ubData.channel);
|
||||||
|
if (cur && cur.available && !silenced.includes(cur.version)) return true;
|
||||||
|
const other = ubData.other_channel;
|
||||||
|
if (other && other.available && other.latest && !silenced.includes(other.latest.version)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshUpdateBanner(keepOpen) {
|
||||||
|
const el = document.getElementById('update-banner');
|
||||||
|
if (!el) return;
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/update/status');
|
||||||
|
ubData = await resp.json();
|
||||||
|
} catch (e) { return; } // leave whatever is shown
|
||||||
|
if (!ubData || !ubData.success) return;
|
||||||
|
if (!ubViewChannel) ubViewChannel = ubData.channel;
|
||||||
|
// Auto-expand for fresh news unless permanently muted.
|
||||||
|
if (!keepOpen && !ubExpanded && ubHasNews()) ubExpanded = true;
|
||||||
|
renderUpdateBanner();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Notes cache keyed by version (versions are server-validated to
|
||||||
|
// digits/dots/dashes only, so they are safe inside onclick quotes).
|
||||||
|
let ubNotesCache = {};
|
||||||
|
function ubSafeVer(v) {
|
||||||
|
return /^[0-9A-Za-z.\-]+$/.test(v || '') ? v : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderUpdateBanner() {
|
||||||
|
const el = document.getElementById('update-banner');
|
||||||
|
if (!el || !ubData) return;
|
||||||
|
if (!ubExpanded) {
|
||||||
|
const dot = ubHasNews() ? '<span class="ub-dot"></span>' : '';
|
||||||
|
const bell = ubData.silence_all ? '🔕' : '🔔';
|
||||||
|
el.style.display = 'block';
|
||||||
|
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(true)">${bell}${dot}</button></span>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = ubData;
|
||||||
|
const channels = [data.channel];
|
||||||
|
if (data.other_channel && data.other_channel.channel &&
|
||||||
|
!channels.includes(data.other_channel.channel)) {
|
||||||
|
channels.push(data.other_channel.channel);
|
||||||
|
}
|
||||||
|
const viewing = ubViewChannel || data.channel;
|
||||||
|
const entry = ubChannelLatest(viewing);
|
||||||
|
const silenced = data.silenced_versions || [];
|
||||||
|
const isSilenced = !!(entry && silenced.includes(entry.version));
|
||||||
|
const canUpdate = !!(entry && entry.available && !isSilenced);
|
||||||
|
|
||||||
|
// Per-version picker: every known release on the viewed channel,
|
||||||
|
// newest first. Older than the running version cannot be installed;
|
||||||
|
// same-numbered is a reinstall (works across channels); newer is
|
||||||
|
// an update. Settings and protected paths are preserved either way.
|
||||||
|
const releases = ubChannelReleases(viewing);
|
||||||
|
let picked = null;
|
||||||
|
if (releases.length) {
|
||||||
|
picked = releases.find(r => r.version === ubViewVersion) || releases[0];
|
||||||
|
if (!ubViewVersion || !releases.some(r => r.version === ubViewVersion)) {
|
||||||
|
ubViewVersion = picked.version;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const cmp = picked ? ubCmpVer(picked.version, data.current_version) : 0;
|
||||||
|
const pickedSilenced = !!(picked && silenced.includes(picked.version));
|
||||||
|
const pickedCanInstall = !!(picked && cmp >= 0 && !pickedSilenced);
|
||||||
|
|
||||||
|
let opts = '';
|
||||||
|
channels.forEach(ch => {
|
||||||
|
const label = ch === data.channel ? `${ch} (yours)` : ch;
|
||||||
|
opts += `<option value="${escHtml(ch)}"${ch === viewing ? ' selected' : ''}>${escHtml(label)}</option>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
let body = `<div class="ub-sub">You are on ${escHtml(data.current_version)} (${escHtml(data.channel)})</div>`;
|
||||||
|
body += `<div class="ub-row"><label>Channel: <select id="ub-channel" onchange="ubViewChannel=this.value;ubViewVersion=null;renderUpdateBanner();">${opts}</select></label>` +
|
||||||
|
`<button onclick="checkUpdatesNow()">Check now</button></div>`;
|
||||||
|
|
||||||
|
if (releases.length) {
|
||||||
|
let vopts = '';
|
||||||
|
releases.forEach(r => {
|
||||||
|
const c = ubCmpVer(r.version, data.current_version);
|
||||||
|
const tag = c < 0 ? ' — Older' : (c === 0 ? ' — Current (reinstall)' : ' — Update available');
|
||||||
|
vopts += `<option value="${escHtml(r.version)}"${picked && r.version === picked.version ? ' selected' : ''}>${escHtml(r.version)}${escHtml(tag)}</option>`;
|
||||||
|
});
|
||||||
|
body += `<div class="ub-row"><label>Version: <select id="ub-version" onchange="ubViewVersion=this.value;renderUpdateBanner();">${vopts}</select></label></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.preview && ubSafeVer(data.preview.version)) {
|
||||||
|
ubNotesCache[data.preview.version] = data.preview.notes || '';
|
||||||
|
body += `<div class="ub-title">${escHtml(data.preview.version)} <span class="ub-preview-tag">preview</span></div>` +
|
||||||
|
`<div class="ub-actions"><button class="ub-ghost" onclick="openNotesOverlay('${data.preview.version}')">Patch notes</button>` +
|
||||||
|
`<button class="ub-ghost" onclick="clearPreview()">Clear preview</button></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (picked && ubSafeVer(picked.version)) {
|
||||||
|
ubNotesCache[picked.version] = picked.notes || '';
|
||||||
|
const isCurrent = cmp === 0;
|
||||||
|
const stateLine = cmp < 0
|
||||||
|
? `<div class="ub-sub">${escHtml(picked.version)} is older than your current version — cannot install.</div>`
|
||||||
|
: (!pickedCanInstall && pickedSilenced)
|
||||||
|
? `<div class="ub-sub">${escHtml(picked.version)} silenced - a newer version will show again.</div>`
|
||||||
|
: isCurrent
|
||||||
|
? `<div class="ub-title">Reinstall: ${escHtml(picked.version)} (same as current)</div>`
|
||||||
|
: `<div class="ub-title">Update available: ${escHtml(picked.version)}</div>`;
|
||||||
|
body += stateLine;
|
||||||
|
body += '<div class="ub-actions">' +
|
||||||
|
(picked.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${picked.version}')">Patch notes</button>` : '') +
|
||||||
|
(pickedCanInstall ? (isCurrent
|
||||||
|
? `<button onclick="applyUpdate('${picked.version}')">Reinstall ${escHtml(picked.version)}</button>`
|
||||||
|
: `<button onclick="applyUpdate('${picked.version}')">Update to ${escHtml(picked.version)}</button>`) : '') +
|
||||||
|
(cmp > 0 && !pickedSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${picked.version}')">Silence this version</button>` : '') +
|
||||||
|
'</div>';
|
||||||
|
} else if (entry && ubSafeVer(entry.version)) {
|
||||||
|
ubNotesCache[entry.version] = entry.notes || '';
|
||||||
|
const stateLine = !entry.available
|
||||||
|
? `<div class="ub-sub">${escHtml(viewing)} is up to date at ${escHtml(entry.version)}.</div>`
|
||||||
|
: isSilenced
|
||||||
|
? `<div class="ub-sub">${escHtml(entry.version)} silenced - a newer version will show again.</div>`
|
||||||
|
: `<div class="ub-title">Update available: ${escHtml(entry.version)}</div>`;
|
||||||
|
body += stateLine;
|
||||||
|
body += '<div class="ub-actions">' +
|
||||||
|
(entry.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${entry.version}')">Patch notes</button>` : '') +
|
||||||
|
(canUpdate ? `<button onclick="applyUpdate('${entry.version}')">Update to ${escHtml(entry.version)}</button>` : '') +
|
||||||
|
(entry.available && !isSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${entry.version}')">Silence this version</button>` : '') +
|
||||||
|
'</div>';
|
||||||
|
} else if (!data.preview) {
|
||||||
|
body += `<div class="ub-sub">No ${escHtml(viewing)} releases found yet.</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
body += `<label class="ub-mute"><input type="checkbox"${data.silence_all ? ' checked' : ''} onchange="setUpdateMute(this.checked)"> Don't remind me again</label>` +
|
||||||
|
'<div class="ub-status" id="ub-status"></div>';
|
||||||
|
el.style.display = 'block';
|
||||||
|
const bellIcon = data.silence_all ? '🔕' : '🔔';
|
||||||
|
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(false)">${bellIcon}</button></span>` +
|
||||||
|
`<div class="ub-panel"><div class="ub-panel-head">Updates</div>` + body + `</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleUpdatePanel(open) {
|
||||||
|
ubExpanded = open;
|
||||||
|
renderUpdateBanner();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkUpdatesNow() {
|
||||||
|
const st = document.getElementById('ub-status');
|
||||||
|
if (st) st.textContent = 'Checking...';
|
||||||
|
try {
|
||||||
|
await csrfFetch('/api/update/check', { method: 'POST' });
|
||||||
|
} catch (e) { /* status refresh below reports */ }
|
||||||
|
refreshUpdateBanner(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openNotesOverlay(version) {
|
||||||
|
closeNotesOverlay();
|
||||||
|
const notes = ubNotesCache[version] || '';
|
||||||
|
const ov = document.createElement('div');
|
||||||
|
ov.id = 'ub-overlay';
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.className = 'ub-overlay-box';
|
||||||
|
const head = document.createElement('div');
|
||||||
|
head.className = 'ub-overlay-head';
|
||||||
|
const title = document.createElement('strong');
|
||||||
|
title.textContent = 'Patch notes - ' + version;
|
||||||
|
const close = document.createElement('button');
|
||||||
|
close.textContent = 'Close';
|
||||||
|
close.onclick = closeNotesOverlay;
|
||||||
|
head.appendChild(title);
|
||||||
|
head.appendChild(close);
|
||||||
|
const pre = document.createElement('pre');
|
||||||
|
pre.textContent = notes || 'No notes for this version.';
|
||||||
|
box.appendChild(head);
|
||||||
|
box.appendChild(pre);
|
||||||
|
ov.appendChild(box);
|
||||||
|
ov.onclick = function(e) { if (e.target === ov) closeNotesOverlay(); };
|
||||||
|
document.body.appendChild(ov);
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeNotesOverlay() {
|
||||||
|
const ov = document.getElementById('ub-overlay');
|
||||||
|
if (ov) ov.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clearPreview() {
|
||||||
|
await csrfFetch('/api/update/preview', { method: 'DELETE' });
|
||||||
|
refreshUpdateBanner(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyUpdate(version) {
|
||||||
|
const isReinstall = ubData && version === ubData.current_version;
|
||||||
|
const action = isReinstall ? 'Reinstall' : 'Update to';
|
||||||
|
if (!confirm(`${action} ${version}? Settings and protected files are preserved. The dashboard backs itself up, installs, then restarts. Players will be briefly disconnected from the panel (not the game).`)) return;
|
||||||
|
const st = document.getElementById('ub-status');
|
||||||
|
if (st) st.textContent = 'Updating - the panel will restart...';
|
||||||
|
try {
|
||||||
|
const resp = await csrfFetch('/api/update/apply', {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ version })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (st) st.textContent = data.success ? (data.message || 'Updating...') : ('Error: ' + (data.message || data.error || 'unknown'));
|
||||||
|
} catch (e) {
|
||||||
|
if (st) st.textContent = 'Error: ' + e.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function silenceUpdateVersion(version) {
|
||||||
|
await csrfFetch('/api/update/silence', {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ action: 'silence', version })
|
||||||
|
});
|
||||||
|
refreshUpdateBanner();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setUpdateMute(on) {
|
||||||
|
await csrfFetch('/api/update/silence', {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ action: on ? 'mute' : 'unmute' })
|
||||||
|
});
|
||||||
|
refreshUpdateBanner();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function unmuteUpdates() {
|
||||||
|
await csrfFetch('/api/update/silence', {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ action: 'unmute' })
|
||||||
|
});
|
||||||
|
refreshUpdateBanner();
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshUpdateBanner();
|
||||||
|
setInterval(refreshUpdateBanner, 10 * 60 * 1000);
|
||||||
</script>
|
</script>
|
||||||
{% block scripts %}{% endblock %}
|
{% block scripts %}{% endblock %}
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@
|
|||||||
<label style="display:flex;align-items:center;gap:4px;font-size:13px;color:var(--text-light);cursor:pointer;">
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;color:var(--text-light);cursor:pointer;">
|
||||||
<input type="checkbox" id="auto-refresh" style="cursor:pointer;"> Auto-refresh (30s)
|
<input type="checkbox" id="auto-refresh" style="cursor:pointer;"> Auto-refresh (30s)
|
||||||
</label>
|
</label>
|
||||||
<select id="filter-channel" style="padding:6px 12px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:13px;">
|
<select id="filter-channel" style="padding:6px 12px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:13px;">
|
||||||
<option value="all">All Channels</option>
|
<option value="all">All Channels</option>
|
||||||
<option value="Proximity">Proximity</option>
|
<option value="Proximity">Proximity</option>
|
||||||
<option value="Map">Map</option>
|
<option value="Map">Map</option>
|
||||||
|
|||||||
@@ -85,7 +85,7 @@
|
|||||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
|
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
|
||||||
<div>
|
<div>
|
||||||
<label>Incoming Transfers:</label>
|
<label>Incoming Transfers:</label>
|
||||||
<select id="incoming-transfers" style="width:100%;padding:6px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;margin-top:4px;">
|
<select id="incoming-transfers" style="width:100%;padding:6px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;margin-top:4px;">
|
||||||
<option value="0">Default (0)</option>
|
<option value="0">Default (0)</option>
|
||||||
<option value="10">Deny All (10)</option>
|
<option value="10">Deny All (10)</option>
|
||||||
<option value="20">From Private Only (20)</option>
|
<option value="20">From Private Only (20)</option>
|
||||||
|
|||||||
+157
-35
@@ -4,8 +4,7 @@
|
|||||||
|
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h1>Game Events</h1>
|
<h1>Game Events</h1>
|
||||||
<p>Recent activity from the game event log</p>
|
<p>What is happening on your server, in plain language</p>
|
||||||
<p style="font-size:11px;color:var(--text-muted);">Note: Solaris currency events may show incomplete history. Delta values may not sum to current balance.</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% if tunnel_down %}
|
{% if tunnel_down %}
|
||||||
@@ -14,56 +13,179 @@
|
|||||||
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
|
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
|
|
||||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
|
<div class="stats-grid">
|
||||||
<div class="card">
|
<div class="stat-card">
|
||||||
<div class="card-header">Game Events ({{ game_events|length }})</div>
|
<div class="label">Events (24h)</div>
|
||||||
|
<div class="value">{{ total_24h }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="label">Deaths (24h)</div>
|
||||||
|
<div class="value">{{ counts_24h.get(0, 0) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="label">Builds Placed (24h)</div>
|
||||||
|
<div class="value">{{ counts_24h.get(10, 0) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="label">Permission Changes (24h)</div>
|
||||||
|
<div class="value">{{ counts_24h.get(97, 0) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="label">Active Maps</div>
|
||||||
|
<div class="value">{{ maps|length }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Event Feed</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<form method="get" action="/events" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;margin-bottom:16px;">
|
||||||
|
<label style="font-size:13px;">Type:
|
||||||
|
<select name="type" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||||
|
<option value="all" {% if type_filter == 'all' %}selected{% endif %}>All types</option>
|
||||||
|
{% for tid, tlabel in type_options %}
|
||||||
|
<option value="{{ tid }}" {% if type_filter == tid %}selected{% endif %}>{{ tlabel }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label style="font-size:13px;">Map:
|
||||||
|
<select name="map" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||||
|
<option value="all" {% if map_filter == 'all' %}selected{% endif %}>All maps</option>
|
||||||
|
{% for m in maps %}
|
||||||
|
<option value="{{ m }}" {% if map_filter == m %}selected{% endif %}>{{ m }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label style="font-size:13px;">Player-facing:
|
||||||
|
<select name="facing" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||||
|
<option value="all" {% if facing_filter == 'all' %}selected{% endif %}>Both</option>
|
||||||
|
<option value="1" {% if facing_filter == '1' %}selected{% endif %}>Yes</option>
|
||||||
|
<option value="0" {% if facing_filter == '0' %}selected{% endif %}>No</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<button type="submit" style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Filter</button>
|
||||||
|
<a href="/events" style="padding:8px 16px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;font-size:13px;text-decoration:none;">Reset</a>
|
||||||
|
</form>
|
||||||
<div class="table-wrap">
|
<div class="table-wrap">
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>Time</th><th>Actor</th><th>Map</th><th>Type</th><th>Player</th><th>Position</th></tr>
|
<tr><th>Time</th><th>Event</th><th>Map</th><th>Details</th><th>Position</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for e in game_events[:25] %}
|
||||||
|
<tr>
|
||||||
|
<td style="font-size:11px;white-space:nowrap;">{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}</td>
|
||||||
|
<td><span class="badge">{{ e.label }}</span></td>
|
||||||
|
<td>{{ e.map or '' }}</td>
|
||||||
|
<td style="font-size:12px;">{{ e.summary or '-' }}</td>
|
||||||
|
<td style="font-size:11px;font-family:monospace;">{% if e.x is not none and e.y is not none %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="5" class="empty">No events match these filters</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if game_events|length > 25 %}
|
||||||
|
<div style="margin-top:12px;text-align:center;">
|
||||||
|
<button onclick="openEventsModal()" style="padding:8px 20px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Show all {{ game_events|length }} events</button>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="events-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeEventsModal()">
|
||||||
|
<div class="modal modal-wide">
|
||||||
|
<h3>All Events ({{ game_events|length }})</h3>
|
||||||
|
<div class="table-wrap" style="max-height:60vh;overflow-y:auto;">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Time</th><th>Event</th><th>Map</th><th>Details</th><th>Position</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for e in game_events %}
|
{% for e in game_events %}
|
||||||
<tr>
|
<tr>
|
||||||
<td style="font-size:11px;white-space:nowrap;">{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}</td>
|
<td style="font-size:11px;white-space:nowrap;">{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}</td>
|
||||||
<td>{{ e.actor_id }}</td>
|
<td><span class="badge">{{ e.label }}</span></td>
|
||||||
<td>{{ e.map or '' }}</td>
|
<td>{{ e.map or '' }}</td>
|
||||||
<td>{{ e.event_type }}</td>
|
<td style="font-size:12px;">{{ e.summary or '-' }}</td>
|
||||||
<td>{% if e.actor_name %}{{ e.actor_name }}{% else %}—{% endif %}</td>
|
<td style="font-size:11px;font-family:monospace;">{% if e.x is not none and e.y is not none %}{{ e.x|round(0)|int }}, {{ e.y|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 %}
|
|
||||||
<tr><td colspan="6" class="empty">No game events found</td></tr>
|
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div class="modal-actions" style="margin-top:12px;text-align:right;">
|
||||||
|
<button onclick="closeEventsModal()" class="btn-cancel">Close</button>
|
||||||
<div class="card">
|
|
||||||
<div class="card-header">Event Log ({{ event_logs|length }})</div>
|
|
||||||
<div class="table-wrap">
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr><th>Time</th><th>Category</th><th>Function</th><th>Message</th><th>Details</th></tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{% for e in event_logs %}
|
|
||||||
<tr>
|
|
||||||
<td style="font-size:11px;white-space:nowrap;">{{ e.event_time.strftime('%Y-%m-%d %H:%M') if e.event_time else '' }}</td>
|
|
||||||
<td><span class="badge badge-{{ e.category.lower() if e.category else 'none' }}">{{ e.category or '' }}</span></td>
|
|
||||||
<td style="font-size:11px;font-family:monospace;">{{ e.function_name or '' }}</td>
|
|
||||||
<td style="font-size:12px;">{{ e.message or '' }}</td>
|
|
||||||
<td style="font-size:10px;max-width:250px;word-break:break-word;">{% if e.meta %}<pre style="margin:0;font-size:10px;white-space:pre-wrap;">{{ e.meta | json_format }}</pre>{% endif %}</td>
|
|
||||||
</tr>
|
|
||||||
{% else %}
|
|
||||||
<tr><td colspan="5" class="empty">No event logs found</td></tr>
|
|
||||||
{% endfor %}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Solaris Movements ({{ solaris|length }})</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Time</th><th>Player</th><th>Change</th><th>Balance</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for s in solaris[:25] %}
|
||||||
|
<tr>
|
||||||
|
<td style="font-size:11px;white-space:nowrap;">{{ s.event_time.strftime('%Y-%m-%d %H:%M') if s.event_time else '' }}</td>
|
||||||
|
<td style="font-family:monospace;font-size:12px;">{{ s.fls_id or '' }}</td>
|
||||||
|
<td style="font-size:13px;font-weight:600;color:{% if s.delta >= 0 %}#27ae60{% else %}#e74c3c{% endif %};">{{ '+' if s.delta >= 0 else '' }}{{ s.delta | format_number }}</td>
|
||||||
|
<td style="font-size:12px;">{{ s.balance | format_number }}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="4" class="empty">No currency movements logged</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if solaris|length > 25 %}
|
||||||
|
<div style="margin-top:12px;text-align:center;">
|
||||||
|
<button onclick="openSolarisModal()" style="padding:8px 20px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Show all {{ solaris|length }} movements</button>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="solaris-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeSolarisModal()">
|
||||||
|
<div class="modal modal-wide">
|
||||||
|
<h3>All Solaris Movements ({{ solaris|length }})</h3>
|
||||||
|
<div class="table-wrap" style="max-height:60vh;overflow-y:auto;">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Time</th><th>Player</th><th>Change</th><th>Balance</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for s in solaris %}
|
||||||
|
<tr>
|
||||||
|
<td style="font-size:11px;white-space:nowrap;">{{ s.event_time.strftime('%Y-%m-%d %H:%M') if s.event_time else '' }}</td>
|
||||||
|
<td style="font-family:monospace;font-size:12px;">{{ s.fls_id or '' }}</td>
|
||||||
|
<td style="font-size:13px;font-weight:600;color:{% if s.delta >= 0 %}#27ae60{% else %}#e74c3c{% endif %};">{{ '+' if s.delta >= 0 else '' }}{{ s.delta | format_number }}</td>
|
||||||
|
<td style="font-size:12px;">{{ s.balance | format_number }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions" style="margin-top:12px;text-align:right;">
|
||||||
|
<button onclick="closeSolarisModal()" class="btn-cancel">Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function openEventsModal() { document.getElementById('events-modal').style.display = 'flex'; }
|
||||||
|
function closeEventsModal() { document.getElementById('events-modal').style.display = 'none'; }
|
||||||
|
function openSolarisModal() { document.getElementById('solaris-modal').style.display = 'flex'; }
|
||||||
|
function closeSolarisModal() { document.getElementById('solaris-modal').style.display = 'none'; }
|
||||||
|
document.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Escape') { closeEventsModal(); closeSolarisModal(); }
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
.view-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
|
.view-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
|
||||||
.view-info { display: flex; gap: 8px; align-items: center; }
|
.view-info { display: flex; gap: 8px; align-items: center; }
|
||||||
.view-actions { display: flex; gap: 8px; }
|
.view-actions { display: flex; gap: 8px; }
|
||||||
.view-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
|
.view-btn { padding: 6px 14px; background: var(--card-bg); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
|
||||||
.view-btn:hover { background: var(--bg-hover); }
|
.view-btn:hover { background: var(--bg-hover); }
|
||||||
.view-btn.primary { background: var(--primary); color: #fff; border-color: var(--primary); }
|
.view-btn.primary { background: var(--primary); color: #fff; border-color: var(--primary); }
|
||||||
.view-btn.primary:hover { background: var(--primary-dark); }
|
.view-btn.primary:hover { background: var(--primary-dark); }
|
||||||
|
|||||||
+30
-8
@@ -10,7 +10,7 @@
|
|||||||
<div class="fm-layout">
|
<div class="fm-layout">
|
||||||
<div class="fm-panel">
|
<div class="fm-panel">
|
||||||
<div class="fm-toolbar">
|
<div class="fm-toolbar">
|
||||||
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
|
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
|
||||||
<option value="">Loading...</option>
|
<option value="">Loading...</option>
|
||||||
</select>
|
</select>
|
||||||
<span style="flex:1;"></span>
|
<span style="flex:1;"></span>
|
||||||
@@ -43,7 +43,7 @@
|
|||||||
.fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
|
.fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
|
||||||
.fm-panel { min-height: 0; display: flex; flex-direction: column; }
|
.fm-panel { min-height: 0; display: flex; flex-direction: column; }
|
||||||
.fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
|
.fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
|
||||||
.fm-btn { padding: 6px 12px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
|
.fm-btn { padding: 6px 12px; background: var(--card-bg); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
|
||||||
.fm-btn:hover { background: var(--bg-hover); }
|
.fm-btn:hover { background: var(--bg-hover); }
|
||||||
.fm-btn.danger { color: var(--danger); border-color: var(--danger); }
|
.fm-btn.danger { color: var(--danger); border-color: var(--danger); }
|
||||||
.fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
|
.fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
|
||||||
@@ -125,15 +125,37 @@ 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">'+p[i]+'</span>'
|
? '<span class="sep">/</span><span class="current">'+seg+'</span>'
|
||||||
: '<span class="sep">/</span><span onclick="loadFiles(\''+b.replace(/'/g,"\\'")+'\')">'+p[i]+'</span>';
|
: '<span class="sep">/</span><span onclick="loadFiles(\''+escAttr(b.replace(/'/g,"\\'"))+'\')">'+seg+'</span>';
|
||||||
}
|
}
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
@@ -156,14 +178,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 = fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
const sp = escAttr(fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'"));
|
||||||
const sn = x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
const sn = escAttr(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':''}">${x.name}</span>
|
<span class="fm-fname ${x.is_dir?'dir':''}">${escHtml(x.name)}</span>
|
||||||
<span class="fm-fsize">${formatSize(x.size)}</span>
|
<span class="fm-fsize">${escHtml(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>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
.login-container {
|
.login-container {
|
||||||
background: var(--bg-card);
|
background: var(--card-bg);
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
|
|||||||
+2
-5
@@ -63,12 +63,9 @@
|
|||||||
<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 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 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>
|
</div>
|
||||||
<aside class="map-panel">
|
<aside class="map-panel">
|
||||||
<section class="panel-section">
|
<section class="panel-section">
|
||||||
@@ -171,7 +168,7 @@ function initMap() {
|
|||||||
markerClusterGroup = (typeof L.markerClusterGroup !== 'undefined')
|
markerClusterGroup = (typeof L.markerClusterGroup !== 'undefined')
|
||||||
? L.markerClusterGroup({
|
? L.markerClusterGroup({
|
||||||
chunkedLoading: true,
|
chunkedLoading: true,
|
||||||
maxClusterRadius: 5,
|
maxClusterRadius: 12,
|
||||||
spiderfyOnMaxZoom: true,
|
spiderfyOnMaxZoom: true,
|
||||||
showCoverageOnHover: false,
|
showCoverageOnHover: false,
|
||||||
iconCreateFunction: function(cluster) {
|
iconCreateFunction: function(cluster) {
|
||||||
|
|||||||
@@ -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 disabled. Log out first.</div>
|
<div style="font-size:12px;color:#e67e22;padding:8px 16px;">Player is online - editing is 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 reflect last game save — game server writes deltas on top of DB value.</div>
|
<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>
|
</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 disabled. Log out first.</div>
|
<div style="font-size:12px;color:#e67e22;padding:0 16px 8px;">Player is online - editing is 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 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>
|
<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>
|
||||||
</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 '—'|safe }}</td>
|
<td>{{ p.map or '-' }}</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 {
|
||||||
|
|||||||
+999
-56
File diff suppressed because it is too large.
Load diff
+262
-8
@@ -23,7 +23,7 @@
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
|
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
|
||||||
<span>Pod Shell</span>
|
<span>Pod Shell</span>
|
||||||
<select id="pod-select" style="padding:4px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;">
|
<select id="pod-select" style="padding:4px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;">
|
||||||
{% for pod in pods %}
|
{% for pod in pods %}
|
||||||
<option value="{{ pod.name }}">{{ pod.name }}</option>
|
<option value="{{ pod.name }}">{{ pod.name }}</option>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -35,27 +35,79 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">Pods ({{ pods|length }})</div>
|
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
|
||||||
|
<span>Pods (<span id="pod-count">{{ pods|length }}</span>)</span>
|
||||||
|
<button onclick="refreshPodList()" style="padding:4px 12px;background:var(--primary);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">↻ Refresh</button>
|
||||||
|
</div>
|
||||||
<div class="table-wrap">
|
<div class="table-wrap">
|
||||||
<table>
|
<table id="pods-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>Name</th><th>Role</th><th>Status</th></tr>
|
<tr><th>Name</th><th>Role</th><th>Status</th><th>Actions</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for pod in pods %}
|
{% for pod in pods %}
|
||||||
<tr>
|
<tr data-pod="{{ pod.name }}" data-role="{{ pod.role }}">
|
||||||
<td style="font-family:monospace;font-size:12px;">{{ pod.name }}</td>
|
<td style="font-family:monospace;font-size:12px;">{{ pod.name }}</td>
|
||||||
<td><span class="badge badge-{{ pod.role.lower() if pod.role else 'default' }}">{{ pod.role or 'default' }}</span></td>
|
<td><span class="badge badge-{{ (pod.role or 'default').lower() }}">{{ pod.role or 'default' }}</span></td>
|
||||||
<td><span class="badge badge-{{ pod.status.lower() }}">{{ pod.status }}</span></td>
|
<td><span class="badge badge-{{ pod.status.lower() }}">{{ pod.status }}</span></td>
|
||||||
|
<td style="white-space:nowrap;">
|
||||||
|
<button class="pod-btn shell-btn" onclick="shellPod('{{ pod.name }}')" title="Open shell">[>_]</button>
|
||||||
|
<button class="pod-btn logs-btn" onclick="fetchPodLogs('{{ pod.name }}')" title="View logs">[📄]</button>
|
||||||
|
<button class="pod-btn desc-btn" onclick="fetchPodDescribe('{{ pod.name }}')" title="Describe pod">[i]</button>
|
||||||
|
{% if pod.role == 'igw-database-operation' %}
|
||||||
|
<button class="pod-btn del-btn-safe" onclick="promptDeletePod('{{ pod.name }}', true)" title="Delete DB backup pod">[🗑 DB backup]</button>
|
||||||
|
{% else %}
|
||||||
|
<button class="pod-btn del-btn" onclick="promptDeletePod('{{ pod.name }}', false)" title="Delete pod">[🗑]</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr><td colspan="3" class="empty">No pods found</td></tr>
|
<tr><td colspan="4" class="empty">No pods found</td></tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Pod 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-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>
|
||||||
|
<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(--card-bg);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||||
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
|
<button onclick="closeModal('logs-modal')" class="btn-cancel">Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Pod 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-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>
|
||||||
|
<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(--card-bg);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||||
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
|
<button onclick="closeModal('describe-modal')" class="btn-cancel">Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Delete Confirmation Modal -->
|
||||||
|
<div id="delete-modal" class="modal-overlay" style="display:none;">
|
||||||
|
<div class="modal" style="max-width:450px;">
|
||||||
|
<div class="modal-header"><h3 id="delete-modal-title">Delete Pod</h3></div>
|
||||||
|
<div class="modal-body" style="padding:20px;">
|
||||||
|
<p id="delete-modal-message">Are you sure you want to delete this pod?</p>
|
||||||
|
<p style="font-family:monospace;font-size:14px;padding:8px 12px;background:var(--card-bg);border-radius:4px;margin:12px 0 0;" id="delete-pod-name-display"></p>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||||
|
<button onclick="closeModal('delete-modal')" class="btn-cancel">Cancel</button>
|
||||||
|
<button id="delete-confirm-btn" onclick="confirmDeletePod()" class="btn-danger" style="margin-left:8px;">Delete Pod</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -64,7 +116,10 @@
|
|||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
||||||
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
const socket = io();
|
// Polling only: the server runs in threading mode, which has no true
|
||||||
|
// websocket support. Letting the client attempt a websocket upgrade only
|
||||||
|
// produces "Cannot obtain socket from WSGI environment" tracebacks.
|
||||||
|
const socket = io({ transports: ['polling'] });
|
||||||
|
|
||||||
let termVM = null;
|
let termVM = null;
|
||||||
let termPod = null;
|
let termPod = null;
|
||||||
@@ -178,9 +233,208 @@ function setupTerminalInput(term, type) {
|
|||||||
socket.emit('shell_input', {data: data, type: type});
|
socket.emit('shell_input', {data: data, type: type});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Pod action functions ──────────────────────────────────────────
|
||||||
|
|
||||||
|
let _pendingDeletePod = null;
|
||||||
|
|
||||||
|
function openModal(id) {
|
||||||
|
document.getElementById(id).style.display = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal(id) {
|
||||||
|
document.getElementById(id).style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
function shellPod(name) {
|
||||||
|
const sel = document.getElementById('pod-select');
|
||||||
|
for (let i = 0; i < sel.options.length; i++) {
|
||||||
|
if (sel.options[i].value === name) {
|
||||||
|
sel.selectedIndex = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!connectedPod) {
|
||||||
|
toggleShell('pod');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchPodLogs(name) {
|
||||||
|
document.getElementById('logs-pod-name').textContent = name;
|
||||||
|
document.getElementById('logs-content').style.display = 'none';
|
||||||
|
document.getElementById('logs-loading').style.display = '';
|
||||||
|
document.getElementById('logs-content').textContent = '';
|
||||||
|
openModal('logs-modal');
|
||||||
|
csrfFetch('/api/pod/logs', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({pod: name}),
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
document.getElementById('logs-loading').style.display = 'none';
|
||||||
|
if (data.success) {
|
||||||
|
const el = document.getElementById('logs-content');
|
||||||
|
el.textContent = data.logs || '(empty logs)';
|
||||||
|
el.style.display = '';
|
||||||
|
} else {
|
||||||
|
document.getElementById('logs-content').textContent = 'Error: ' + (data.error || 'Unknown');
|
||||||
|
document.getElementById('logs-content').style.display = '';
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
document.getElementById('logs-loading').style.display = 'none';
|
||||||
|
document.getElementById('logs-content').textContent = 'Request failed: ' + err;
|
||||||
|
document.getElementById('logs-content').style.display = '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchPodDescribe(name) {
|
||||||
|
document.getElementById('describe-pod-name').textContent = name;
|
||||||
|
document.getElementById('describe-content').style.display = 'none';
|
||||||
|
document.getElementById('describe-loading').style.display = '';
|
||||||
|
document.getElementById('describe-content').textContent = '';
|
||||||
|
openModal('describe-modal');
|
||||||
|
csrfFetch('/api/pod/describe', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({pod: name}),
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
document.getElementById('describe-loading').style.display = 'none';
|
||||||
|
if (data.success) {
|
||||||
|
const el = document.getElementById('describe-content');
|
||||||
|
el.textContent = data.describe || '(empty)';
|
||||||
|
el.style.display = '';
|
||||||
|
} else {
|
||||||
|
document.getElementById('describe-content').textContent = 'Error: ' + (data.error || 'Unknown');
|
||||||
|
document.getElementById('describe-content').style.display = '';
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
document.getElementById('describe-loading').style.display = 'none';
|
||||||
|
document.getElementById('describe-content').textContent = 'Request failed: ' + err;
|
||||||
|
document.getElementById('describe-content').style.display = '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function promptDeletePod(name, safe) {
|
||||||
|
_pendingDeletePod = name;
|
||||||
|
document.getElementById('delete-pod-name-display').textContent = name;
|
||||||
|
const title = document.getElementById('delete-modal-title');
|
||||||
|
const msg = document.getElementById('delete-modal-message');
|
||||||
|
const btn = document.getElementById('delete-confirm-btn');
|
||||||
|
if (safe) {
|
||||||
|
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?';
|
||||||
|
btn.className = 'btn-edit';
|
||||||
|
btn.textContent = 'Delete Backup Pod';
|
||||||
|
} else {
|
||||||
|
title.textContent = 'Delete Pod?';
|
||||||
|
msg.innerHTML = 'Deleting a pod will restart it. Depending on the pod role, this may cause a brief service interruption. Proceed?';
|
||||||
|
btn.className = 'btn-danger';
|
||||||
|
btn.textContent = 'Delete Pod';
|
||||||
|
}
|
||||||
|
openModal('delete-modal');
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmDeletePod() {
|
||||||
|
const name = _pendingDeletePod;
|
||||||
|
if (!name) return;
|
||||||
|
closeModal('delete-modal');
|
||||||
|
const btn = document.querySelector(`[data-pod="${name}"] .del-btn, [data-pod="${name}"] .del-btn-safe`);
|
||||||
|
if (btn) { btn.textContent = '...'; btn.disabled = true; }
|
||||||
|
csrfFetch('/api/pod/delete', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({pod: name}),
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.success) {
|
||||||
|
setTimeout(refreshPodList, 3000);
|
||||||
|
} else {
|
||||||
|
alert('Delete failed: ' + (data.error || 'Unknown'));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
alert('Delete request failed: ' + err);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
_pendingDeletePod = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshPodList() {
|
||||||
|
csrfFetch('/api/pods')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
if (!data.success) return;
|
||||||
|
const tbody = document.querySelector('#pods-table tbody');
|
||||||
|
const countEl = document.getElementById('pod-count');
|
||||||
|
if (!tbody) return;
|
||||||
|
tbody.innerHTML = '';
|
||||||
|
if (!data.pods || data.pods.length === 0) {
|
||||||
|
tbody.innerHTML = '<tr><td colspan="4" class="empty">No pods found</td></tr>';
|
||||||
|
if (countEl) countEl.textContent = '0';
|
||||||
|
// Also update pod select
|
||||||
|
const sel = document.getElementById('pod-select');
|
||||||
|
sel.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (countEl) countEl.textContent = data.pods.length;
|
||||||
|
// Rebuild pod select
|
||||||
|
const sel = document.getElementById('pod-select');
|
||||||
|
sel.innerHTML = '';
|
||||||
|
data.pods.forEach(p => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = p.name;
|
||||||
|
opt.textContent = p.name;
|
||||||
|
sel.appendChild(opt);
|
||||||
|
// Build table row
|
||||||
|
const tr = document.createElement('tr');
|
||||||
|
tr.dataset.pod = p.name;
|
||||||
|
tr.dataset.role = p.role || '';
|
||||||
|
const role = p.role || 'default';
|
||||||
|
const roleLower = role.toLowerCase();
|
||||||
|
tr.innerHTML = `
|
||||||
|
<td style="font-family:monospace;font-size:12px;">${p.name}</td>
|
||||||
|
<td><span class="badge badge-${roleLower}">${role}</span></td>
|
||||||
|
<td><span class="badge badge-${p.status.toLowerCase()}">${p.status}</span></td>
|
||||||
|
<td style="white-space:nowrap;">
|
||||||
|
<button class="pod-btn shell-btn" onclick="shellPod('${p.name}')" title="Open shell">[>_]</button>
|
||||||
|
<button class="pod-btn logs-btn" onclick="fetchPodLogs('${p.name}')" title="View logs">[📄]</button>
|
||||||
|
<button class="pod-btn desc-btn" onclick="fetchPodDescribe('${p.name}')" title="Describe pod">[i]</button>
|
||||||
|
${p.role === 'igw-database-operation'
|
||||||
|
? `<button class="pod-btn del-btn-safe" onclick="promptDeletePod('${p.name}', true)" title="Delete DB backup pod">[🗑 DB backup]</button>`
|
||||||
|
: `<button class="pod-btn del-btn" onclick="promptDeletePod('${p.name}', false)" title="Delete pod">[🗑]</button>`
|
||||||
|
}
|
||||||
|
</td>`;
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
<style>
|
<style>
|
||||||
.xterm { height: 100%; }
|
.xterm { height: 100%; }
|
||||||
.xterm-viewport { overflow-y: auto !important; }
|
.xterm-viewport { overflow-y: auto !important; }
|
||||||
|
.pod-btn {
|
||||||
|
padding: 2px 6px; border: none; border-radius: 3px;
|
||||||
|
cursor: pointer; font-size: 11px; font-family: monospace;
|
||||||
|
margin: 0 2px; line-height: 1.6;
|
||||||
|
}
|
||||||
|
.shell-btn { background: var(--primary); color: #fff; }
|
||||||
|
.shell-btn:hover { opacity: .85; }
|
||||||
|
.logs-btn { background: #5a6c7d; color: #fff; }
|
||||||
|
.logs-btn:hover { opacity: .85; }
|
||||||
|
.desc-btn { background: #6c5a7d; color: #fff; }
|
||||||
|
.desc-btn:hover { opacity: .85; }
|
||||||
|
.del-btn { background: #c0392b; color: #fff; }
|
||||||
|
.del-btn:hover { opacity: .85; }
|
||||||
|
.del-btn-safe { background: #27ae60; color: #fff; padding: 2px 8px; }
|
||||||
|
.del-btn-safe:hover { opacity: .85; }
|
||||||
|
.pod-btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
</style>
|
</style>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -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>
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""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
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Tests for game event summaries and solaris log parsing."""
|
||||||
|
|
||||||
|
from app.utils.events import (
|
||||||
|
clean_name,
|
||||||
|
event_label,
|
||||||
|
parse_solaris_meta,
|
||||||
|
summarize_game_event,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLabels:
|
||||||
|
def test_known_types(self):
|
||||||
|
assert event_label(0) == 'Death'
|
||||||
|
assert event_label(97) == 'Permission change'
|
||||||
|
|
||||||
|
def test_unknown_type_falls_back(self):
|
||||||
|
assert event_label(12345) == 'Event 12345'
|
||||||
|
assert event_label('xyz') == 'Event xyz'
|
||||||
|
|
||||||
|
|
||||||
|
class TestCleanName:
|
||||||
|
def test_strips_hashes(self):
|
||||||
|
assert clean_name('##MediumOrnithopter') == 'MediumOrnithopter'
|
||||||
|
assert clean_name('#Totem') == 'Totem'
|
||||||
|
|
||||||
|
def test_blanks(self):
|
||||||
|
assert clean_name(None) == ''
|
||||||
|
assert clean_name('None') == ''
|
||||||
|
assert clean_name('!!act#0') == ''
|
||||||
|
|
||||||
|
|
||||||
|
class TestSummaries:
|
||||||
|
def test_death(self):
|
||||||
|
msg = summarize_game_event(0, {'m_KillerType': 'NPC', 'm_DamageType': 'None'})
|
||||||
|
assert 'NPC' in msg
|
||||||
|
|
||||||
|
def test_build(self):
|
||||||
|
msg = summarize_game_event(10, {'m_CauserType': 'Player',
|
||||||
|
'm_BuildableName': 'Totem_Small_Placeable'})
|
||||||
|
assert 'Totem_Small_Placeable' in msg
|
||||||
|
|
||||||
|
def test_permission(self):
|
||||||
|
msg = summarize_game_event(97, {'m_PermissionActorName': '##MediumOrnithopter',
|
||||||
|
'm_OldPermissionRank': 'Associate',
|
||||||
|
'm_NewPermissionRank': 'CoOwner'})
|
||||||
|
assert 'Associate -> CoOwner' in msg
|
||||||
|
|
||||||
|
def test_power_hours(self):
|
||||||
|
msg = summarize_game_event(95, {'m_BuildableName': 'Totem_Placeable',
|
||||||
|
'm_PowerTimeLeftSeconds': 35959})
|
||||||
|
assert '9h' in msg
|
||||||
|
|
||||||
|
def test_never_raises(self):
|
||||||
|
assert summarize_game_event(0, 'not json {{{') == '' or True
|
||||||
|
assert summarize_game_event(999, None) == ''
|
||||||
|
assert summarize_game_event(97, {'m_OldPermissionRank': 'x'}) != '' or True
|
||||||
|
|
||||||
|
|
||||||
|
class TestSolarisMeta:
|
||||||
|
def test_python_repr_format(self):
|
||||||
|
parsed = parse_solaris_meta(
|
||||||
|
"{'event': 'adjust_player_virtual_currency_balance', "
|
||||||
|
"'fls_id': 'ABC123', 'solaris_delta': -27562, 'solaris_balance': 23135}")
|
||||||
|
assert parsed == {'fls_id': 'ABC123', 'delta': -27562, 'balance': 23135}
|
||||||
|
|
||||||
|
def test_json_format(self):
|
||||||
|
parsed = parse_solaris_meta(
|
||||||
|
'{"fls_id": "ABC", "solaris_delta": 6000, "solaris_balance": 100}')
|
||||||
|
assert parsed['delta'] == 6000
|
||||||
|
|
||||||
|
def test_garbage_returns_none(self):
|
||||||
|
assert parse_solaris_meta(None) is None
|
||||||
|
assert parse_solaris_meta('just a string') is None
|
||||||
|
assert parse_solaris_meta('[1, 2]') is None
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""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_plain_http_and_dead_socket_go_to_debug_only(self, caplog):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def orig(msg='', level=20, traceback=False):
|
||||||
|
calls.append((msg, level))
|
||||||
|
|
||||||
|
noises = [
|
||||||
|
"Client ('1.2.3.4', 123) attempted to speak plain HTTP into a "
|
||||||
|
"TCP connection configured for TLS-only traffic",
|
||||||
|
'[SSL: HTTP_REQUEST] http request (_ssl.c:1081)',
|
||||||
|
'OSError: [WinError 10038] An operation was attempted on '
|
||||||
|
'something that is not a socket',
|
||||||
|
]
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.utils.http_server'):
|
||||||
|
for noise in noises:
|
||||||
|
cheroot_error_filter(orig, noise)
|
||||||
|
assert calls == []
|
||||||
|
assert len([r for r in caplog.records
|
||||||
|
if r.levelno == logging.DEBUG]) == len(noises)
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
"""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
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""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 == []
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""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',
|
||||||
|
})
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""Tests for SSH known-hosts persistence (kills the unknown-key warning)."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from app.services import ssh as ssh_module
|
||||||
|
from app.services.ssh import SSHService
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeTransport:
|
||||||
|
def is_active(self):
|
||||||
|
return True
|
||||||
|
|
||||||
|
def set_keepalive(self, interval):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
instances = []
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.loaded = []
|
||||||
|
self.saved = []
|
||||||
|
self.connected = False
|
||||||
|
_FakeClient.instances.append(self)
|
||||||
|
|
||||||
|
def load_host_keys(self, path):
|
||||||
|
self.loaded.append(path)
|
||||||
|
if not os.path.exists(path):
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
def set_missing_host_key_policy(self, policy):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def connect(self, **kwargs):
|
||||||
|
self.connected = True
|
||||||
|
|
||||||
|
def get_transport(self):
|
||||||
|
return _FakeTransport()
|
||||||
|
|
||||||
|
def save_host_keys(self, path):
|
||||||
|
self.saved.append(path)
|
||||||
|
with open(path, 'w') as f:
|
||||||
|
f.write('# test known hosts\n')
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _service(monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr(ssh_module.paramiko, 'SSHClient', _FakeClient)
|
||||||
|
monkeypatch.setenv('DUNE_KNOWN_HOSTS', str(tmp_path / 'known_hosts'))
|
||||||
|
_FakeClient.instances.clear()
|
||||||
|
return SSHService('example.com', 'dune', ssh_key=None)
|
||||||
|
|
||||||
|
|
||||||
|
class TestKnownHosts:
|
||||||
|
def test_saves_after_connect(self, tmp_path, monkeypatch):
|
||||||
|
svc = _service(monkeypatch, tmp_path)
|
||||||
|
client = svc._get_client()
|
||||||
|
assert client.connected is True
|
||||||
|
assert client.saved == [str(tmp_path / 'known_hosts')]
|
||||||
|
assert os.path.exists(str(tmp_path / 'known_hosts'))
|
||||||
|
|
||||||
|
def test_loads_existing_file(self, tmp_path, monkeypatch):
|
||||||
|
hosts = tmp_path / 'known_hosts'
|
||||||
|
hosts.write_text('# existing\n')
|
||||||
|
svc = _service(monkeypatch, tmp_path)
|
||||||
|
client = svc._get_client()
|
||||||
|
assert client.loaded == [str(hosts)]
|
||||||
|
|
||||||
|
def test_reuses_live_client(self, tmp_path, monkeypatch):
|
||||||
|
svc = _service(monkeypatch, tmp_path)
|
||||||
|
first = svc._get_client()
|
||||||
|
second = svc._get_client()
|
||||||
|
assert first is second
|
||||||
|
assert len(_FakeClient.instances) == 1
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Tests for SSHService.run(quiet=...) - log level only, same results."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.services.ssh import SSHService
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeChannel:
|
||||||
|
def __init__(self, rc):
|
||||||
|
self._rc = rc
|
||||||
|
|
||||||
|
def settimeout(self, timeout):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def recv_exit_status(self):
|
||||||
|
return self._rc
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeStream:
|
||||||
|
def __init__(self, data, rc):
|
||||||
|
self._data = data
|
||||||
|
self.channel = _FakeChannel(rc)
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return self._data
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self, out=b'', err=b'Error from server (NotFound)', rc=1):
|
||||||
|
self._out = _FakeStream(out, rc)
|
||||||
|
self._err = _FakeStream(err, rc)
|
||||||
|
|
||||||
|
def get_transport(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def exec_command(self, command, timeout=None):
|
||||||
|
return None, self._out, self._err
|
||||||
|
|
||||||
|
|
||||||
|
def _service_with_fake_client():
|
||||||
|
svc = SSHService.__new__(SSHService)
|
||||||
|
import threading
|
||||||
|
svc.host = 'h'
|
||||||
|
svc.user = 'u'
|
||||||
|
svc.ssh_key = None
|
||||||
|
svc._client = _FakeClient()
|
||||||
|
svc._lock = threading.Lock()
|
||||||
|
# Bypass reconnect logic: _get_client returns the fake directly when
|
||||||
|
# its transport check is skipped. Patch at instance level.
|
||||||
|
svc._get_client = lambda: svc._client
|
||||||
|
return svc
|
||||||
|
|
||||||
|
|
||||||
|
class TestQuietFlag:
|
||||||
|
def test_results_identical_quiet_or_not(self, caplog):
|
||||||
|
svc = _service_with_fake_client()
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
out1, err1, rc1 = svc.run('kubectl get x', quiet=False)
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
out2, err2, rc2 = svc.run('kubectl get x', quiet=True)
|
||||||
|
assert (out1, err1, rc1) == (out2, err2, rc2) == ('', 'Error from server (NotFound)', 1)
|
||||||
|
|
||||||
|
def test_loud_logs_warning_quiet_logs_debug(self, caplog):
|
||||||
|
svc = _service_with_fake_client()
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
caplog.clear()
|
||||||
|
svc.run('kubectl get x', quiet=False)
|
||||||
|
loud_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
caplog.clear()
|
||||||
|
svc.run('kubectl get x', quiet=True)
|
||||||
|
quiet_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||||
|
assert logging.WARNING in loud_levels
|
||||||
|
assert logging.WARNING not in quiet_levels
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
"""Tests for channel-aware self updates (no network - releases are stubbed)."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.services.updater import (
|
||||||
|
UpdateService,
|
||||||
|
channel_of,
|
||||||
|
compare_versions,
|
||||||
|
parse_version,
|
||||||
|
release_matches_channel,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def make_releases():
|
||||||
|
return [
|
||||||
|
{'tag_name': 'v0.7.5-experimental', 'body': 'exp notes',
|
||||||
|
'zipball_url': 'https://example.com/exp.zip'},
|
||||||
|
{'tag_name': 'v0.7.4', 'body': 'stable notes',
|
||||||
|
'zipball_url': 'https://example.com/stable.zip'},
|
||||||
|
{'tag_name': 'v0.7.3-Experimental', 'body': 'old exp',
|
||||||
|
'zipball_url': 'https://example.com/old.zip'},
|
||||||
|
{'tag_name': 'v0.7.3', 'draft': True, 'body': 'draft',
|
||||||
|
'zipball_url': 'https://example.com/draft.zip'},
|
||||||
|
{'tag_name': 'not-a-version', 'body': 'x',
|
||||||
|
'zipball_url': 'https://example.com/x.zip'},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def make_service(tmp_path, version='0.7.4-experimental'):
|
||||||
|
(tmp_path / 'VERSION').write_text(version + '\n')
|
||||||
|
return UpdateService(str(tmp_path))
|
||||||
|
|
||||||
|
|
||||||
|
class TestVersions:
|
||||||
|
def test_parse(self):
|
||||||
|
assert parse_version('v0.7.5-experimental') == ((0, 7, 5), 'experimental')
|
||||||
|
assert parse_version('0.7.3') == ((0, 7, 3), '')
|
||||||
|
assert parse_version(' v1.2.3 ') == ((1, 2, 3), '')
|
||||||
|
assert parse_version('garbage') is None
|
||||||
|
assert parse_version('') is None
|
||||||
|
assert parse_version(None) is None
|
||||||
|
assert parse_version('1.2') is None
|
||||||
|
|
||||||
|
def test_channel(self):
|
||||||
|
assert channel_of('0.7.5-experimental') == 'experimental'
|
||||||
|
assert channel_of('0.7.5-Experimental') == 'experimental'
|
||||||
|
assert channel_of('0.7.3') == 'stable'
|
||||||
|
assert channel_of('garbage') == 'stable'
|
||||||
|
|
||||||
|
def test_compare(self):
|
||||||
|
assert compare_versions('0.7.5-experimental', '0.7.4-experimental') > 0
|
||||||
|
assert compare_versions('0.7.4', '0.7.4') == 0
|
||||||
|
assert compare_versions('0.7.3', '0.7.4') < 0
|
||||||
|
assert compare_versions('0.7.10', '0.7.9') > 0
|
||||||
|
assert compare_versions('garbage', '0.7.4') < 0
|
||||||
|
|
||||||
|
def test_channel_match(self):
|
||||||
|
assert release_matches_channel('v0.7.5-experimental', 'experimental')
|
||||||
|
assert release_matches_channel('v0.7.3-Experimental', 'experimental')
|
||||||
|
assert not release_matches_channel('v0.7.4', 'experimental')
|
||||||
|
assert release_matches_channel('v0.7.4', 'stable')
|
||||||
|
assert not release_matches_channel('v0.7.5-experimental', 'stable')
|
||||||
|
|
||||||
|
|
||||||
|
class TestPickLatest:
|
||||||
|
def test_experimental_picks_max_experimental(self):
|
||||||
|
best = UpdateService._pick_latest(make_releases(), 'experimental')
|
||||||
|
assert best['version'] == '0.7.5-experimental'
|
||||||
|
|
||||||
|
def test_stable_ignores_drafts(self):
|
||||||
|
best = UpdateService._pick_latest(make_releases(), 'stable')
|
||||||
|
assert best['version'] == '0.7.4'
|
||||||
|
|
||||||
|
def test_nothing_matching(self):
|
||||||
|
assert UpdateService._pick_latest([], 'stable') is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestReleaseLists:
|
||||||
|
def test_collect_channel_newest_first(self):
|
||||||
|
releases = UpdateService._collect_channel(make_releases(), 'experimental')
|
||||||
|
assert [e['version'] for e in releases] == [
|
||||||
|
'0.7.5-experimental', '0.7.3-Experimental']
|
||||||
|
|
||||||
|
def test_collect_skips_drafts_and_garbage(self):
|
||||||
|
releases = UpdateService._collect_channel(make_releases(), 'stable')
|
||||||
|
assert [e['version'] for e in releases] == ['0.7.4']
|
||||||
|
|
||||||
|
def test_status_includes_lists_and_find_searches_them(self, tmp_path, monkeypatch):
|
||||||
|
svc = make_service(tmp_path, '0.7.4-experimental')
|
||||||
|
monkeypatch.setattr(svc, '_fetch_releases', make_releases)
|
||||||
|
svc.check_for_updates()
|
||||||
|
status = svc.status()
|
||||||
|
assert [e['version'] for e in status['releases']['experimental']] == [
|
||||||
|
'0.7.5-experimental', '0.7.3-Experimental']
|
||||||
|
assert [e['version'] for e in status['releases']['stable']] == ['0.7.4']
|
||||||
|
# list payload stays lean (no download URLs for the panel)
|
||||||
|
assert 'zipball_url' not in status['releases']['experimental'][0]
|
||||||
|
# an older (non-latest) version is known but refused as a downgrade
|
||||||
|
assert svc._find_release('0.7.3-Experimental')['tag'] == 'v0.7.3-Experimental'
|
||||||
|
ok, msg = svc.apply_update('0.7.3-Experimental')
|
||||||
|
assert ok is False
|
||||||
|
assert 'owngrade' in msg or 'older' in msg
|
||||||
|
|
||||||
|
def test_cross_channel_same_number_is_reinstall(self, tmp_path, monkeypatch):
|
||||||
|
# Stable 0.7.4 installing experimental 0.7.4 is numeric-equal:
|
||||||
|
# allowed past validation (fails later only on download).
|
||||||
|
svc = make_service(tmp_path, '0.7.4')
|
||||||
|
monkeypatch.setattr(svc, '_fetch_releases', lambda: [
|
||||||
|
{'tag_name': 'v0.7.4-experimental', 'body': 'x',
|
||||||
|
'zipball_url': 'https://example.com/x.zip'},
|
||||||
|
])
|
||||||
|
svc.check_for_updates()
|
||||||
|
ok, msg = svc.apply_update('0.7.4-experimental')
|
||||||
|
assert ok is False
|
||||||
|
assert 'owngrade' not in msg and 'Unknown version' not in msg
|
||||||
|
|
||||||
|
|
||||||
|
class TestApplyRules:
|
||||||
|
def test_refuses_downgrade_without_network(self, tmp_path):
|
||||||
|
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||||
|
svc._latest = {'version': '0.7.6-experimental', 'tag': 'v0.7.6-experimental',
|
||||||
|
'notes': '', 'zipball_url': 'https://example.com/x.zip'}
|
||||||
|
ok, msg = svc.apply_update('0.7.4-experimental')
|
||||||
|
assert ok is False
|
||||||
|
assert 'owngrade' in msg or 'older' in msg
|
||||||
|
assert svc._update_in_progress is False
|
||||||
|
|
||||||
|
def test_refuses_unknown_version(self, tmp_path, monkeypatch):
|
||||||
|
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||||
|
monkeypatch.setattr(svc, '_fetch_releases', lambda: [])
|
||||||
|
ok, msg = svc.apply_update('9.9.9')
|
||||||
|
assert ok is False
|
||||||
|
assert 'Unknown version' in msg
|
||||||
|
|
||||||
|
def test_refuses_garbage(self, tmp_path):
|
||||||
|
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||||
|
ok, msg = svc.apply_update('not-a-version!!!')
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
def test_same_version_allowed_to_proceed(self, tmp_path, monkeypatch):
|
||||||
|
# Same version = reinstall. Must get past validation (it will then
|
||||||
|
# fail downloading from example.com, which proves the rule passed).
|
||||||
|
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||||
|
svc._latest = {'version': '0.7.5-experimental', 'tag': 'v0.7.5-experimental',
|
||||||
|
'notes': '', 'zipball_url': 'https://example.com/x.zip'}
|
||||||
|
ok, msg = svc.apply_update('0.7.5-experimental')
|
||||||
|
assert ok is False
|
||||||
|
assert 'owngrade' not in msg and 'Unknown version' not in msg
|
||||||
|
|
||||||
|
|
||||||
|
class TestPreview:
|
||||||
|
def test_set_clear_and_reject_garbage(self, tmp_path):
|
||||||
|
svc = make_service(tmp_path)
|
||||||
|
preview = svc.set_preview('0.7.6-experimental', 'notes here')
|
||||||
|
assert preview == {'version': '0.7.6-experimental', 'notes': 'notes here'}
|
||||||
|
assert svc.status()['preview'] == preview
|
||||||
|
svc.clear_preview()
|
||||||
|
assert svc.status()['preview'] is None
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
svc.set_preview('garbage!!!')
|
||||||
|
|
||||||
|
|
||||||
|
class TestSilence:
|
||||||
|
def test_round_trip(self, tmp_path):
|
||||||
|
svc = make_service(tmp_path)
|
||||||
|
state = svc.silence_version('0.7.6-experimental')
|
||||||
|
assert state['silenced_versions'] == ['0.7.6-experimental']
|
||||||
|
assert svc.get_silence() == state
|
||||||
|
state = svc.unsilence_version('0.7.6-experimental')
|
||||||
|
assert state['silenced_versions'] == []
|
||||||
|
state = svc.set_silence_all(True)
|
||||||
|
assert state['silence_all'] is True
|
||||||
|
state = svc.clear_silence()
|
||||||
|
assert state == {'silenced_versions': [], 'silence_all': False}
|
||||||
|
|
||||||
|
def test_status_reports_available_and_silence(self, tmp_path):
|
||||||
|
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||||
|
svc._latest = {'version': '0.7.6-experimental', 'tag': 'v0.7.6-experimental',
|
||||||
|
'notes': 'n', 'zipball_url': 'u'}
|
||||||
|
svc._other_latest = None
|
||||||
|
status = svc.status()
|
||||||
|
assert status['available'] is True
|
||||||
|
assert status['latest']['version'] == '0.7.6-experimental'
|
||||||
|
assert status['current_version'] == '0.7.5-experimental'
|
||||||
|
assert status['channel'] == 'experimental'
|
||||||
|
|
||||||
|
|
||||||
|
class TestLocalVersion:
|
||||||
|
def test_reads_version_file(self, tmp_path):
|
||||||
|
svc = make_service(tmp_path, '0.7.3')
|
||||||
|
assert svc.current_version == '0.7.3'
|
||||||
|
assert svc.channel == 'stable'
|
||||||
|
|
||||||
|
def test_missing_file_falls_back(self, tmp_path):
|
||||||
|
svc = UpdateService(str(tmp_path))
|
||||||
|
assert svc.current_version == '0.0.0'
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Tests for the self-watchdog liveness probe."""
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
|
||||||
|
from app.utils.watchdog import probe
|
||||||
|
|
||||||
|
|
||||||
|
class _Handler(BaseHTTPRequestHandler):
|
||||||
|
def do_GET(self):
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(b'ok')
|
||||||
|
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _serve_on_free_port():
|
||||||
|
server = HTTPServer(('127.0.0.1', 0), _Handler)
|
||||||
|
port = server.server_address[1]
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
return server, port
|
||||||
|
|
||||||
|
|
||||||
|
class TestProbe:
|
||||||
|
def test_healthy_server_answers(self):
|
||||||
|
server, port = _serve_on_free_port()
|
||||||
|
try:
|
||||||
|
assert probe('127.0.0.1', port, use_ssl=False) is True
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
|
||||||
|
def test_dead_port_fails(self):
|
||||||
|
# Port 1 is never listening.
|
||||||
|
assert probe('127.0.0.1', 1, use_ssl=False, timeout=2) is False
|
||||||
|
|
||||||
|
def test_ssl_mismatch_fails_plain(self):
|
||||||
|
server, port = _serve_on_free_port()
|
||||||
|
try:
|
||||||
|
# Plain HTTP server probed as HTTPS must fail, not hang.
|
||||||
|
assert probe('127.0.0.1', port, use_ssl=True, timeout=5) is False
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
Reference in new issue
Block a user