Compare commits
31
Commits
v0.5.0-nightly
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
518dd45f6d | ||
|
|
91c7abc771 | ||
|
|
cd00f984c5 | ||
|
|
aa0e5ec4e7 | ||
|
|
97cdbd3027 | ||
|
|
d7ce2a8caf | ||
|
|
715845751b | ||
|
|
bb5b17ef2a | ||
|
|
2c63aca276 | ||
|
|
bd9bd452c9 | ||
|
|
bb5065dd59 | ||
|
|
f48a09e8d3 | ||
|
|
9c61e198fa | ||
|
|
3b0bffe464 | ||
|
|
ce241a283d | ||
|
|
91944a0213 | ||
|
|
421b37e854 | ||
|
|
901c485c65 | ||
|
|
312abe7bce | ||
|
|
54d9d5db25 | ||
|
|
aee4028f5c | ||
|
|
a2d5af20c9 | ||
|
|
306ebcc871 | ||
|
|
3486f3b2cb | ||
|
|
42eec81081 | ||
|
|
65a1948fd1 | ||
|
|
1d1d2ab2ee | ||
|
|
32517999f3 | ||
|
|
5d19f772e5 | ||
|
|
9ea0829789 | ||
|
|
5ecf9f2417 |
No files matched your search
+9
-2
@@ -14,6 +14,10 @@ frontend/.pnpm-store/
|
|||||||
frontend/.vite/
|
frontend/.vite/
|
||||||
frontend/dist/
|
frontend/dist/
|
||||||
|
|
||||||
|
# New dashboard (removed - legacy only)
|
||||||
|
backend/
|
||||||
|
frontend/
|
||||||
|
|
||||||
# Virtual environments
|
# Virtual environments
|
||||||
venv/
|
venv/
|
||||||
env/
|
env/
|
||||||
@@ -34,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/
|
||||||
@@ -69,6 +74,8 @@ logs/
|
|||||||
|
|
||||||
# Database
|
# Database
|
||||||
*.db
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
*.sqlite3
|
*.sqlite3
|
||||||
instance/
|
instance/
|
||||||
|
|
||||||
@@ -99,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
|
||||||
@@ -25,20 +23,19 @@ chmod +x start.sh
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Interactive Maps** with calibrated coordinates
|
|
||||||
- **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**
|
||||||
- **Admin Tools** (ban/kick, history, read‑only SQL viewer)
|
- **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 request/SSH/K8s tracing
|
|
||||||
- **14 Dune house themes** (Atreides, Harkonnen, Fremen etc.)
|
|
||||||
- And yes, it’s all probably more than you’ll ever need — but it *felt right at the time*.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -46,67 +43,26 @@ chmod +x start.sh
|
|||||||
|
|
||||||
```
|
```
|
||||||
DuneDashboard/
|
DuneDashboard/
|
||||||
├── backend/ # Flask API + services
|
├── app/ # Flask/Jinja2 dashboard
|
||||||
├── frontend/ # React + Vite + Tailwind SPA
|
|
||||||
├── app/ # Legacy Flask/Jinja2 dashboard
|
|
||||||
├── launcher.ps1 # Windows launcher
|
├── launcher.ps1 # Windows launcher
|
||||||
├── start.sh # Linux/macOS launcher
|
├── start.sh # Linux/macOS launcher
|
||||||
└── settings.yaml # Generated config (gitignored)
|
└── settings.yaml # Generated config (gitignored)
|
||||||
```
|
```
|
||||||
|
|
||||||
> The legacy dashboard still works. Like an old Fremen still wandering the desert — reliable, but we don’t talk about it much.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Python 3.8+
|
- Python 3.8+
|
||||||
- Node.js 18+
|
|
||||||
- OpenSSH client
|
- OpenSSH client
|
||||||
- `kubectl` access to your Dune Awakening cluster
|
- `kubectl` access to your Dune Awakening cluster
|
||||||
- SSH access to the game server VM
|
- SSH access to the game server VM
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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
|
||||||
|
|
||||||
### Frontend
|
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
||||||
```bash
|
|
||||||
cd frontend
|
|
||||||
npm install
|
|
||||||
npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
```bash
|
|
||||||
cd backend
|
|
||||||
pip install -r requirements.txt
|
|
||||||
python run.py
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 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
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -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):
|
||||||
@@ -219,7 +227,7 @@ class DashboardDatabaseService:
|
|||||||
for row in old_rows:
|
for row in old_rows:
|
||||||
vals = [row[c] for c in cols]
|
vals = [row[c] for c in cols]
|
||||||
self.execute(
|
self.execute(
|
||||||
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
|
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders}) ON CONFLICT DO NOTHING",
|
||||||
vals,
|
vals,
|
||||||
)
|
)
|
||||||
migrated = True
|
migrated = True
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Backend package init.
|
|
||||||
@@ -1,287 +0,0 @@
|
|||||||
"""Settings loader — reads settings.yaml with env var overrides."""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import socket
|
|
||||||
import yaml
|
|
||||||
import logging
|
|
||||||
import copy
|
|
||||||
import secrets
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
DEFAULTS = {
|
|
||||||
"server": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"user": "dune",
|
|
||||||
"ssh_key": None,
|
|
||||||
"local_ip": None,
|
|
||||||
},
|
|
||||||
"dashboard": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5050,
|
|
||||||
"debug": False,
|
|
||||||
"secret_key": None,
|
|
||||||
"ssl_cert": None,
|
|
||||||
"ssl_key": None,
|
|
||||||
"ssl_domain": None,
|
|
||||||
"ssl_email": None,
|
|
||||||
"http_redirect": False,
|
|
||||||
"http_redirect_port": 80,
|
|
||||||
},
|
|
||||||
"database": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 15433,
|
|
||||||
"user": "postgres",
|
|
||||||
"password": None,
|
|
||||||
"name": "dune",
|
|
||||||
"schema": "dune",
|
|
||||||
"min_connections": 2,
|
|
||||||
"max_connections": 10,
|
|
||||||
"owner": "dune",
|
|
||||||
"dashboard_schema": "dashboard",
|
|
||||||
"dashboard_database_name": "dashboard",
|
|
||||||
},
|
|
||||||
"kubernetes": {
|
|
||||||
"namespace": "",
|
|
||||||
"battlegroup_script": "/home/dune/.dune/bin/battlegroup",
|
|
||||||
},
|
|
||||||
"director": {
|
|
||||||
"port": 32479,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
},
|
|
||||||
"rmq": {
|
|
||||||
"admin_host": "127.0.0.1",
|
|
||||||
"admin_port": 32686,
|
|
||||||
"game_host": "127.0.0.1",
|
|
||||||
"game_port": 32021,
|
|
||||||
"username": "admin",
|
|
||||||
"password": None,
|
|
||||||
"vhost": "%2f",
|
|
||||||
},
|
|
||||||
"filebrowser": {
|
|
||||||
"port": 18888,
|
|
||||||
},
|
|
||||||
"firewall": {
|
|
||||||
"block_filebrowser": True,
|
|
||||||
"block_director": True,
|
|
||||||
},
|
|
||||||
"cache": {
|
|
||||||
"chat_pod_ttl": 60,
|
|
||||||
"chat_messages_ttl": 10,
|
|
||||||
"static_data_ttl": 300,
|
|
||||||
"bgd_ttl": 10,
|
|
||||||
"rmq_ttl": 15,
|
|
||||||
},
|
|
||||||
"auth": {
|
|
||||||
"enabled": True,
|
|
||||||
"username": None,
|
|
||||||
"password_hash": None,
|
|
||||||
"shell_enabled": True,
|
|
||||||
},
|
|
||||||
"logging": {
|
|
||||||
"level": "INFO",
|
|
||||||
"file": "logs/dashboard.log",
|
|
||||||
"debug_file": "logs/debug.log",
|
|
||||||
"debug_enabled": False,
|
|
||||||
"max_bytes": 10485760,
|
|
||||||
"backup_count": 5,
|
|
||||||
},
|
|
||||||
"ssl": {
|
|
||||||
"check_interval_hours": 24,
|
|
||||||
"renewal_days_before_expiry": 30,
|
|
||||||
},
|
|
||||||
"maps": {
|
|
||||||
"default_map": "HaggaBasin",
|
|
||||||
"DeepDesert": {
|
|
||||||
"image": "maps/Deep_Desert.webp",
|
|
||||||
"label": "The Deep Desert",
|
|
||||||
"bounds": {
|
|
||||||
"min_x": -1268624.82,
|
|
||||||
"max_x": 1163312.83,
|
|
||||||
"min_y": -1266548.17,
|
|
||||||
"max_y": 1162416.13,
|
|
||||||
},
|
|
||||||
"flip_y": False,
|
|
||||||
"image_size": {"width": 8000, "height": 8000},
|
|
||||||
"default_zoom": 0.15,
|
|
||||||
},
|
|
||||||
"HaggaBasin": {
|
|
||||||
"image": "maps/HaggaBasin_8k.webp",
|
|
||||||
"label": "Hagga Basin",
|
|
||||||
"bounds": {
|
|
||||||
"min_x": -456752.21,
|
|
||||||
"max_x": 354547.46,
|
|
||||||
"min_y": -450630.14,
|
|
||||||
"max_y": 353821.95,
|
|
||||||
},
|
|
||||||
"flip_y": False,
|
|
||||||
"image_size": {"width": 8000, "height": 8000},
|
|
||||||
"default_zoom": 0.15,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def deep_merge(base, override):
|
|
||||||
"""Deep merge override dict into base dict."""
|
|
||||||
result = base.copy()
|
|
||||||
for key, value in override.items():
|
|
||||||
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
||||||
result[key] = deep_merge(result[key], value)
|
|
||||||
else:
|
|
||||||
result[key] = value
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _detect_local_ip():
|
|
||||||
"""Detect local IP address for VM connectivity."""
|
|
||||||
try:
|
|
||||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
||||||
s.settimeout(1)
|
|
||||||
s.connect(("8.8.8.8", 80))
|
|
||||||
local_ip = s.getsockname()[0]
|
|
||||||
s.close()
|
|
||||||
if local_ip:
|
|
||||||
logger.debug(f"Detected local IP: {local_ip}")
|
|
||||||
return local_ip
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Could not detect local IP: {e}")
|
|
||||||
return "127.0.0.1"
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_server_host(settings):
|
|
||||||
"""Validate and fix server.host if invalid or placeholder."""
|
|
||||||
server = settings.setdefault("server", {})
|
|
||||||
host = server.get("host", "")
|
|
||||||
|
|
||||||
local_ip = server.get("local_ip")
|
|
||||||
if local_ip:
|
|
||||||
local_ip_str = str(local_ip).strip()
|
|
||||||
if local_ip_str and local_ip_str not in ("", "null", "None", "YOUR_SERVER_IP", "YOUR_VM_IP"):
|
|
||||||
if local_ip_str.count(".") == 3 and all(part.isdigit() and 0 <= int(part) <= 255 for part in local_ip_str.split(".")):
|
|
||||||
server["host"] = local_ip_str
|
|
||||||
logger.info(f"Using server.local_ip override: {server['host']}")
|
|
||||||
return settings
|
|
||||||
|
|
||||||
host_str = str(host).strip() if host else ""
|
|
||||||
invalid_hosts = ("", "YOUR_SERVER_IP", "YOUR_VM_IP", "null", "None")
|
|
||||||
|
|
||||||
if host_str in invalid_hosts or not host_str:
|
|
||||||
detected_ip = _detect_local_ip()
|
|
||||||
server["host"] = detected_ip
|
|
||||||
logger.warning(f"Invalid server.host detected, using auto-detected IP: {detected_ip}")
|
|
||||||
logger.warning("To fix: Edit settings.yaml and set server.host to your VM's IP address")
|
|
||||||
|
|
||||||
return settings
|
|
||||||
|
|
||||||
|
|
||||||
def _find_missing_keys(defaults, current, path=""):
|
|
||||||
"""Find keys present in defaults but missing in current."""
|
|
||||||
missing = []
|
|
||||||
for key, val in defaults.items():
|
|
||||||
new_path = f"{path}.{key}" if path else key
|
|
||||||
if key not in current:
|
|
||||||
missing.append(new_path)
|
|
||||||
elif isinstance(val, dict) and isinstance(current.get(key), dict):
|
|
||||||
missing.extend(_find_missing_keys(val, current[key], new_path))
|
|
||||||
return missing
|
|
||||||
|
|
||||||
|
|
||||||
def load_settings(settings_path=None):
|
|
||||||
"""Load settings from YAML file with defaults and env var overrides."""
|
|
||||||
if settings_path is None:
|
|
||||||
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
|
|
||||||
|
|
||||||
settings = copy.deepcopy(DEFAULTS)
|
|
||||||
|
|
||||||
if os.path.exists(settings_path):
|
|
||||||
try:
|
|
||||||
with open(settings_path, "r") as f:
|
|
||||||
file_settings = yaml.safe_load(f) or {}
|
|
||||||
settings = deep_merge(settings, file_settings)
|
|
||||||
logger.info(f"Settings loaded from {settings_path}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to load settings from {settings_path}: {e}")
|
|
||||||
logger.warning("Using default settings")
|
|
||||||
else:
|
|
||||||
logger.warning(f"Settings file not found at {settings_path}, using defaults")
|
|
||||||
|
|
||||||
env_overrides = {}
|
|
||||||
|
|
||||||
if os.environ.get("DUNE_SERVER_HOST"):
|
|
||||||
env_overrides.setdefault("server", {})["host"] = os.environ["DUNE_SERVER_HOST"]
|
|
||||||
if os.environ.get("DUNE_SERVER_USER"):
|
|
||||||
env_overrides.setdefault("server", {})["user"] = os.environ["DUNE_SERVER_USER"]
|
|
||||||
if os.environ.get("DUNE_DB_PASSWORD"):
|
|
||||||
env_overrides.setdefault("database", {})["password"] = os.environ["DUNE_DB_PASSWORD"]
|
|
||||||
if os.environ.get("DUNE_K8S_NAMESPACE"):
|
|
||||||
env_overrides.setdefault("kubernetes", {})["namespace"] = os.environ["DUNE_K8S_NAMESPACE"]
|
|
||||||
if os.environ.get("DUNE_AUTH_PASSWORD"):
|
|
||||||
env_overrides.setdefault("auth", {})["password"] = os.environ["DUNE_AUTH_PASSWORD"]
|
|
||||||
if os.environ.get("DUNE_DASHBOARD_PORT"):
|
|
||||||
env_overrides.setdefault("dashboard", {})["port"] = int(os.environ["DUNE_DASHBOARD_PORT"])
|
|
||||||
if os.environ.get("DUNE_RMQ_PASSWORD"):
|
|
||||||
env_overrides.setdefault("rmq", {})["password"] = os.environ["DUNE_RMQ_PASSWORD"]
|
|
||||||
|
|
||||||
if env_overrides:
|
|
||||||
settings = deep_merge(settings, env_overrides)
|
|
||||||
logger.info("Environment variable overrides applied")
|
|
||||||
|
|
||||||
if not settings["dashboard"].get("secret_key"):
|
|
||||||
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
|
|
||||||
logger.info("Generated secure SECRET_KEY")
|
|
||||||
|
|
||||||
auth = settings.get("auth", {})
|
|
||||||
password_migrated = False
|
|
||||||
if auth.get("password") and not auth.get("password_hash"):
|
|
||||||
try:
|
|
||||||
from argon2 import PasswordHasher
|
|
||||||
ph = PasswordHasher(time_cost=3, memory_cost=65536)
|
|
||||||
settings["auth"]["password_hash"] = ph.hash(str(auth["password"]))
|
|
||||||
del settings["auth"]["password"]
|
|
||||||
password_migrated = True
|
|
||||||
logger.info("Migrated plaintext password to Argon2 hash")
|
|
||||||
except ImportError:
|
|
||||||
logger.error("argon2-cffi not installed. Password hashing unavailable.")
|
|
||||||
settings["auth"]["password_hash"] = None
|
|
||||||
|
|
||||||
if password_migrated:
|
|
||||||
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
|
|
||||||
logger.warning("Rotated secret_key to invalidate sessions after password migration")
|
|
||||||
|
|
||||||
settings = _validate_server_host(settings)
|
|
||||||
|
|
||||||
return settings
|
|
||||||
|
|
||||||
|
|
||||||
_settings_cache = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_settings():
|
|
||||||
"""Get current settings (cached for performance)."""
|
|
||||||
global _settings_cache
|
|
||||||
if _settings_cache is None:
|
|
||||||
_settings_cache = load_settings()
|
|
||||||
return _settings_cache
|
|
||||||
|
|
||||||
|
|
||||||
def save_settings(settings):
|
|
||||||
"""Save settings to YAML file."""
|
|
||||||
global _settings_cache
|
|
||||||
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
|
|
||||||
try:
|
|
||||||
with open(settings_path, "w") as f:
|
|
||||||
yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False)
|
|
||||||
_settings_cache = settings
|
|
||||||
logger.info(f"Settings saved to {settings_path}")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to save settings to {settings_path}: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def reload_settings():
|
|
||||||
"""Force reload settings from file."""
|
|
||||||
global _settings_cache
|
|
||||||
_settings_cache = load_settings()
|
|
||||||
return _settings_cache
|
|
||||||
@@ -1,328 +0,0 @@
|
|||||||
# Application factory — creates and configures the Flask app.
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import logging
|
|
||||||
import logging.handlers
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from flask import Flask, jsonify, request, g, send_from_directory
|
|
||||||
from flask_cors import CORS
|
|
||||||
from flask_login import current_user
|
|
||||||
from flask_socketio import SocketIO
|
|
||||||
from flask_limiter import Limiter
|
|
||||||
from flask_limiter.util import get_remote_address
|
|
||||||
|
|
||||||
from app.config import load_settings
|
|
||||||
from app.routes.auth import auth_bp, init_auth
|
|
||||||
from app.routes.health import health_bp
|
|
||||||
from app.routes.api import api_bp
|
|
||||||
from app.routes.director import director_bp
|
|
||||||
from app.routes.server import server_bp
|
|
||||||
from app.routes.files import files_bp
|
|
||||||
from app.routes.debug import debug_bp
|
|
||||||
from app.routes.chat import chat_bp
|
|
||||||
from app.websocket.shell import register_websocket_handlers
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService, DashboardDatabaseService
|
|
||||||
from app.services.ssh import SSHService
|
|
||||||
from app.services.k8s import K8sService
|
|
||||||
from app.services.bg_director import BgDirectorService
|
|
||||||
from app.services.rmq_admin import RmqAdminService
|
|
||||||
from app.services.rmq_game import RmqGameService
|
|
||||||
from app.services.realtime import RealtimeService
|
|
||||||
from app.services.player import PlayerService
|
|
||||||
from app.services.economy import EconomyService
|
|
||||||
from app.services.guild import GuildService
|
|
||||||
from app.services.world import WorldService
|
|
||||||
from app.services.progression import ProgressionService
|
|
||||||
from app.services.character import CharacterService
|
|
||||||
from app.services.audit import AuditService
|
|
||||||
from app.services.chat import ChatService
|
|
||||||
|
|
||||||
_services = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_services():
|
|
||||||
global _services
|
|
||||||
return _services
|
|
||||||
|
|
||||||
|
|
||||||
def create_app(settings_path=None):
|
|
||||||
global _services
|
|
||||||
|
|
||||||
settings = load_settings(settings_path)
|
|
||||||
base_dir = os.path.dirname(os.path.dirname(__file__))
|
|
||||||
|
|
||||||
app = Flask(
|
|
||||||
__name__,
|
|
||||||
template_folder=os.path.join(base_dir, "frontend", "dist"),
|
|
||||||
static_folder=os.path.join(base_dir, "frontend", "dist", "assets"),
|
|
||||||
static_url_path="/assets",
|
|
||||||
)
|
|
||||||
app.config["SECRET_KEY"] = settings["dashboard"]["secret_key"]
|
|
||||||
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
|
||||||
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
|
||||||
app.config["WTF_CSRF_ENABLED"] = True
|
|
||||||
app.config["WTF_CSRF_TIME_LIMIT"] = None
|
|
||||||
|
|
||||||
CORS(app, resources={r"/api/*": {"origins": "*"}})
|
|
||||||
|
|
||||||
ssl_enabled = bool(
|
|
||||||
settings["dashboard"].get("ssl_cert")
|
|
||||||
and settings["dashboard"].get("ssl_key")
|
|
||||||
and settings["dashboard"]["ssl_cert"] != "null"
|
|
||||||
and settings["dashboard"]["ssl_key"] != "null"
|
|
||||||
)
|
|
||||||
app.config["SESSION_COOKIE_SECURE"] = ssl_enabled
|
|
||||||
|
|
||||||
if not settings["dashboard"]["debug"]:
|
|
||||||
@app.after_request
|
|
||||||
def add_security_headers(response):
|
|
||||||
if ssl_enabled:
|
|
||||||
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
|
|
||||||
response.headers["X-Frame-Options"] = "SAMEORIGIN"
|
|
||||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
||||||
response.headers["X-XSS-Protection"] = "1; mode=block"
|
|
||||||
response.headers["Content-Security-Policy"] = (
|
|
||||||
"default-src 'self'; "
|
|
||||||
"script-src 'self' 'unsafe-inline'; "
|
|
||||||
"style-src 'self' 'unsafe-inline'; "
|
|
||||||
"img-src 'self' data:; "
|
|
||||||
"connect-src 'self' ws: wss:; "
|
|
||||||
"frame-ancestors 'self'; "
|
|
||||||
"base-uri 'self'; "
|
|
||||||
"form-action 'self'"
|
|
||||||
)
|
|
||||||
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
|
|
||||||
return response
|
|
||||||
|
|
||||||
# Error handlers
|
|
||||||
@app.errorhandler(Exception)
|
|
||||||
def handle_exception(e):
|
|
||||||
logging.exception("Unhandled exception: %s", e)
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
if settings["dashboard"].get("debug", False):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InternalError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InternalError", message="An internal error occurred"),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
@app.errorhandler(404)
|
|
||||||
def handle_not_found(e):
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Resource not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
|
|
||||||
@app.errorhandler(405)
|
|
||||||
def handle_method_not_allowed(e):
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="MethodNotAllowed", message="Method not allowed"),
|
|
||||||
).model_dump()), 405
|
|
||||||
|
|
||||||
# Request logging
|
|
||||||
@app.before_request
|
|
||||||
def before_request_logging():
|
|
||||||
import time as _time
|
|
||||||
g._request_start_time = _time.time()
|
|
||||||
|
|
||||||
@app.after_request
|
|
||||||
def after_request_logging(response):
|
|
||||||
import time as _time
|
|
||||||
duration = _time.time() - g.get("_request_start_time", _time.time())
|
|
||||||
user = current_user.id if current_user.is_authenticated else "anonymous"
|
|
||||||
if request.path.startswith("/api") or request.path.startswith("/server"):
|
|
||||||
logging.info("%s %s %d %.3fs user=%s", request.method, request.path, response.status_code, duration, user)
|
|
||||||
response.headers["X-Response-Time"] = f"{duration:.3f}s"
|
|
||||||
return response
|
|
||||||
|
|
||||||
_setup_logging(settings)
|
|
||||||
|
|
||||||
# ── Services ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
db_config = {
|
|
||||||
"host": settings["database"]["host"],
|
|
||||||
"port": settings["database"]["port"],
|
|
||||||
"user": settings["database"]["user"],
|
|
||||||
"password": settings["database"]["password"],
|
|
||||||
"database": settings["database"]["name"],
|
|
||||||
}
|
|
||||||
|
|
||||||
dash_db_config = {
|
|
||||||
"host": settings["database"]["host"],
|
|
||||||
"port": settings["database"]["port"],
|
|
||||||
"user": settings["database"]["user"],
|
|
||||||
"password": settings["database"]["password"],
|
|
||||||
"database": settings["database"].get("dashboard_database_name", "dashboard"),
|
|
||||||
}
|
|
||||||
|
|
||||||
db_service = DatabaseService(
|
|
||||||
db_config,
|
|
||||||
min_conn=settings["database"]["min_connections"],
|
|
||||||
max_conn=settings["database"]["max_connections"],
|
|
||||||
)
|
|
||||||
|
|
||||||
dash_db_service = DashboardDatabaseService(
|
|
||||||
dash_db_config,
|
|
||||||
min_conn=settings["database"]["min_connections"],
|
|
||||||
max_conn=settings["database"]["max_connections"],
|
|
||||||
owner=settings["database"].get("owner", "dune"),
|
|
||||||
)
|
|
||||||
dash_db_service.ensure_tables(game_db=db_service)
|
|
||||||
|
|
||||||
ssh_service = SSHService(
|
|
||||||
host=settings["server"]["host"],
|
|
||||||
user=settings["server"]["user"],
|
|
||||||
ssh_key=settings["server"].get("ssh_key"),
|
|
||||||
)
|
|
||||||
|
|
||||||
k8s_service = K8sService(
|
|
||||||
ssh_service=ssh_service,
|
|
||||||
namespace=settings["kubernetes"]["namespace"],
|
|
||||||
)
|
|
||||||
|
|
||||||
bg_director = BgDirectorService(
|
|
||||||
host=settings["director"].get("host", "127.0.0.1"),
|
|
||||||
node_port=settings["director"].get("port", 32479),
|
|
||||||
)
|
|
||||||
|
|
||||||
rmq_admin = RmqAdminService(
|
|
||||||
host=settings["rmq"]["admin_host"],
|
|
||||||
port=settings["rmq"]["admin_port"],
|
|
||||||
username=settings["rmq"]["username"],
|
|
||||||
password=settings["rmq"]["password"],
|
|
||||||
)
|
|
||||||
|
|
||||||
rmq_game = RmqGameService(
|
|
||||||
host=settings["rmq"]["game_host"],
|
|
||||||
port=settings["rmq"]["game_port"],
|
|
||||||
username=settings["rmq"]["username"],
|
|
||||||
password=settings["rmq"]["password"],
|
|
||||||
)
|
|
||||||
|
|
||||||
player_svc = PlayerService(db_service)
|
|
||||||
economy_svc = EconomyService(db_service)
|
|
||||||
guild_svc = GuildService(db_service)
|
|
||||||
world_svc = WorldService(db_service)
|
|
||||||
progression_svc = ProgressionService(db_service)
|
|
||||||
character_svc = CharacterService(db_service)
|
|
||||||
audit_svc = AuditService(dash_db_service)
|
|
||||||
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service)
|
|
||||||
|
|
||||||
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
|
|
||||||
realtime_svc.start()
|
|
||||||
|
|
||||||
_services = {
|
|
||||||
"db": db_service,
|
|
||||||
"dash_db": dash_db_service,
|
|
||||||
"ssh": ssh_service,
|
|
||||||
"k8s": k8s_service,
|
|
||||||
"bg_director": bg_director,
|
|
||||||
"rmq_admin": rmq_admin,
|
|
||||||
"rmq_game": rmq_game,
|
|
||||||
"realtime": realtime_svc,
|
|
||||||
"player": player_svc,
|
|
||||||
"economy": economy_svc,
|
|
||||||
"guild": guild_svc,
|
|
||||||
"world": world_svc,
|
|
||||||
"progression": progression_svc,
|
|
||||||
"character": character_svc,
|
|
||||||
"audit": audit_svc,
|
|
||||||
"chat": chat_svc,
|
|
||||||
}
|
|
||||||
|
|
||||||
app.dune_settings = settings
|
|
||||||
app.dune_services = _services
|
|
||||||
|
|
||||||
# ── Blueprints ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
init_auth(app, settings)
|
|
||||||
|
|
||||||
# Auto-login for development — bypasses authentication on all endpoints
|
|
||||||
from flask_login import login_user
|
|
||||||
from app.routes.auth import AdminUser
|
|
||||||
|
|
||||||
@app.before_request
|
|
||||||
def auto_login_dev():
|
|
||||||
if not current_user.is_authenticated:
|
|
||||||
cfg_user = str(settings.get("auth", {}).get("username", "admin"))
|
|
||||||
login_user(AdminUser(cfg_user))
|
|
||||||
|
|
||||||
app.register_blueprint(auth_bp, url_prefix="/api/auth")
|
|
||||||
app.register_blueprint(health_bp, url_prefix="/api")
|
|
||||||
app.register_blueprint(api_bp, url_prefix="/api")
|
|
||||||
app.register_blueprint(director_bp, url_prefix="/api/director")
|
|
||||||
app.register_blueprint(server_bp, url_prefix="/api/server")
|
|
||||||
app.register_blueprint(files_bp, url_prefix="/api/files")
|
|
||||||
app.register_blueprint(chat_bp, url_prefix="/api/chat")
|
|
||||||
app.register_blueprint(debug_bp, url_prefix="/api/debug")
|
|
||||||
|
|
||||||
# ── SocketIO ─────────────────────────────────────────────────
|
|
||||||
socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
|
|
||||||
register_websocket_handlers(socketio, settings)
|
|
||||||
app.socketio = socketio
|
|
||||||
|
|
||||||
# ── Rate Limiter ─────────────────────────────────────────────
|
|
||||||
limiter = Limiter(
|
|
||||||
app=app,
|
|
||||||
key_func=get_remote_address,
|
|
||||||
default_limits=[],
|
|
||||||
storage_uri="memory://",
|
|
||||||
)
|
|
||||||
app.limiter = limiter
|
|
||||||
|
|
||||||
# ── Catch-all for React SPA ─────────────────────────────────
|
|
||||||
@app.route("/", defaults={"path": ""})
|
|
||||||
@app.route("/<path:path>")
|
|
||||||
def serve_react(path):
|
|
||||||
if path.startswith("api/") or path.startswith("server/") or path.startswith("static/") or path.startswith("assets/"):
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Resource not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return send_from_directory(os.path.join(base_dir, "frontend", "dist"), "index.html")
|
|
||||||
|
|
||||||
# ── Auto-detect namespace if empty ───────────────────────────
|
|
||||||
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("Could not auto-detect K8s namespace: %s", e)
|
|
||||||
|
|
||||||
return app
|
|
||||||
|
|
||||||
|
|
||||||
def _setup_logging(settings):
|
|
||||||
log_level = getattr(logging, settings["logging"]["level"].upper(), logging.INFO)
|
|
||||||
log_file = settings["logging"]["file"]
|
|
||||||
os.makedirs(os.path.dirname(log_file), exist_ok=True)
|
|
||||||
|
|
||||||
handler = logging.handlers.RotatingFileHandler(
|
|
||||||
log_file,
|
|
||||||
maxBytes=settings["logging"]["max_bytes"],
|
|
||||||
backupCount=settings["logging"]["backup_count"],
|
|
||||||
)
|
|
||||||
handler.setFormatter(logging.Formatter(
|
|
||||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
||||||
))
|
|
||||||
handler.setLevel(log_level)
|
|
||||||
|
|
||||||
console = logging.StreamHandler(sys.stdout)
|
|
||||||
console.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
|
|
||||||
console.setLevel(log_level)
|
|
||||||
|
|
||||||
root = logging.getLogger()
|
|
||||||
root.setLevel(log_level)
|
|
||||||
root.addHandler(handler)
|
|
||||||
root.addHandler(console)
|
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
# Pydantic models for the Dune Admin Dashboard API.
|
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from typing import Any, List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ErrorDetail(BaseModel):
|
|
||||||
code: str
|
|
||||||
message: str
|
|
||||||
details: Optional[Any] = None
|
|
||||||
|
|
||||||
|
|
||||||
class ApiResponse(BaseModel):
|
|
||||||
success: bool
|
|
||||||
data: Optional[Any] = None
|
|
||||||
error: Optional[ErrorDetail] = None
|
|
||||||
|
|
||||||
|
|
||||||
# ── Player Models ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
class Vitals(BaseModel):
|
|
||||||
current_health: Optional[float] = None
|
|
||||||
max_health: Optional[float] = None
|
|
||||||
current_hydration: Optional[float] = None
|
|
||||||
dehydration_penalty: Optional[float] = None
|
|
||||||
current_spice: Optional[float] = None
|
|
||||||
spice_addiction_level: Optional[float] = None
|
|
||||||
spice_tolerance: Optional[float] = None
|
|
||||||
|
|
||||||
|
|
||||||
class CurrencyBalance(BaseModel):
|
|
||||||
currency_id: int
|
|
||||||
currency_label: str
|
|
||||||
balance: float = 0.0
|
|
||||||
|
|
||||||
|
|
||||||
class Item(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
template_id: str = ""
|
|
||||||
stack_size: int = 1
|
|
||||||
quality_level: int = 0
|
|
||||||
is_new: bool = False
|
|
||||||
position_index: int = 0
|
|
||||||
stats: Optional[Any] = None
|
|
||||||
durability: Optional[float] = None
|
|
||||||
max_durability: Optional[float] = None
|
|
||||||
ammo: Optional[int] = None
|
|
||||||
|
|
||||||
|
|
||||||
class Inventory(BaseModel):
|
|
||||||
inventory_id: int
|
|
||||||
actor_id: Optional[int] = None
|
|
||||||
inventory_type: int = 0
|
|
||||||
inventory_type_label: str = ""
|
|
||||||
max_item_count: Optional[int] = None
|
|
||||||
max_item_volume: Optional[float] = None
|
|
||||||
items: List[Item] = []
|
|
||||||
|
|
||||||
|
|
||||||
class VehicleSummary(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
class_name: str = ""
|
|
||||||
display_name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class BuildingSummary(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
class_name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
owner_name: str = ""
|
|
||||||
instance_count: int = 0
|
|
||||||
is_powered: bool = False
|
|
||||||
power_level: Optional[Any] = None
|
|
||||||
|
|
||||||
|
|
||||||
class Landclaim(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
class_name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class SpecializationTrack(BaseModel):
|
|
||||||
track_type: str = ""
|
|
||||||
xp_amount: int = 0
|
|
||||||
level: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class Keystone(BaseModel):
|
|
||||||
id: int
|
|
||||||
name: str = ""
|
|
||||||
|
|
||||||
|
|
||||||
class FactionReputation(BaseModel):
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
faction_name: str = ""
|
|
||||||
reputation_amount: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class LandsraadInfo(BaseModel):
|
|
||||||
daily_reward_charges: Optional[int] = None
|
|
||||||
last_viewed_term_id: Optional[int] = None
|
|
||||||
daily_reward_last_processed: Optional[Any] = None
|
|
||||||
|
|
||||||
|
|
||||||
class PlayerSummary(BaseModel):
|
|
||||||
player_controller_id: Optional[int] = None
|
|
||||||
character_name: str = "Unknown"
|
|
||||||
account_email: Optional[str] = None
|
|
||||||
funcom_id: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
map: Optional[str] = None
|
|
||||||
online_status: str = "Unknown"
|
|
||||||
life_state: Optional[str] = None
|
|
||||||
last_login_time: Optional[str] = None
|
|
||||||
last_avatar_activity: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class PlayerDetail(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
account_id: int
|
|
||||||
player_controller_id: Optional[int] = None
|
|
||||||
player_pawn_id: Optional[int] = None
|
|
||||||
character_name: str = "Unknown"
|
|
||||||
account_email: Optional[str] = None
|
|
||||||
funcom_id: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
map: Optional[str] = None
|
|
||||||
online_status: str = "Unknown"
|
|
||||||
life_state: Optional[str] = None
|
|
||||||
last_login_time: Optional[str] = None
|
|
||||||
last_avatar_activity: Optional[str] = None
|
|
||||||
vitals: Optional[Vitals] = None
|
|
||||||
currency: List[CurrencyBalance] = []
|
|
||||||
inventories: List[Inventory] = []
|
|
||||||
vehicles: List[VehicleSummary] = []
|
|
||||||
buildings: List[BuildingSummary] = []
|
|
||||||
landclaims: List[Landclaim] = []
|
|
||||||
specialization: List[SpecializationTrack] = []
|
|
||||||
keystones: List[Keystone] = []
|
|
||||||
faction_reputation: List[FactionReputation] = []
|
|
||||||
landsraad: Optional[LandsraadInfo] = None
|
|
||||||
tags: List[str] = []
|
|
||||||
is_online: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
# ── Guild Models ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class GuildMember(BaseModel):
|
|
||||||
player_id: int
|
|
||||||
role_id: int = 50
|
|
||||||
role_name: str = "Member"
|
|
||||||
player_name: str = "Unknown"
|
|
||||||
online_status: str = "Unknown"
|
|
||||||
|
|
||||||
|
|
||||||
class GuildSummary(BaseModel):
|
|
||||||
guild_id: int
|
|
||||||
guild_name: str = ""
|
|
||||||
guild_description: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
member_count: int = 0
|
|
||||||
online_count: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class GuildDetail(BaseModel):
|
|
||||||
guild_id: int
|
|
||||||
guild_name: str = ""
|
|
||||||
guild_description: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
members: List[GuildMember] = []
|
|
||||||
|
|
||||||
|
|
||||||
# ── World Models ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
class PartitionInfo(BaseModel):
|
|
||||||
partition_id: int
|
|
||||||
name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
player_count: int = 0
|
|
||||||
status: str = "unknown"
|
|
||||||
|
|
||||||
|
|
||||||
# ── RMQ Models ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class RmqQueueInfo(BaseModel):
|
|
||||||
name: str
|
|
||||||
messages: int = 0
|
|
||||||
consumers: int = 0
|
|
||||||
state: str = ""
|
|
||||||
|
|
||||||
|
|
||||||
class RmqOverview(BaseModel):
|
|
||||||
queues: List[RmqQueueInfo] = []
|
|
||||||
total_messages: int = 0
|
|
||||||
total_consumers: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
# ── BGD Models ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class BattlegroupState(BaseModel):
|
|
||||||
battlegroup_id: Optional[int] = None
|
|
||||||
name: Optional[str] = None
|
|
||||||
status: Optional[str] = None
|
|
||||||
player_count: Optional[int] = None
|
|
||||||
servers: Optional[List[Any]] = None
|
|
||||||
|
|
||||||
|
|
||||||
# ── Request Models ─────────────────────────────────────────────
|
|
||||||
|
|
||||||
class BroadcastRequest(BaseModel):
|
|
||||||
message: str = Field(..., min_length=1, max_length=500)
|
|
||||||
server: Optional[str] = None
|
|
||||||
partition: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class TeleportRequest(BaseModel):
|
|
||||||
player_id: int
|
|
||||||
destination: str = Field(..., min_length=1)
|
|
||||||
|
|
||||||
|
|
||||||
class FunctionExecuteRequest(BaseModel):
|
|
||||||
schema_name: Optional[str] = Field(default=None, alias="schema")
|
|
||||||
function: str = Field(..., min_length=1)
|
|
||||||
args: dict = {}
|
|
||||||
|
|
||||||
|
|
||||||
class RawQueryRequest(BaseModel):
|
|
||||||
query: str = Field(..., min_length=1)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Routes package init.
|
|
||||||
@@ -1,972 +0,0 @@
|
|||||||
# Main API routes — players, guilds, economy, world, progression, character, admin.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, request, jsonify
|
|
||||||
from flask_login import login_required, current_user
|
|
||||||
from pydantic import ValidationError
|
|
||||||
|
|
||||||
from app.models import (
|
|
||||||
ApiResponse, ErrorDetail, PlayerDetail, BroadcastRequest,
|
|
||||||
TeleportRequest, FunctionExecuteRequest, RawQueryRequest,
|
|
||||||
)
|
|
||||||
|
|
||||||
api_bp = Blueprint("api", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _audit(action: str, details: dict | None = None, target_player_id: int | None = None, severity: str = "info"):
|
|
||||||
from app.factory import get_services
|
|
||||||
services = get_services()
|
|
||||||
audit = services.get("audit")
|
|
||||||
if audit:
|
|
||||||
audit.log(
|
|
||||||
action=action,
|
|
||||||
user=current_user.id if current_user.is_authenticated else "anonymous",
|
|
||||||
details=details,
|
|
||||||
target_player_id=target_player_id,
|
|
||||||
severity=severity,
|
|
||||||
source_ip=request.remote_addr,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.errorhandler(ValidationError)
|
|
||||||
def handle_validation_error(e):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=str(e)),
|
|
||||||
).model_dump()), 400
|
|
||||||
|
|
||||||
|
|
||||||
# ── Player Endpoints ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/players", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_players():
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 50))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["player"]
|
|
||||||
results = svc.search(term, limit=limit)
|
|
||||||
return jsonify(ApiResponse(success=True, data=results).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/search", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def search_players():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
term = data.get("term", "")
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["player"]
|
|
||||||
results = svc.search(term)
|
|
||||||
return jsonify(ApiResponse(success=True, data=results).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["player"]
|
|
||||||
detail = svc.get_detail(account_id)
|
|
||||||
if not detail:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Player not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=detail).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/inventory", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_inventory(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
inventories = svc.get_inventory(account_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data=inventories).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/currency", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_currency(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
player_svc = get_services()["player"]
|
|
||||||
detail = player_svc.get_detail(account_id)
|
|
||||||
pid = detail.get("player_controller_id") if detail else None
|
|
||||||
if not pid:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Player controller not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
econ = get_services()["economy"]
|
|
||||||
currency = econ.get_currency(pid)
|
|
||||||
return jsonify(ApiResponse(success=True, data=currency).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/vitals", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_vitals(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
player_svc = get_services()["player"]
|
|
||||||
detail = player_svc.get_detail(account_id)
|
|
||||||
pawn_id = detail.get("player_pawn_id") if detail else None
|
|
||||||
if not pawn_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Player pawn not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
econ = get_services()["economy"]
|
|
||||||
vitals = econ.get_vitals(pawn_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data=vitals).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Economy Mutations ────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/items/add", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def add_item():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
inventory_id = data.get("inventory_id")
|
|
||||||
template_id = data.get("template_id")
|
|
||||||
stack_size = data.get("stack_size", 1)
|
|
||||||
quality_level = data.get("quality_level", 0)
|
|
||||||
if not inventory_id or not template_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing inventory_id or template_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
item_id = svc.add_item(inventory_id, template_id, stack_size, quality_level)
|
|
||||||
_audit("item_add", {"inventory_id": inventory_id, "template_id": template_id, "item_id": item_id})
|
|
||||||
return jsonify(ApiResponse(success=True, data={"item_id": item_id}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/items/<int:item_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def delete_item(item_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.delete_item(item_id)
|
|
||||||
_audit("item_delete", {"item_id": item_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/items/<int:item_id>", methods=["PATCH"])
|
|
||||||
@login_required
|
|
||||||
def edit_item(item_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
field = data.get("field")
|
|
||||||
value = data.get("value")
|
|
||||||
if not field or value is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing field or value"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.edit_item_field(item_id, field, value)
|
|
||||||
_audit("item_edit", {"item_id": item_id, "field": field, "value": value})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/currency/adjust", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def adjust_currency():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
controller_id = data.get("controller_id")
|
|
||||||
currency_id = data.get("currency_id")
|
|
||||||
delta = data.get("delta")
|
|
||||||
if controller_id is None or currency_id is None or delta is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
new_balance = svc.adjust_currency(controller_id, currency_id, delta)
|
|
||||||
_audit("currency_adjust", {"controller_id": controller_id, "currency_id": currency_id, "delta": delta, "new_balance": new_balance}, target_player_id=controller_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"new_balance": new_balance}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/currency/set", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def set_currency():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
controller_id = data.get("controller_id")
|
|
||||||
currency_id = data.get("currency_id")
|
|
||||||
balance = data.get("balance")
|
|
||||||
if controller_id is None or currency_id is None or balance is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.set_currency(controller_id, currency_id, balance)
|
|
||||||
_audit("currency_set", {"controller_id": controller_id, "currency_id": currency_id, "balance": balance}, target_player_id=controller_id)
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/vitals/set", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def set_vitals():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
pawn_id = data.get("pawn_id")
|
|
||||||
health = data.get("health")
|
|
||||||
max_health = data.get("max_health")
|
|
||||||
hydration = data.get("hydration")
|
|
||||||
spice = data.get("spice")
|
|
||||||
if pawn_id is None or hydration is None or spice is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.set_vitals(pawn_id, health, max_health, hydration, spice)
|
|
||||||
_audit("vitals_edit", {"pawn_id": pawn_id, "health": health, "max_health": max_health, "hydration": hydration, "spice": spice})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Guild Endpoints ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/guilds", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_guilds():
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 50))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
guilds = svc.list_all()
|
|
||||||
if term:
|
|
||||||
guilds = [g for g in guilds if term.lower() in g.guild_name.lower()]
|
|
||||||
return jsonify(ApiResponse(success=True, data=guilds[:limit]).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_guild(guild_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
guild = svc.get_detail(guild_id)
|
|
||||||
if not guild:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Guild not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=guild).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def disband_guild(guild_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
svc.disband(guild_id)
|
|
||||||
_audit("guild_disband", {"guild_id": guild_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def remove_guild_member(guild_id, player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
svc.remove_member(guild_id, player_id)
|
|
||||||
_audit("guild_kick", {"guild_id": guild_id, "player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>/role", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def set_guild_role(guild_id, player_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
role_id = data.get("role_id")
|
|
||||||
action = data.get("action", "promote")
|
|
||||||
if role_id is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing role_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
if action == "promote":
|
|
||||||
svc.promote(guild_id, player_id, role_id)
|
|
||||||
else:
|
|
||||||
svc.demote(guild_id, player_id, role_id)
|
|
||||||
_audit(f"guild_{action}", {"guild_id": guild_id, "player_id": player_id, "role_id": role_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── World Endpoints ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/partitions", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_partitions():
|
|
||||||
map_name = request.args.get("map", "")
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
partitions = svc.get_partitions(map_name)
|
|
||||||
return jsonify(ApiResponse(success=True, data=partitions).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/teleport", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def teleport():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
req = TeleportRequest(**data)
|
|
||||||
except ValidationError as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=str(e)),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
svc.teleport(req.fls_id, req.partition_id, req.x, req.y, req.z)
|
|
||||||
_audit("player_teleport", {"fls_id": req.fls_id, "partition_id": req.partition_id, "coords": [req.x, req.y, req.z]})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/spice/reset", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def reset_spice():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
map_name = data.get("map_name")
|
|
||||||
dimension_index = data.get("dimension_index", 0)
|
|
||||||
if not map_name:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing map_name"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
svc.reset_spice(map_name, dimension_index)
|
|
||||||
_audit("spice_reset", {"map": map_name, "dimension": dimension_index})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/spice/spawn", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def force_spice_spawn():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
server_id = data.get("server_id")
|
|
||||||
spicefield_type_id = data.get("spicefield_type_id")
|
|
||||||
if not server_id or spicefield_type_id is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
svc.force_spice_spawn(server_id, spicefield_type_id)
|
|
||||||
_audit("spice_spawn", {"server_id": server_id, "spicefield_type_id": spicefield_type_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Progression Endpoints ────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/progression/journey", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def journey_action():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
node_ids = data.get("node_ids", [])
|
|
||||||
action = data.get("action", "complete")
|
|
||||||
if not player_id or not node_ids:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id or node_ids"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["progression"]
|
|
||||||
if action == "complete":
|
|
||||||
svc.complete_nodes(player_id, node_ids)
|
|
||||||
elif action == "reveal":
|
|
||||||
svc.reveal_nodes(player_id, node_ids)
|
|
||||||
elif action == "reset":
|
|
||||||
svc.reset_nodes(player_id, node_ids)
|
|
||||||
else:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Invalid action"),
|
|
||||||
).model_dump()), 400
|
|
||||||
_audit(f"journey_{action}", {"player_id": player_id, "node_ids": node_ids})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/progression/specialization", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def set_specialization():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
track_type = data.get("track_type")
|
|
||||||
xp = data.get("xp")
|
|
||||||
level = data.get("level")
|
|
||||||
if player_id is None or not track_type or xp is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["progression"]
|
|
||||||
svc.set_specialization(player_id, track_type, xp, level or 0)
|
|
||||||
_audit("specialization_set", {"player_id": player_id, "track": track_type, "xp": xp, "level": level})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/progression/specialization/reset", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def reset_specializations():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
if player_id is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["progression"]
|
|
||||||
svc.reset_specializations(player_id)
|
|
||||||
_audit("specialization_reset", {"player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Character Management Endpoints ──────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/characters/<int:account_id>/name", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def rename_character(account_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
name = data.get("name", "").strip()
|
|
||||||
if not name:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing name"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.rename(account_id, name)
|
|
||||||
_audit("character_rename", {"account_id": account_id, "new_name": name})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/characters/<int:actor_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def delete_character(actor_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.delete_character(actor_id)
|
|
||||||
_audit("character_delete", {"actor_id": actor_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/accounts/<user_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def delete_account(user_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
reason = data.get("reason", "admin")
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.delete_account(user_id, reason)
|
|
||||||
_audit("account_delete", {"user_id": user_id, "reason": reason})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/accounts/<user_id>/demo", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def set_demo_state(user_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
state = data.get("demo")
|
|
||||||
if state is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing demo"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.set_demo(user_id, state)
|
|
||||||
_audit("demo_set", {"user_id": user_id, "state": state})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Vehicles ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/vehicles", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_vehicles():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT a.id, a.class, a.map
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
|
|
||||||
WHERE a.class ILIKE %s
|
|
||||||
ORDER BY a.id DESC LIMIT %s""",
|
|
||||||
[f"%{term}%", limit],
|
|
||||||
)
|
|
||||||
vehicles = [{
|
|
||||||
"id": r["id"],
|
|
||||||
"class_name": r["class"],
|
|
||||||
"display_name": (r["class"] or "").split("/")[-1].replace("_C", "").replace("BP_", "").replace("_", " "),
|
|
||||||
"map": r["map"],
|
|
||||||
"owner_name": "Unknown",
|
|
||||||
} for r in rows]
|
|
||||||
return jsonify(ApiResponse(success=True, data=vehicles).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/vehicles/<int:vehicle_id>/<action>", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def vehicle_action(vehicle_id, action):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
if action == "repair":
|
|
||||||
db.call_procedure("repair_vehicle", [vehicle_id])
|
|
||||||
_audit("vehicle_repair", {"vehicle_id": vehicle_id})
|
|
||||||
elif action == "destroy":
|
|
||||||
db.call_procedure("destroy_vehicle", [vehicle_id])
|
|
||||||
_audit("vehicle_destroy", {"vehicle_id": vehicle_id})
|
|
||||||
else:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
|
|
||||||
).model_dump()), 400
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Buildings ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/buildings", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_buildings():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
|
|
||||||
a.properties->>'m_PowerLevel' as power_level
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.buildings b ON a.id = b.id
|
|
||||||
WHERE a.class ILIKE %s
|
|
||||||
ORDER BY a.id DESC LIMIT %s""",
|
|
||||||
[f"%{term}%", limit],
|
|
||||||
)
|
|
||||||
buildings = [{
|
|
||||||
"id": r["id"],
|
|
||||||
"class_name": r["class"],
|
|
||||||
"map": r["map"],
|
|
||||||
"owner_name": "Unknown",
|
|
||||||
"is_powered": r.get("is_powered") == "True",
|
|
||||||
"power_level": r.get("power_level"),
|
|
||||||
"instance_count": 1,
|
|
||||||
} for r in rows]
|
|
||||||
return jsonify(ApiResponse(success=True, data=buildings).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Accounts ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/accounts", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_accounts():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT a.id, COALESCE(a.email, '') as email, a.funcom_id,
|
|
||||||
(SELECT COUNT(*) FROM dune.player_state ps WHERE ps.account_id = a.id) as character_count,
|
|
||||||
COALESCE(a.is_demo, false) as is_demo, COALESCE(a.is_cheater, false) as is_cheater,
|
|
||||||
NULL as last_login
|
|
||||||
FROM dune.accounts a
|
|
||||||
WHERE a.email ILIKE %s OR a.funcom_id ILIKE %s
|
|
||||||
LIMIT %s""",
|
|
||||||
[f"%{term}%", f"%{term}%", limit],
|
|
||||||
)
|
|
||||||
accounts = [{
|
|
||||||
"id": r["id"],
|
|
||||||
"email": r.get("email") or "",
|
|
||||||
"funcom_id": r["funcom_id"],
|
|
||||||
"character_count": r["character_count"],
|
|
||||||
"is_demo": r["is_demo"],
|
|
||||||
"is_cheater": r["is_cheater"],
|
|
||||||
"last_login": r["last_login"].isoformat() if r["last_login"] else None,
|
|
||||||
} for r in rows]
|
|
||||||
return jsonify(ApiResponse(success=True, data=accounts).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/cheater", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def flag_cheater(account_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
cheat_type = data.get("cheat_type")
|
|
||||||
if not cheat_type:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing cheat_type"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.flag_cheater(account_id, cheat_type)
|
|
||||||
_audit("cheater_flag", {"account_id": account_id, "cheat_type": cheat_type})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/tags", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_tags(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
tags = svc.get_tags(account_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"tags": tags}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/tags", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def update_player_tags(account_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
add = data.get("add", [])
|
|
||||||
remove = data.get("remove", [])
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.update_tags(account_id, add, remove)
|
|
||||||
_audit("tags_update", {"account_id": account_id, "add": add, "remove": remove})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Broadcast ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/broadcast", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def send_broadcast():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
req = BroadcastRequest(**data)
|
|
||||||
except ValidationError as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=str(e)),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["rmq_game"]
|
|
||||||
success = svc.send_broadcast(req.message, server=req.server, partition=req.partition)
|
|
||||||
if success:
|
|
||||||
_audit("broadcast_sent", {"message": req.message, "server": req.server, "partition": req.partition})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="BroadcastFailed", message="Failed to send broadcast via RMQ"),
|
|
||||||
).model_dump()), 502
|
|
||||||
|
|
||||||
|
|
||||||
# ── Vendor / Economy ────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/vendors/clean", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def clean_vendor_stock():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
if not player_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.clean_vendor_stock(player_id)
|
|
||||||
_audit("vendor_clean", {"player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/tax/invoices", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def get_tax_invoices():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
if not player_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
invoices = svc.get_tax_invoices(player_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data=invoices).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Function Explorer ────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/functions", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_functions():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT p.proname as name,
|
|
||||||
pg_get_function_identity_arguments(p.oid) as args,
|
|
||||||
l.lanname as language,
|
|
||||||
p.prokind as kind
|
|
||||||
FROM pg_proc p
|
|
||||||
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
||||||
JOIN pg_language l ON l.oid = p.prolang
|
|
||||||
WHERE n.nspname = 'dune' AND p.prokind = 'f'
|
|
||||||
ORDER BY p.proname"""
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/functions/<name>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_function_detail(name):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT pg_get_functiondef(p.oid) as definition,
|
|
||||||
p.proname as name,
|
|
||||||
pg_get_function_identity_arguments(p.oid) as args
|
|
||||||
FROM pg_proc p
|
|
||||||
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
||||||
WHERE n.nspname = 'dune' AND p.proname = %s AND p.prokind = 'f'""",
|
|
||||||
[name],
|
|
||||||
)
|
|
||||||
if not rows:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Function not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows[0]).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/functions/execute", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def execute_function_v2():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
schema = data.get("schema")
|
|
||||||
func_name = data.get("function", "")
|
|
||||||
args = data.get("args", {})
|
|
||||||
if not func_name:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing function name"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
full_name = f"{schema}.{func_name}" if schema else func_name
|
|
||||||
if isinstance(args, dict):
|
|
||||||
params = list(args.values())
|
|
||||||
elif isinstance(args, list):
|
|
||||||
params = args
|
|
||||||
else:
|
|
||||||
params = [args]
|
|
||||||
result = db.call_function(full_name, params)
|
|
||||||
_audit("function_execute", {"function": full_name, "params": params})
|
|
||||||
return jsonify(ApiResponse(success=True, data=result).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Function execution failed")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ExecutionError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/functions/<name>/execute", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def execute_function(name):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
params = data.get("params", [])
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
result = db.call_function(name, params)
|
|
||||||
_audit("function_execute", {"function": name, "params": params})
|
|
||||||
return jsonify(ApiResponse(success=True, data=result).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Function execution failed")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ExecutionError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
# ── Raw Query (SELECT only) ──────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/query", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def raw_query():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
sql = (data.get("query") or data.get("sql", "")).strip()
|
|
||||||
if not sql:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing SQL"),
|
|
||||||
).model_dump()), 400
|
|
||||||
upper = sql.upper()
|
|
||||||
if any(kw in upper for kw in ("INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "GRANT", "TRUNCATE")):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="Forbidden", message="Only SELECT queries are allowed"),
|
|
||||||
).model_dump()), 403
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
result = db.execute_readonly(sql)
|
|
||||||
_audit("raw_query", {"sql": sql[:200]})
|
|
||||||
return jsonify(ApiResponse(success=True, data=result).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="QueryError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
# ── Audit Logs ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/audit/logs", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_audit_logs():
|
|
||||||
action = request.args.get("action")
|
|
||||||
user = request.args.get("user")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
offset = int(request.args.get("offset", 0))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["audit"]
|
|
||||||
logs = svc.get_logs(action=action, user=user, limit=limit, offset=offset)
|
|
||||||
return jsonify(ApiResponse(success=True, data=logs).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/stats", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_stats():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
stats = db.execute_readonly("""
|
|
||||||
SELECT
|
|
||||||
(SELECT COUNT(*) FROM dune.player_state) AS total_players,
|
|
||||||
(SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') AS online_players,
|
|
||||||
(SELECT COUNT(*) FROM dune.guilds) AS guild_count,
|
|
||||||
(SELECT 0) AS active_guilds,
|
|
||||||
(SELECT COUNT(*) FROM dune.accounts) AS server_count,
|
|
||||||
(SELECT 0) AS partition_count,
|
|
||||||
(SELECT 0) AS total_worth,
|
|
||||||
(SELECT 0) AS total_flavor_text
|
|
||||||
""")
|
|
||||||
return jsonify(ApiResponse(success=True, data=stats[0] if stats else {}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Failed to get stats")
|
|
||||||
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="StatsError", message=str(e))).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/audit/stats", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_audit_stats():
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["audit"]
|
|
||||||
stats = svc.get_stats()
|
|
||||||
return jsonify(ApiResponse(success=True, data=stats).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Settings ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/settings", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_settings():
|
|
||||||
from app.factory import get_services
|
|
||||||
dash_db = get_services()["dash_db"]
|
|
||||||
settings = dash_db.execute_readonly(
|
|
||||||
"SELECT key, value, updated_at FROM settings ORDER BY key"
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/settings", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def update_settings():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
dash_db = get_services()["dash_db"]
|
|
||||||
for key, value in data.items():
|
|
||||||
dash_db.execute_mutation(
|
|
||||||
"""INSERT INTO settings (key, value, updated_at)
|
|
||||||
VALUES (%s, %s, NOW())
|
|
||||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
|
|
||||||
[key, str(value)],
|
|
||||||
)
|
|
||||||
_audit("settings_update", {"keys": list(data.keys())})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Moderation (Ban / Kick) ────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/ban", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def ban_player(player_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
reason = data.get("reason", "admin")
|
|
||||||
duration = data.get("duration_hours", 0)
|
|
||||||
from app.factory import get_services
|
|
||||||
dash_db = get_services()["dash_db"]
|
|
||||||
dash_db.execute_mutation(
|
|
||||||
"""INSERT INTO bans (player_id, reason, duration, banned_at, expires_at, active)
|
|
||||||
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
|
|
||||||
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
|
|
||||||
[player_id, reason, duration, duration, duration],
|
|
||||||
)
|
|
||||||
_audit("player_ban", {"player_id": player_id, "reason": reason, "duration": duration})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/unban", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def unban_player(player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
dash_db = get_services()["dash_db"]
|
|
||||||
dash_db.execute_mutation(
|
|
||||||
"UPDATE bans SET active = FALSE WHERE player_id = %s",
|
|
||||||
[player_id],
|
|
||||||
)
|
|
||||||
_audit("player_unban", {"player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/ban", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_ban(player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
dash_db = get_services()["dash_db"]
|
|
||||||
rows = dash_db.execute_readonly(
|
|
||||||
"SELECT * FROM bans WHERE player_id = %s AND active = TRUE",
|
|
||||||
[player_id],
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/kick", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def kick_player(player_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
reason = data.get("reason", "admin")
|
|
||||||
_audit("player_kick", {"player_id": player_id, "reason": reason})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/history", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_history(player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
dash_db = get_services()["dash_db"]
|
|
||||||
logs = dash_db.execute_readonly(
|
|
||||||
"""SELECT * FROM audit_log
|
|
||||||
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
|
|
||||||
ORDER BY created_at DESC LIMIT 100""",
|
|
||||||
[player_id, player_id],
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data=logs).model_dump())
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
# Authentication routes — login, logout.
|
|
||||||
|
|
||||||
import time
|
|
||||||
import threading
|
|
||||||
from functools import wraps
|
|
||||||
|
|
||||||
from flask import Blueprint, request, jsonify, session
|
|
||||||
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
auth_bp = Blueprint("auth", __name__)
|
|
||||||
login_manager = LoginManager()
|
|
||||||
|
|
||||||
_failed_attempts = {}
|
|
||||||
_failed_lock = threading.Lock()
|
|
||||||
_MAX_FAILED_ATTEMPTS = 5
|
|
||||||
_BLOCK_DURATION = 900
|
|
||||||
|
|
||||||
|
|
||||||
class AdminUser(UserMixin):
|
|
||||||
def __init__(self, username):
|
|
||||||
self.id = username
|
|
||||||
|
|
||||||
|
|
||||||
def _is_ip_blocked(ip):
|
|
||||||
with _failed_lock:
|
|
||||||
record = _failed_attempts.get(ip)
|
|
||||||
if record and record["count"] >= _MAX_FAILED_ATTEMPTS:
|
|
||||||
elapsed = time.time() - record["first_attempt"]
|
|
||||||
if elapsed < _BLOCK_DURATION:
|
|
||||||
return True
|
|
||||||
del _failed_attempts[ip]
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _record_failed_attempt(ip):
|
|
||||||
with _failed_lock:
|
|
||||||
now = time.time()
|
|
||||||
record = _failed_attempts.get(ip)
|
|
||||||
if record:
|
|
||||||
record["count"] += 1
|
|
||||||
else:
|
|
||||||
_failed_attempts[ip] = {"count": 1, "first_attempt": now}
|
|
||||||
return _failed_attempts[ip]["count"] >= _MAX_FAILED_ATTEMPTS
|
|
||||||
|
|
||||||
|
|
||||||
def _clear_failed_attempts(ip):
|
|
||||||
with _failed_lock:
|
|
||||||
_failed_attempts.pop(ip, None)
|
|
||||||
|
|
||||||
|
|
||||||
def init_auth(app, settings):
|
|
||||||
login_manager.init_app(app)
|
|
||||||
login_manager.login_view = "auth.login"
|
|
||||||
login_manager.login_message = "Please log in."
|
|
||||||
|
|
||||||
@login_manager.user_loader
|
|
||||||
def load_user(user_id):
|
|
||||||
auth = settings.get("auth", {})
|
|
||||||
if str(auth.get("username")) == str(user_id):
|
|
||||||
return AdminUser(user_id)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def get_audit_user():
|
|
||||||
return current_user.id if current_user.is_authenticated else "anonymous"
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/login", methods=["POST"])
|
|
||||||
def login():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
username = data.get("username", "").strip()
|
|
||||||
password = data.get("password", "")
|
|
||||||
client_ip = request.remote_addr or "unknown"
|
|
||||||
|
|
||||||
if _is_ip_blocked(client_ip):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="IpBlocked", message="Too many failed attempts. Try again later."),
|
|
||||||
).model_dump()), 429
|
|
||||||
|
|
||||||
auth = request.app.dune_settings.get("auth", {})
|
|
||||||
cfg_u = str(auth.get("username", ""))
|
|
||||||
password_hash = auth.get("password_hash")
|
|
||||||
|
|
||||||
if username != cfg_u:
|
|
||||||
_record_failed_attempt(client_ip)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
|
|
||||||
).model_dump()), 401
|
|
||||||
|
|
||||||
if password_hash:
|
|
||||||
try:
|
|
||||||
from argon2 import PasswordHasher, exceptions
|
|
||||||
ph = PasswordHasher(time_cost=3, memory_cost=65536)
|
|
||||||
ph.verify(password_hash, password)
|
|
||||||
_clear_failed_attempts(client_ip)
|
|
||||||
login_user(AdminUser(username))
|
|
||||||
return jsonify(ApiResponse(success=True, data={"user": username}).model_dump())
|
|
||||||
except exceptions.VerifyMismatchError:
|
|
||||||
_record_failed_attempt(client_ip)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
|
|
||||||
).model_dump()), 401
|
|
||||||
except Exception:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AuthError", message="Authentication error"),
|
|
||||||
).model_dump()), 500
|
|
||||||
else:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotConfigured", message="Authentication not configured"),
|
|
||||||
).model_dump()), 403
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/logout", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def logout():
|
|
||||||
logout_user()
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/me", methods=["GET"])
|
|
||||||
def me():
|
|
||||||
if current_user.is_authenticated:
|
|
||||||
return jsonify(ApiResponse(success=True, data={"user": current_user.id}).model_dump())
|
|
||||||
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="Unauthorized", message="Not authenticated")).model_dump()), 401
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
# Chat routes.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
chat_bp = Blueprint("chat", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@chat_bp.route("/history", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def chat_history():
|
|
||||||
channel = request.args.get("channel", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["chat"]
|
|
||||||
rows = svc.get_history(limit=limit)
|
|
||||||
if channel:
|
|
||||||
rows = [r for r in rows if r.get("channel", "").lower() == channel.lower()]
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows).model_dump())
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
# Debug routes — restricted to admin.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
debug_bp = Blueprint("debug", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_services():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()
|
|
||||||
|
|
||||||
|
|
||||||
@debug_bp.route("/tables", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_tables():
|
|
||||||
db = _get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'dune' ORDER BY table_name"
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"tables": [r["table_name"] for r in rows]}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@debug_bp.route("/vehicle/<int:vehicle_id>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def debug_vehicle(vehicle_id):
|
|
||||||
db = _get_services()["db"]
|
|
||||||
vehicle = db.execute_readonly(
|
|
||||||
"""SELECT a.id, a.class, a.properties
|
|
||||||
FROM dune.actors a JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s""",
|
|
||||||
[vehicle_id],
|
|
||||||
)
|
|
||||||
if not vehicle:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Vehicle not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=vehicle[0]).model_dump())
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
# BGD Director proxy routes.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
director_bp = Blueprint("director", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_service():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()["bg_director"]
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/battlegroup", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def director_battlegroup():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
data = svc.get_battlegroup()
|
|
||||||
return jsonify(ApiResponse(success=True, data=data.model_dump()).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Director battlegroup error: %s", e)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e), hint="Check BGD pod logs"),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/config", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_update_config():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.update_server_config(data)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/config/clear", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_clear_config():
|
|
||||||
map_name = request.get_data(as_text=True).strip()
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.clear_map_config(map_name)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/transfer", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def director_transfer_get():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
data = svc.get_transfer_rules()
|
|
||||||
return jsonify(ApiResponse(success=True, data=data).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/transfer", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_transfer_update():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.update_transfer_settings(data)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/transfer/clear", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_transfer_clear():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.clear_transfer_overrides()
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/fls", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def director_fls_get():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
data = svc.get_fls_settings()
|
|
||||||
return jsonify(ApiResponse(success=True, data=data).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/fls", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_fls_update():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.update_fls_settings(data)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/fls/clear", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_fls_clear():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.clear_fls_overrides()
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
# File browser routes.
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import logging
|
|
||||||
import posixpath
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
files_bp = Blueprint("files", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
FILEBROWSER_BASE_PATH = "/srv"
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_fb_path(path: str) -> bool:
|
|
||||||
path_str = str(path or "").lstrip("/")
|
|
||||||
if ".." in path_str or "\x00" in path_str:
|
|
||||||
return False
|
|
||||||
normalized = posixpath.normpath("/" + path_str)
|
|
||||||
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
|
|
||||||
|
|
||||||
|
|
||||||
def _get_services():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()
|
|
||||||
|
|
||||||
|
|
||||||
def _fb_exec(command: str, timeout: int = 10):
|
|
||||||
services = _get_services()
|
|
||||||
k8s = services["k8s"]
|
|
||||||
pod = k8s.get_filebrowser_pod()
|
|
||||||
if not pod:
|
|
||||||
return "", "FileBrowser pod not found", 1
|
|
||||||
full_cmd = f"sudo kubectl exec {pod} -n {k8s.namespace} -- {command}"
|
|
||||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
|
||||||
|
|
||||||
|
|
||||||
@files_bp.route("/list", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def files_list():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
path = data.get("path", "/srv")
|
|
||||||
if not _validate_fb_path(path):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
|
|
||||||
).model_dump()), 403
|
|
||||||
import shlex
|
|
||||||
safe_path = shlex.quote(path)
|
|
||||||
out, err, rc = _fb_exec(f"ls -la {safe_path}", timeout=10)
|
|
||||||
if rc != 0:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="CommandError", message=err or "Failed to list directory"),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
files = []
|
|
||||||
for line in out.strip().split("\n")[1:]:
|
|
||||||
parts = line.split(None, 8)
|
|
||||||
if len(parts) >= 9:
|
|
||||||
name = parts[8]
|
|
||||||
if name in (".", ".."):
|
|
||||||
continue
|
|
||||||
files.append({
|
|
||||||
"name": name,
|
|
||||||
"is_dir": parts[0].startswith("d"),
|
|
||||||
"size": parts[4] if not parts[0].startswith("d") else "",
|
|
||||||
"perms": parts[0],
|
|
||||||
"date": " ".join(parts[5:8]),
|
|
||||||
})
|
|
||||||
return jsonify(ApiResponse(success=True, data={"files": files}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@files_bp.route("/view", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def files_view():
|
|
||||||
path = request.args.get("path", "")
|
|
||||||
if not path or not _validate_fb_path(path):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
|
|
||||||
).model_dump()), 403
|
|
||||||
import shlex
|
|
||||||
safe_path = shlex.quote(path)
|
|
||||||
out, err, rc = _fb_exec(f"head -c 100000 {safe_path}", timeout=10)
|
|
||||||
if rc != 0:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="CommandError", message=err or "Failed to read file"),
|
|
||||||
).model_dump()), 500
|
|
||||||
return jsonify(ApiResponse(success=True, data={"content": out, "path": path}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@files_bp.route("/save", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def files_save():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
path = data.get("path", "")
|
|
||||||
content = data.get("content", "")
|
|
||||||
if not path or not _validate_fb_path(path):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
|
|
||||||
).model_dump()), 403
|
|
||||||
import shlex
|
|
||||||
import base64
|
|
||||||
content_b64 = base64.b64encode(content.encode()).decode()
|
|
||||||
safe_path = shlex.quote(path)
|
|
||||||
# Write via base64 decode inside pod
|
|
||||||
cmd = f"echo {content_b64} | base64 -d > {safe_path}"
|
|
||||||
out, err, rc = _fb_exec(cmd, timeout=15)
|
|
||||||
if rc != 0:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="CommandError", message=err or "Failed to save file"),
|
|
||||||
).model_dump()), 500
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
# Health and SSE routes.
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, Response, request, stream_with_context
|
|
||||||
from flask_login import login_required, current_user
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
health_bp = Blueprint("health", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@health_bp.route("/health", methods=["GET"])
|
|
||||||
def health_check():
|
|
||||||
from app.factory import get_services
|
|
||||||
services = get_services()
|
|
||||||
health = {"status": "healthy", "timestamp": __import__("datetime").datetime.now().isoformat(), "checks": {}}
|
|
||||||
status_code = 200
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["db"].health_check()
|
|
||||||
health["checks"]["database"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["database"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["ssh"].check_connection()
|
|
||||||
health["checks"]["ssh"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["ssh"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["bg_director"].get_battlegroup()
|
|
||||||
health["checks"]["bgd"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["bgd"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["rmq_admin"].get_overview()
|
|
||||||
health["checks"]["rmq"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["rmq"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
return jsonify(health), status_code
|
|
||||||
|
|
||||||
|
|
||||||
@health_bp.route("/events/stream", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def sse_stream():
|
|
||||||
from app.factory import get_services
|
|
||||||
services = get_services()
|
|
||||||
realtime = services["realtime"]
|
|
||||||
|
|
||||||
queue = asyncio.Queue(maxsize=100)
|
|
||||||
realtime.add_client(queue)
|
|
||||||
|
|
||||||
def event_stream():
|
|
||||||
try:
|
|
||||||
yield "event: connected\ndata: {}\n\n"
|
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(loop)
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
msg = loop.run_until_complete(asyncio.wait_for(queue.get(), timeout=30))
|
|
||||||
yield msg
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
yield ":ping\n\n"
|
|
||||||
except Exception:
|
|
||||||
break
|
|
||||||
finally:
|
|
||||||
realtime.remove_client(queue)
|
|
||||||
|
|
||||||
return Response(stream_with_context(event_stream()), mimetype="text/event-stream")
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
# Server and infrastructure routes.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
server_bp = Blueprint("server", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_services():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/pods", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def server_pods():
|
|
||||||
services = _get_services()
|
|
||||||
pods = services["k8s"].get_pods()
|
|
||||||
return jsonify(ApiResponse(success=True, data=pods).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/deployments", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def server_deployments():
|
|
||||||
services = _get_services()
|
|
||||||
deployments = services["k8s"].get_deployments()
|
|
||||||
return jsonify(ApiResponse(success=True, data=deployments).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/metrics", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def server_metrics():
|
|
||||||
services = _get_services()
|
|
||||||
raw = services["k8s"].get_node_metrics()
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
metrics = []
|
|
||||||
if raw:
|
|
||||||
cpu_str = raw.get("cpu", "0m").replace("m", "").replace("%", "")
|
|
||||||
mem_str = raw.get("memory", "0Mi").replace("Mi", "").replace("Gi", "000")
|
|
||||||
try:
|
|
||||||
cpu_val = float(cpu_str)
|
|
||||||
mem_val = float(mem_str)
|
|
||||||
metrics.append({
|
|
||||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
||||||
"cpu_percent": min(100, round(cpu_val / 10, 1)), # rough estimate
|
|
||||||
"memory_percent": min(100, round(mem_val / 100, 1)), # rough estimate
|
|
||||||
})
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
return jsonify(ApiResponse(success=True, data=metrics).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/deployments/<name>/restart", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def restart_deployment(name: str):
|
|
||||||
services = _get_services()
|
|
||||||
out, err, rc = services["k8s"].run(f"rollout restart deployment/{name}")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=rc == 0,
|
|
||||||
data={"output": out, "error": err, "rc": rc},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/deployments/<name>/scale", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def scale_deployment(name: str):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
replicas = data.get("replicas")
|
|
||||||
if replicas is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing replicas"),
|
|
||||||
).model_dump()), 400
|
|
||||||
services = _get_services()
|
|
||||||
out, err, rc = services["k8s"].run(f"scale deployment/{name} --replicas={replicas}")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=rc == 0,
|
|
||||||
data={"output": out, "error": err, "rc": rc},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/action", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def server_action():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
deployment = data.get("deployment", "")
|
|
||||||
action = data.get("action", "")
|
|
||||||
if not deployment or not action:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing deployment or action"),
|
|
||||||
).model_dump()), 400
|
|
||||||
|
|
||||||
actions = {
|
|
||||||
"restart": f"rollout restart deployment/{deployment}",
|
|
||||||
"status": f"rollout status deployment/{deployment}",
|
|
||||||
"scale_0": f"scale deployment/{deployment} --replicas=0",
|
|
||||||
"scale_1": f"scale deployment/{deployment} --replicas=1",
|
|
||||||
"describe": f"describe deployment/{deployment}",
|
|
||||||
}
|
|
||||||
cmd = actions.get(action)
|
|
||||||
if not cmd:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
|
|
||||||
).model_dump()), 400
|
|
||||||
|
|
||||||
services = _get_services()
|
|
||||||
out, err, rc = services["k8s"].run(cmd)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=rc == 0,
|
|
||||||
data={"output": out, "error": err, "rc": rc},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/firewall", methods=["GET"])
|
|
||||||
@server_bp.route("/firewall/status", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def firewall_status():
|
|
||||||
services = _get_services()
|
|
||||||
ssh = services["ssh"]
|
|
||||||
out, _, _ = ssh.run(
|
|
||||||
"sudo iptables -L INPUT -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; "
|
|
||||||
"sudo iptables -L FORWARD -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; "
|
|
||||||
"sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E 'dpt:(18888|32479)'",
|
|
||||||
timeout=15,
|
|
||||||
)
|
|
||||||
blocked_ports = set()
|
|
||||||
for line in out.split("\n"):
|
|
||||||
for port in ("18888", "32479"):
|
|
||||||
if f"dpt:{port}" in line and "DROP" in line:
|
|
||||||
blocked_ports.add(port)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=True,
|
|
||||||
data={
|
|
||||||
"18888_blocked": "18888" in blocked_ports,
|
|
||||||
"32479_blocked": "32479" in blocked_ports,
|
|
||||||
},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/firewall/toggle", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def firewall_toggle():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
port = data.get("port")
|
|
||||||
block = data.get("block", True)
|
|
||||||
if not port:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing port"),
|
|
||||||
).model_dump()), 400
|
|
||||||
services = _get_services()
|
|
||||||
ssh = services["ssh"]
|
|
||||||
if block:
|
|
||||||
cmd = (
|
|
||||||
f"sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
|
|
||||||
f"sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP && "
|
|
||||||
f"sudo iptables -I FORWARD 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
|
|
||||||
f"sudo iptables -I FORWARD 2 -p tcp --dport {port} -j DROP && "
|
|
||||||
f"sudo iptables -t mangle -I PREROUTING 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
|
|
||||||
f"sudo iptables -t mangle -I PREROUTING 2 -p tcp --dport {port} -j DROP"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
cmd = (
|
|
||||||
f"sudo iptables -D INPUT -p tcp --dport {port} -j DROP 2>/dev/null; "
|
|
||||||
f"sudo iptables -D INPUT -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
|
|
||||||
f"sudo iptables -D FORWARD -p tcp --dport {port} -j DROP 2>/dev/null; "
|
|
||||||
f"sudo iptables -D FORWARD -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
|
|
||||||
f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -j DROP 2>/dev/null; "
|
|
||||||
f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
|
|
||||||
f"echo DONE"
|
|
||||||
)
|
|
||||||
out, err, rc = ssh.run(cmd, timeout=20)
|
|
||||||
success = rc == 0 or "DONE" in out
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=success,
|
|
||||||
data={"output": out, "error": err},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/rmq/queues", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def rmq_queues():
|
|
||||||
services = _get_services()
|
|
||||||
try:
|
|
||||||
queues = services["rmq_admin"].get_queue_depths()
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=True,
|
|
||||||
data=[q.model_dump() for q in queues],
|
|
||||||
).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="RmqError", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/rmq/overview", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def rmq_overview():
|
|
||||||
services = _get_services()
|
|
||||||
try:
|
|
||||||
overview = services["rmq_admin"].get_overview()
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=True,
|
|
||||||
data=overview.model_dump(),
|
|
||||||
).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="RmqError", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Services package init.
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
# Audit logging service — persistent PostgreSQL storage.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from app.services.database import DashboardDatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class AuditService:
|
|
||||||
def __init__(self, db: DashboardDatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def log(self, action: str, user: str, details: dict | None = None,
|
|
||||||
target_player_id: int | None = None, severity: str = "info",
|
|
||||||
source_ip: str | None = None) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"""INSERT INTO dashboard.audit_log
|
|
||||||
(action_type, user_name, target_player_id, details, source_ip, severity, created_at)
|
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, NOW())""",
|
|
||||||
[action, user, target_player_id, details or {}, source_ip, severity],
|
|
||||||
)
|
|
||||||
logger.info("Audit: %s by %s", action, user)
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Audit log failed: %s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def get_logs(self, action: str | None = None, user: str | None = None,
|
|
||||||
target_player_id: int | None = None, limit: int = 100,
|
|
||||||
offset: int = 0) -> list[dict]:
|
|
||||||
sql = """SELECT id, action_type, user_name, target_player_id, details,
|
|
||||||
source_ip, severity, created_at
|
|
||||||
FROM dashboard.audit_log WHERE 1=1"""
|
|
||||||
params = []
|
|
||||||
if action:
|
|
||||||
sql += " AND action_type = %s"
|
|
||||||
params.append(action)
|
|
||||||
if user:
|
|
||||||
sql += " AND user_name = %s"
|
|
||||||
params.append(user)
|
|
||||||
if target_player_id:
|
|
||||||
sql += " AND target_player_id = %s"
|
|
||||||
params.append(target_player_id)
|
|
||||||
sql += " ORDER BY created_at DESC LIMIT %s OFFSET %s"
|
|
||||||
params.extend([limit, offset])
|
|
||||||
return self.db.execute_readonly(sql, params)
|
|
||||||
|
|
||||||
def get_stats(self) -> dict:
|
|
||||||
rows = self.db.execute_readonly(
|
|
||||||
"""SELECT action_type, COUNT(*) as cnt FROM dashboard.audit_log
|
|
||||||
GROUP BY action_type"""
|
|
||||||
)
|
|
||||||
return {r["action_type"]: r["cnt"] for r in rows}
|
|
||||||
|
|
||||||
def cleanup_old(self, days: int = 90) -> int:
|
|
||||||
result = self.db.execute_mutation(
|
|
||||||
"DELETE FROM dashboard.audit_log WHERE created_at < NOW() - INTERVAL '%s days'",
|
|
||||||
[days],
|
|
||||||
)
|
|
||||||
logger.info("Audit cleanup: removed %d entries older than %d days", result, days)
|
|
||||||
return result
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
"""Battlegroup Director HTTP API client."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from typing import Any, Dict
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from app.models import BattlegroupState, ErrorDetail
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class BgDirectorService:
|
|
||||||
def __init__(self, host: str, node_port: int):
|
|
||||||
self.base_url = f"http://{host}:{node_port}"
|
|
||||||
self.client = httpx.Client(base_url=self.base_url, timeout=15)
|
|
||||||
logger.debug("BgDirectorService initialized: %s", self.base_url)
|
|
||||||
|
|
||||||
def _request(self, method: str, path: str, data: Any = None, timeout: int = 15) -> dict | str:
|
|
||||||
try:
|
|
||||||
if method == "GET":
|
|
||||||
resp = self.client.get(path, timeout=timeout)
|
|
||||||
else:
|
|
||||||
if isinstance(data, str):
|
|
||||||
resp = self.client.request(method, path, content=data, headers={"Content-Type": "application/json"}, timeout=timeout)
|
|
||||||
else:
|
|
||||||
resp = self.client.request(method, path, json=data, timeout=timeout)
|
|
||||||
resp.raise_for_status()
|
|
||||||
if resp.headers.get("content-type", "").startswith("application/json"):
|
|
||||||
return resp.json()
|
|
||||||
return resp.text
|
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error("BGD HTTP error %s %s: %s", method, path, e)
|
|
||||||
raise DirectorUnavailableError(f"BGD returned {e.response.status_code}")
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
logger.error("BGD connection error %s %s: %s", method, path, e)
|
|
||||||
raise DirectorUnavailableError("The Battlegroup Director is not responding. Check BGD pod logs.")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("BGD request error %s %s: %s", method, path, e)
|
|
||||||
raise DirectorUnavailableError(str(e))
|
|
||||||
|
|
||||||
# ── Player Endpoints ──────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_battlegroup(self) -> BattlegroupState:
|
|
||||||
data = self._request("GET", "/v0/battlegroup", timeout=15)
|
|
||||||
if isinstance(data, str):
|
|
||||||
data = json.loads(data)
|
|
||||||
return _parse_battlegroup(data)
|
|
||||||
|
|
||||||
def get_all_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_online_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/online")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_intransit_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/intransit")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_graceperiod_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/graceperiod")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_completion_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/completion")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_queued_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/queued")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
# ── FLS Settings ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_fls_settings(self) -> dict:
|
|
||||||
return self._request("GET", "/v0/BattlegroupFetchFlsReportSettings")
|
|
||||||
|
|
||||||
def update_fls_settings(self, settings: dict) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupUpdateFlsReportSettings", data=settings, timeout=30)
|
|
||||||
|
|
||||||
def clear_fls_overrides(self) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupClearFlsReportOverrides", timeout=30)
|
|
||||||
|
|
||||||
# ── Server Config ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
def update_server_config(self, config: dict) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupUpdateServerGroupConfig", data=config, timeout=30)
|
|
||||||
|
|
||||||
def clear_map_config(self, map_name: str) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupClearMapConfigOverrides", data=map_name, timeout=30)
|
|
||||||
|
|
||||||
# ── Character Transfer ──────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_transfer_rules(self) -> dict:
|
|
||||||
return self._request("GET", "/v0/BattlegroupFetchCharacterTransferRules")
|
|
||||||
|
|
||||||
def update_transfer_settings(self, config: dict) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupUpdateCharacterTransferSettings", data=config, timeout=30)
|
|
||||||
|
|
||||||
def clear_transfer_overrides(self) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupClearCharacterTransferOverrides", timeout=30)
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
self.client.close()
|
|
||||||
|
|
||||||
|
|
||||||
class DirectorUnavailableError(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_battlegroup(data: dict) -> BattlegroupState:
|
|
||||||
"""Parse raw BGD JSON into BattlegroupState model."""
|
|
||||||
state = BattlegroupState()
|
|
||||||
|
|
||||||
for key in ["dimensionMaps", "singleServerMaps", "instancedMaps"]:
|
|
||||||
if key in data:
|
|
||||||
target = "dimension_maps" if key == "dimensionMaps" else "single_server_maps" if key == "singleServerMaps" else "instanced_maps"
|
|
||||||
for mg in data[key]:
|
|
||||||
group = {"name": mg.get("name", ""), "servers": []}
|
|
||||||
for sv in mg.get("servers", []):
|
|
||||||
sst = sv.get("lastServerState", {})
|
|
||||||
sgs = sst.get("serverGameplaySettings", {})
|
|
||||||
server = {
|
|
||||||
"partition": sv.get("partition", ""),
|
|
||||||
"ip": sv.get("ip", ""),
|
|
||||||
"game_port": sv.get("gamePort", 7777),
|
|
||||||
"num_players": sv.get("numPlayers", 0),
|
|
||||||
"status": sv.get("status", "unknown"),
|
|
||||||
"hydration": sgs.get("hydration", 1.0),
|
|
||||||
"sandstorm": sgs.get("sandstorm", False),
|
|
||||||
"sandworm": sgs.get("sandworm", True),
|
|
||||||
"pvp_enabled": sgs.get("pvpEnabled", False),
|
|
||||||
"mining_multiplier": sgs.get("miningMultiplier", 1.0),
|
|
||||||
"durability": sgs.get("durability", 1.0),
|
|
||||||
}
|
|
||||||
group["servers"].append(server)
|
|
||||||
getattr(state, target).append(group)
|
|
||||||
|
|
||||||
return state
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
# Character service — rename, delete, demo, cheater flags using DB functions.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class CharacterService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def rename(self, account_id: int, name: str) -> bool:
|
|
||||||
self.db.call_procedure("set_character_name", [account_id, name])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def delete_character(self, actor_id: int) -> bool:
|
|
||||||
self.db.call_procedure("delete_character", [actor_id])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def delete_account(self, user_id: str, reason: str = "admin") -> bool:
|
|
||||||
self.db.call_procedure("delete_account", [user_id, reason])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def set_demo(self, user_id: str, state: str) -> bool:
|
|
||||||
self.db.call_procedure("set_demo_state", [user_id, state])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def flag_cheater(self, account_id: int, cheat_type: str) -> bool:
|
|
||||||
self.db.call_procedure("flag_player_as_cheater", [account_id, cheat_type])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def get_tags(self, account_id: int) -> list[str]:
|
|
||||||
rows = self.db.call_function("admin_read_player_tags", [account_id])
|
|
||||||
return [r.get("tag", "") for r in rows if r.get("tag")]
|
|
||||||
|
|
||||||
def update_tags(self, account_id: int, add: list[str], remove: list[str]) -> bool:
|
|
||||||
# DB-ONLY direct SQL — no function exists for tag management
|
|
||||||
for tag in add:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"INSERT INTO dune.player_tags (account_id, tag) VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
|
||||||
[account_id, tag],
|
|
||||||
)
|
|
||||||
if remove:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"DELETE FROM dune.player_tags WHERE account_id = %s AND tag = ANY(%s)",
|
|
||||||
[account_id, remove],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
# Chat service — chat history and log parsing.
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from app.services.database import DashboardDatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class ChatService:
|
|
||||||
def __init__(self, db: DashboardDatabaseService, k8s_service, ssh_service):
|
|
||||||
self.db = db
|
|
||||||
self.k8s = k8s_service
|
|
||||||
self.ssh = ssh_service
|
|
||||||
self.ensured_table = False
|
|
||||||
|
|
||||||
def ensure_history_table(self):
|
|
||||||
if self.ensured_table:
|
|
||||||
return True
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation("""
|
|
||||||
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
|
||||||
channel VARCHAR(50),
|
|
||||||
sender VARCHAR(255),
|
|
||||||
message TEXT,
|
|
||||||
target VARCHAR(255),
|
|
||||||
location_x FLOAT,
|
|
||||||
location_y FLOAT,
|
|
||||||
location_z FLOAT,
|
|
||||||
is_admin BOOLEAN DEFAULT FALSE
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)"
|
|
||||||
)
|
|
||||||
self.ensured_table = True
|
|
||||||
logger.info("Chat history table ready")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to create chat history table: %s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def save_message(self, channel, sender, message, target="", location=None, is_admin=False):
|
|
||||||
loc_x = location.get("X", 0) if location else 0
|
|
||||||
loc_y = location.get("Y", 0) if location else 0
|
|
||||||
loc_z = location.get("Z", 0) if location else 0
|
|
||||||
return self.db.execute_mutation(
|
|
||||||
"""INSERT INTO dashboard.chat_history
|
|
||||||
(channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
|
|
||||||
[channel, sender, message, target, loc_x, loc_y, loc_z, is_admin],
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_history(self, limit: int = 200) -> list[dict]:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT id, timestamp, channel, sender, message, target,
|
|
||||||
location_x, location_y, location_z, is_admin
|
|
||||||
FROM dashboard.chat_history ORDER BY timestamp DESC LIMIT %s""",
|
|
||||||
[limit],
|
|
||||||
)
|
|
||||||
|
|
||||||
def catch_up(self, namespace: str) -> int:
|
|
||||||
db_messages = self.get_history(1)
|
|
||||||
has_history = db_messages and len(db_messages) >= 10
|
|
||||||
if has_history:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if not namespace:
|
|
||||||
logger.warning("Cannot catch up — kubernetes namespace not set")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
pod_name = self.k8s.get_text_router_pod()
|
|
||||||
if not pod_name:
|
|
||||||
logger.warning("Cannot catch up — no text-router pod found")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
log_cmd = f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null"
|
|
||||||
out, err, rc = self.ssh.run(log_cmd, timeout=30)
|
|
||||||
if rc != 0 or not out:
|
|
||||||
logger.debug("Cannot catch up — failed to get pod logs (rc=%d)", rc)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
lines = [line for line in out.split("\n") if "CLOG" in line and "TextChat" in line]
|
|
||||||
lines = [line for line in lines if "Starting filtering" not in line]
|
|
||||||
lines = [line for line in lines if "Skipping filtering" not in line]
|
|
||||||
lines = [line for line in lines if "Redirected message" not in line]
|
|
||||||
|
|
||||||
messages = []
|
|
||||||
seen = set()
|
|
||||||
for line in lines:
|
|
||||||
if not line.strip():
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
idx = line.index("received message from ")
|
|
||||||
rest = line[idx + len("received message from "):]
|
|
||||||
parts = rest.split(" to ", 1)
|
|
||||||
if len(parts) < 2:
|
|
||||||
continue
|
|
||||||
sender_id = parts[0].strip()
|
|
||||||
target_and_json = parts[1]
|
|
||||||
target_idx = target_and_json.index(": ")
|
|
||||||
target = target_and_json[:target_idx].strip()
|
|
||||||
msg_str = target_and_json[target_idx + 2:].strip()
|
|
||||||
|
|
||||||
msg_data = json.loads(msg_str)
|
|
||||||
content = json.loads(msg_data.get("content", "{}"))
|
|
||||||
|
|
||||||
dedup_key = (
|
|
||||||
content.get("m_ChannelType", ""),
|
|
||||||
content.get("m_FuncomIdFrom", ""),
|
|
||||||
content.get("m_Message", {}).get("m_UnlocalizedMessage", ""),
|
|
||||||
)
|
|
||||||
if dedup_key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(dedup_key)
|
|
||||||
|
|
||||||
messages.append({
|
|
||||||
"channel": content.get("m_ChannelType", "Unknown"),
|
|
||||||
"sender": content.get("m_FuncomIdFrom", sender_id),
|
|
||||||
"message": content.get("m_Message", {}).get("m_UnlocalizedMessage", ""),
|
|
||||||
"target": target,
|
|
||||||
"location": content.get("m_OriginLocation", {}),
|
|
||||||
"is_admin": False,
|
|
||||||
})
|
|
||||||
except (ValueError, KeyError, json.JSONDecodeError, IndexError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
if messages:
|
|
||||||
saved = self._save_batch(messages)
|
|
||||||
logger.info("Caught up %d chat messages from pod logs", saved)
|
|
||||||
return saved
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def _save_batch(self, messages: list[dict]) -> int:
|
|
||||||
if not messages:
|
|
||||||
return 0
|
|
||||||
count = 0
|
|
||||||
for msg in messages:
|
|
||||||
if self.save_message(
|
|
||||||
msg["channel"], msg["sender"], msg["message"],
|
|
||||||
msg.get("target", ""), msg.get("location"), msg.get("is_admin", False),
|
|
||||||
):
|
|
||||||
count += 1
|
|
||||||
return count
|
|
||||||
@@ -1,400 +0,0 @@
|
|||||||
"""Database service — psycopg3 connection pool and stored procedure executor."""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import time
|
|
||||||
from typing import Any, List, Optional
|
|
||||||
|
|
||||||
import psycopg
|
|
||||||
from psycopg.rows import dict_row
|
|
||||||
from psycopg_pool import ConnectionPool
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class DatabaseService:
|
|
||||||
"""Service for game database queries (dune schema functions/procedures)."""
|
|
||||||
|
|
||||||
def __init__(self, db_config, min_conn=2, max_conn=10):
|
|
||||||
self.db_config = db_config
|
|
||||||
self.min_conn = min_conn
|
|
||||||
self.max_conn = max_conn
|
|
||||||
self.pool = None
|
|
||||||
|
|
||||||
def init_pool(self):
|
|
||||||
if self.pool is not None:
|
|
||||||
return self.pool
|
|
||||||
|
|
||||||
conninfo = (
|
|
||||||
f"host={self.db_config['host']} "
|
|
||||||
f"port={self.db_config['port']} "
|
|
||||||
f"dbname={self.db_config['database']} "
|
|
||||||
f"user={self.db_config['user']} "
|
|
||||||
f"password={self.db_config['password']}"
|
|
||||||
)
|
|
||||||
|
|
||||||
for attempt in range(10):
|
|
||||||
try:
|
|
||||||
self.pool = ConnectionPool(
|
|
||||||
conninfo=conninfo,
|
|
||||||
min_size=self.min_conn,
|
|
||||||
max_size=self.max_conn,
|
|
||||||
open=False,
|
|
||||||
)
|
|
||||||
self.pool.open(wait=True, timeout=20)
|
|
||||||
logger.info("Database connection pool initialized (psycopg3)")
|
|
||||||
return self.pool
|
|
||||||
except Exception as e:
|
|
||||||
if attempt < 9:
|
|
||||||
logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
|
||||||
time.sleep(2)
|
|
||||||
else:
|
|
||||||
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
|
||||||
self.pool = None
|
|
||||||
return self.pool
|
|
||||||
|
|
||||||
def call_function(self, name: str, args: List[Any]) -> List[dict]:
|
|
||||||
"""Call a dune schema function and return rows as dicts."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
placeholders = ",".join(["%s"] * len(args))
|
|
||||||
sql = f"SELECT * FROM dune.{name}({placeholders})"
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor(row_factory=dict_row) as cur:
|
|
||||||
cur.execute(sql, args)
|
|
||||||
rows = cur.fetchall()
|
|
||||||
return rows if rows else []
|
|
||||||
|
|
||||||
def call_procedure(self, name: str, args: List[Any]) -> None:
|
|
||||||
"""Call a dune schema procedure (void return)."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
placeholders = ",".join(["%s"] * len(args))
|
|
||||||
sql = f"CALL dune.{name}({placeholders})"
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(sql, args)
|
|
||||||
conn.commit()
|
|
||||||
|
|
||||||
def execute_readonly(self, sql: str, params: Optional[List[Any]] = None) -> List[dict]:
|
|
||||||
"""Execute a read-only SELECT query."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor(row_factory=dict_row) as cur:
|
|
||||||
cur.execute(sql, params or [])
|
|
||||||
rows = cur.fetchall()
|
|
||||||
return rows if rows else []
|
|
||||||
|
|
||||||
def execute_mutation(self, sql: str, params: Optional[List[Any]] = None) -> int:
|
|
||||||
"""Execute a direct mutation (UPDATE/INSERT/DELETE) with validation."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(sql, params or [])
|
|
||||||
conn.commit()
|
|
||||||
return cur.rowcount
|
|
||||||
|
|
||||||
def health_check(self) -> bool:
|
|
||||||
try:
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
return False
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute("SELECT 1")
|
|
||||||
cur.fetchone()
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Database health check FAILED: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
if self.pool:
|
|
||||||
try:
|
|
||||||
self.pool.close()
|
|
||||||
logger.info("Database pool closed")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error closing pool: {e}")
|
|
||||||
self.pool = None
|
|
||||||
|
|
||||||
|
|
||||||
class DashboardDatabaseService:
|
|
||||||
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
|
|
||||||
|
|
||||||
def __init__(self, db_config, min_conn=2, max_conn=10, owner="dune"):
|
|
||||||
self.db_config = db_config
|
|
||||||
self.min_conn = min_conn
|
|
||||||
self.max_conn = max_conn
|
|
||||||
self.owner = owner
|
|
||||||
self.pool = None
|
|
||||||
self._migrated = False
|
|
||||||
|
|
||||||
def _conninfo(self, dbname=None):
|
|
||||||
return (
|
|
||||||
f"host={self.db_config['host']} "
|
|
||||||
f"port={self.db_config['port']} "
|
|
||||||
f"dbname={dbname or self.db_config['database']} "
|
|
||||||
f"user={self.db_config['user']} "
|
|
||||||
f"password={self.db_config['password']}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def _temp_connection(self, dbname="postgres"):
|
|
||||||
"""Get a temporary single connection (for database creation)."""
|
|
||||||
conn = psycopg.connect(self._conninfo(dbname))
|
|
||||||
conn.autocommit = True
|
|
||||||
return conn
|
|
||||||
|
|
||||||
def init_pool(self):
|
|
||||||
if self.pool is not None:
|
|
||||||
return self.pool
|
|
||||||
|
|
||||||
conninfo = self._conninfo()
|
|
||||||
|
|
||||||
for attempt in range(10):
|
|
||||||
try:
|
|
||||||
self.pool = ConnectionPool(
|
|
||||||
conninfo=conninfo,
|
|
||||||
min_size=self.min_conn,
|
|
||||||
max_size=self.max_conn,
|
|
||||||
open=False,
|
|
||||||
)
|
|
||||||
self.pool.open(wait=True, timeout=20)
|
|
||||||
logger.info("Dashboard database pool initialized")
|
|
||||||
return self.pool
|
|
||||||
except psycopg.errors.OperationalError as e:
|
|
||||||
if "does not exist" in str(e) and attempt == 0:
|
|
||||||
logger.info("Dashboard database does not exist, creating...")
|
|
||||||
self._ensure_database()
|
|
||||||
continue
|
|
||||||
if attempt < 9:
|
|
||||||
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
|
||||||
time.sleep(2)
|
|
||||||
else:
|
|
||||||
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
|
||||||
self.pool = None
|
|
||||||
except Exception as e:
|
|
||||||
if attempt < 9:
|
|
||||||
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
|
||||||
time.sleep(2)
|
|
||||||
else:
|
|
||||||
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
|
||||||
self.pool = None
|
|
||||||
return self.pool
|
|
||||||
|
|
||||||
def _ensure_database(self):
|
|
||||||
"""Create the dashboard database if it doesn't exist."""
|
|
||||||
try:
|
|
||||||
conn = self._temp_connection("postgres")
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(
|
|
||||||
"SELECT 1 FROM pg_database WHERE datname = %s",
|
|
||||||
[self.db_config["database"]],
|
|
||||||
)
|
|
||||||
if not cur.fetchone():
|
|
||||||
cur.execute(
|
|
||||||
f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}"
|
|
||||||
)
|
|
||||||
logger.info("Created dashboard database '%s'", self.db_config["database"])
|
|
||||||
else:
|
|
||||||
logger.debug("Dashboard database already exists")
|
|
||||||
conn.close()
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to create dashboard database: %s", e)
|
|
||||||
raise
|
|
||||||
|
|
||||||
def _migrate_old_schema(self, game_db):
|
|
||||||
"""Migrate data from old dashboard schema in the game database."""
|
|
||||||
if self._migrated:
|
|
||||||
return
|
|
||||||
|
|
||||||
tables = ["settings", "bans", "player_ips", "player_actions", "audit_log", "chat_history"]
|
|
||||||
migrated = False
|
|
||||||
|
|
||||||
for table in tables:
|
|
||||||
try:
|
|
||||||
rows = game_db.execute_readonly(
|
|
||||||
f"SELECT count(*) as cnt FROM dashboard.{table}"
|
|
||||||
)
|
|
||||||
if rows and rows[0]["cnt"] > 0:
|
|
||||||
logger.info("Migrating %d rows from dashboard.%s", rows[0]["cnt"], table)
|
|
||||||
old_rows = game_db.execute_readonly(f"SELECT * FROM dashboard.{table}")
|
|
||||||
if old_rows:
|
|
||||||
cols = list(old_rows[0].keys())
|
|
||||||
placeholders = ",".join([f"%s"] * len(cols))
|
|
||||||
col_names = ",".join(cols)
|
|
||||||
for row in old_rows:
|
|
||||||
vals = [row[c] for c in cols]
|
|
||||||
self.execute_mutation(
|
|
||||||
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
|
|
||||||
vals,
|
|
||||||
)
|
|
||||||
migrated = True
|
|
||||||
logger.info("Migrated dashboard.%s → %s (%d rows)", table, table, rows[0]["cnt"])
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
|
|
||||||
|
|
||||||
if migrated:
|
|
||||||
logger.info("Data migration from old dashboard schema complete")
|
|
||||||
self._migrated = True
|
|
||||||
|
|
||||||
def ensure_tables(self, game_db=None):
|
|
||||||
"""Ensure tables exist in the dashboard database and migrate if needed."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
return
|
|
||||||
|
|
||||||
ddl = """
|
|
||||||
CREATE TABLE IF NOT EXISTS audit_log (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
action_type VARCHAR(50) NOT NULL,
|
|
||||||
user_name VARCHAR(100) NOT NULL,
|
|
||||||
target_player_id BIGINT,
|
|
||||||
details JSONB DEFAULT '{}',
|
|
||||||
source_ip INET,
|
|
||||||
severity VARCHAR(20) DEFAULT 'info',
|
|
||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON audit_log (created_at DESC);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_action ON audit_log (action_type);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log (user_name);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS player_ips (
|
|
||||||
player_id BIGINT PRIMARY KEY,
|
|
||||||
ip_address INET NOT NULL,
|
|
||||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS bans (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
player_id BIGINT UNIQUE,
|
|
||||||
account_id BIGINT,
|
|
||||||
reason TEXT DEFAULT '',
|
|
||||||
note TEXT DEFAULT '',
|
|
||||||
duration INT DEFAULT 0,
|
|
||||||
banned_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
||||||
expires_at TIMESTAMP,
|
|
||||||
active BOOLEAN DEFAULT TRUE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS player_actions (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
player_id BIGINT NOT NULL,
|
|
||||||
action_type VARCHAR(50) NOT NULL,
|
|
||||||
reason TEXT DEFAULT '',
|
|
||||||
note TEXT DEFAULT '',
|
|
||||||
duration_minutes INT DEFAULT 0,
|
|
||||||
ip_address INET,
|
|
||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_history (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
|
||||||
channel VARCHAR(50),
|
|
||||||
sender VARCHAR(255),
|
|
||||||
message TEXT,
|
|
||||||
target VARCHAR(255),
|
|
||||||
location_x FLOAT,
|
|
||||||
location_y FLOAT,
|
|
||||||
location_z FLOAT,
|
|
||||||
is_admin BOOLEAN DEFAULT FALSE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS settings (
|
|
||||||
key VARCHAR(255) PRIMARY KEY,
|
|
||||||
value TEXT DEFAULT '',
|
|
||||||
updated_at TIMESTAMP DEFAULT NOW()
|
|
||||||
);
|
|
||||||
"""
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(ddl)
|
|
||||||
|
|
||||||
owner = self.owner
|
|
||||||
cur.execute(f"""
|
|
||||||
DO $$DECLARE r RECORD;
|
|
||||||
BEGIN
|
|
||||||
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
|
|
||||||
LOOP
|
|
||||||
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
|
|
||||||
END LOOP;
|
|
||||||
END$$;
|
|
||||||
""")
|
|
||||||
cur.execute(f"""
|
|
||||||
DO $$DECLARE r RECORD;
|
|
||||||
BEGIN
|
|
||||||
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
|
|
||||||
LOOP
|
|
||||||
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
|
|
||||||
END LOOP;
|
|
||||||
END$$;
|
|
||||||
""")
|
|
||||||
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
|
|
||||||
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
|
|
||||||
|
|
||||||
conn.commit()
|
|
||||||
|
|
||||||
logger.info("Dashboard tables ensured, owner=%s", owner)
|
|
||||||
|
|
||||||
if game_db is not None:
|
|
||||||
self._migrate_old_schema(game_db)
|
|
||||||
|
|
||||||
def execute_readonly(self, sql: str, params: Optional[List[Any]] = None) -> List[dict]:
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Dashboard database pool not available")
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor(row_factory=dict_row) as cur:
|
|
||||||
cur.execute(sql, params or [])
|
|
||||||
rows = cur.fetchall()
|
|
||||||
return rows if rows else []
|
|
||||||
|
|
||||||
def execute_mutation(self, sql: str, params: Optional[List[Any]] = None) -> int:
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Dashboard database pool not available")
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(sql, params or [])
|
|
||||||
conn.commit()
|
|
||||||
return cur.rowcount
|
|
||||||
|
|
||||||
def health_check(self) -> bool:
|
|
||||||
try:
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
return False
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute("SELECT 1")
|
|
||||||
cur.fetchone()
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("Dashboard database health check FAILED: %s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
if self.pool:
|
|
||||||
try:
|
|
||||||
self.pool.close()
|
|
||||||
logger.info("Dashboard database pool closed")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Error closing dashboard pool: %s", e)
|
|
||||||
self.pool = None
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
# Economy service — items, currency, vitals, vendors. Uses direct SQL.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class EconomyService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def get_inventory(self, account_id: int) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT it.id, it.item_name, it.quantity, it.durability
|
|
||||||
FROM dune.inventory_items it
|
|
||||||
WHERE it.account_id = %s
|
|
||||||
ORDER BY it.item_name""",
|
|
||||||
[account_id],
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_currency(self, player_id: int) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT currency_id, balance
|
|
||||||
FROM dune.player_currency
|
|
||||||
WHERE player_controller_id = %s""",
|
|
||||||
[player_id],
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_vitals(self, pawn_id: int) -> dict | None:
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(
|
|
||||||
"""SELECT current_health, max_health, current_stamina,
|
|
||||||
max_stamina, current_water, max_water,
|
|
||||||
current_oxygen, max_oxygen
|
|
||||||
FROM dune.player_state
|
|
||||||
WHERE player_pawn_id = %s
|
|
||||||
LIMIT 1""",
|
|
||||||
[pawn_id],
|
|
||||||
)
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def add_item(self, inventory_id: int, template_id: str, stack_size: int = 1, quality_level: int = 0) -> int:
|
|
||||||
sql = """INSERT INTO dune.inventory_items (inventory_id, template_id, quantity, quality_level)
|
|
||||||
VALUES (%s, %s, %s, %s) RETURNING id"""
|
|
||||||
rows = self.db.execute_mutation(sql, [inventory_id, template_id, stack_size, quality_level])
|
|
||||||
if rows and rows[0].get("id"):
|
|
||||||
return rows[0]["id"]
|
|
||||||
raise ValueError("Item add failed")
|
|
||||||
|
|
||||||
def delete_item(self, item_id: int) -> bool:
|
|
||||||
self.db.execute_mutation("DELETE FROM dune.inventory_items WHERE id = %s", [item_id])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def edit_item_field(self, item_id: int, field: str, value: Any) -> bool:
|
|
||||||
allowed = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"}
|
|
||||||
if field not in allowed:
|
|
||||||
raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(allowed))}")
|
|
||||||
self.db.execute_mutation(
|
|
||||||
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
|
|
||||||
[value, item_id],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
# Guild service — uses direct SQL matching old working dashboard.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"}
|
|
||||||
|
|
||||||
|
|
||||||
class GuildService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def list_all(self) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
f.name as faction_name,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
LEFT JOIN dune.factions f ON g.faction_id = f.id
|
|
||||||
ORDER BY g.id
|
|
||||||
""")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Guild list via faction join failed: {e}, trying fallback")
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
NULL as faction_name,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
ORDER BY g.id
|
|
||||||
""")
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_detail(self, guild_id: int) -> dict | None:
|
|
||||||
try:
|
|
||||||
guild_rows = self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
f.name as faction_name, g.faction_id as guild_faction,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
LEFT JOIN dune.factions f ON g.faction_id = f.id
|
|
||||||
WHERE g.id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
except Exception:
|
|
||||||
guild_rows = self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
NULL as faction_name, NULL as guild_faction,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
WHERE g.id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
|
|
||||||
if not guild_rows:
|
|
||||||
return None
|
|
||||||
|
|
||||||
g = guild_rows[0]
|
|
||||||
try:
|
|
||||||
member_rows = self.db.execute_readonly("""
|
|
||||||
SELECT gm.player_id, gm.role_id, ps.character_name as name,
|
|
||||||
ps.online_status::text as online_status
|
|
||||||
FROM dune.guild_members gm
|
|
||||||
LEFT JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id
|
|
||||||
WHERE gm.guild_id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
except Exception:
|
|
||||||
member_rows = self.db.execute_readonly("""
|
|
||||||
SELECT gm.player_id, gm.role_id, NULL as name, NULL as online_status
|
|
||||||
FROM dune.guild_members gm
|
|
||||||
WHERE gm.guild_id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
|
|
||||||
members = [{
|
|
||||||
"player_id": r.get("player_id"),
|
|
||||||
"role_id": r.get("role_id"),
|
|
||||||
"role_name": GUILD_ROLES.get(r.get("role_id", 50), "Member"),
|
|
||||||
"name": r.get("name") or "Unknown",
|
|
||||||
"online_status": r.get("online_status") or "Unknown",
|
|
||||||
} for r in (member_rows or [])]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"guild_id": g.get("guild_id"),
|
|
||||||
"guild_name": g.get("guild_name", ""),
|
|
||||||
"guild_description": g.get("guild_description"),
|
|
||||||
"faction_name": g.get("faction_name"),
|
|
||||||
"faction_id": g.get("guild_faction"),
|
|
||||||
"members": members,
|
|
||||||
}
|
|
||||||
|
|
||||||
def disband(self, guild_id: int) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation("SELECT dune.disband_guild(%s)", [guild_id])
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def remove_member(self, guild_id: int, player_id: int, reason: int = 0) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"DELETE FROM dune.guild_members WHERE guild_id = %s AND player_id = %s",
|
|
||||||
[guild_id, player_id],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def promote(self, guild_id: int, player_id: int, role_id: int) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"UPDATE dune.guild_members SET role_id = %s WHERE guild_id = %s AND player_id = %s",
|
|
||||||
[role_id, guild_id, player_id],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
"""Kubernetes service — kubectl operations via SSH."""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class K8sService:
|
|
||||||
def __init__(self, ssh_service, namespace):
|
|
||||||
self.ssh = ssh_service
|
|
||||||
self.namespace = namespace
|
|
||||||
|
|
||||||
def run(self, kubectl_command, timeout=30):
|
|
||||||
full_cmd = f"sudo kubectl {kubectl_command} -n {self.namespace}"
|
|
||||||
logger.debug("K8s executing: %s", full_cmd)
|
|
||||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
|
||||||
out, err, rc = result
|
|
||||||
if rc != 0:
|
|
||||||
logger.debug("K8s command failed (rc=%d): %s", rc, err[:100] if err else "no error")
|
|
||||||
else:
|
|
||||||
logger.debug("K8s command OK, output lines: %d", len(out.split("\n")) if out else 0)
|
|
||||||
return result
|
|
||||||
|
|
||||||
def get_pods(self):
|
|
||||||
out, err, rc = self.run("get pods -o json")
|
|
||||||
if rc != 0:
|
|
||||||
logger.error("Failed to get pods: %s", err)
|
|
||||||
return []
|
|
||||||
try:
|
|
||||||
import json
|
|
||||||
data = json.loads(out or "{}")
|
|
||||||
items = data.get("items", [])
|
|
||||||
pods = []
|
|
||||||
for item in items:
|
|
||||||
metadata = item.get("metadata", {})
|
|
||||||
status = item.get("status", {})
|
|
||||||
container_statuses = status.get("containerStatuses", [])
|
|
||||||
restarts = sum(c.get("restartCount", 0) for c in container_statuses)
|
|
||||||
pods.append({
|
|
||||||
"name": metadata.get("name", ""),
|
|
||||||
"namespace": metadata.get("namespace", self.namespace),
|
|
||||||
"status": status.get("phase", "Unknown"),
|
|
||||||
"restarts": restarts,
|
|
||||||
"age": self._age_from_creation(metadata.get("creationTimestamp")),
|
|
||||||
})
|
|
||||||
logger.debug("Found %d pods in namespace %s", len(pods), self.namespace)
|
|
||||||
return pods
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to parse pods: %s", e)
|
|
||||||
return []
|
|
||||||
|
|
||||||
def find_pod_by_pattern(self, pattern):
|
|
||||||
pods = self.get_pods()
|
|
||||||
for pod in pods:
|
|
||||||
if pattern.lower() in pod.lower():
|
|
||||||
return pod
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_text_router_pod(self):
|
|
||||||
pod = self.find_pod_by_pattern("tr-deploy")
|
|
||||||
if pod:
|
|
||||||
return pod
|
|
||||||
pod = self.find_pod_by_pattern("text")
|
|
||||||
if pod:
|
|
||||||
return pod
|
|
||||||
return self.find_pod_by_pattern("router")
|
|
||||||
|
|
||||||
def get_rabbitmq_pod(self, admin=True):
|
|
||||||
if admin:
|
|
||||||
return self.find_pod_by_pattern("mq-admin")
|
|
||||||
return self.find_pod_by_pattern("mq-game")
|
|
||||||
|
|
||||||
def get_filebrowser_pod(self):
|
|
||||||
return self.find_pod_by_pattern("fb-deploy")
|
|
||||||
|
|
||||||
def get_deployments(self):
|
|
||||||
out, err, rc = self.run("get deployments -o json")
|
|
||||||
if rc != 0:
|
|
||||||
return []
|
|
||||||
try:
|
|
||||||
import json
|
|
||||||
data = json.loads(out or "{}")
|
|
||||||
items = data.get("items", [])
|
|
||||||
deployments = []
|
|
||||||
for item in items:
|
|
||||||
metadata = item.get("metadata", {})
|
|
||||||
spec = item.get("spec", {})
|
|
||||||
status = item.get("status", {})
|
|
||||||
deployments.append({
|
|
||||||
"name": metadata.get("name", ""),
|
|
||||||
"namespace": metadata.get("namespace", self.namespace),
|
|
||||||
"replicas": spec.get("replicas", 0),
|
|
||||||
"available": status.get("availableReplicas", 0),
|
|
||||||
})
|
|
||||||
return deployments
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to parse deployments: %s", e)
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_node_metrics(self):
|
|
||||||
out, err, rc = self.run("top nodes")
|
|
||||||
if rc == 0 and out.strip():
|
|
||||||
lines = out.strip().split("\n")
|
|
||||||
if len(lines) >= 2:
|
|
||||||
parts = lines[1].split()
|
|
||||||
if len(parts) >= 4:
|
|
||||||
return {
|
|
||||||
"cpu": parts[2],
|
|
||||||
"memory": parts[3],
|
|
||||||
"cpu_pct": parts[1],
|
|
||||||
}
|
|
||||||
return {}
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _age_from_creation(timestamp: str | None) -> str:
|
|
||||||
if not timestamp:
|
|
||||||
return "Unknown"
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
try:
|
|
||||||
created = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
|
||||||
delta = datetime.now(timezone.utc) - created
|
|
||||||
days = delta.days
|
|
||||||
hours = delta.seconds // 3600
|
|
||||||
minutes = (delta.seconds % 3600) // 60
|
|
||||||
if days > 0:
|
|
||||||
return f"{days}d"
|
|
||||||
if hours > 0:
|
|
||||||
return f"{hours}h"
|
|
||||||
return f"{minutes}m"
|
|
||||||
except Exception:
|
|
||||||
return "Unknown"
|
|
||||||
|
|
||||||
def auto_detect_namespace(self):
|
|
||||||
out, err, rc = self.ssh.run("sudo kubectl get namespaces -o name", timeout=10)
|
|
||||||
if rc == 0:
|
|
||||||
for line in (out or "").strip().split("\n"):
|
|
||||||
ns = line.replace("namespace/", "").strip()
|
|
||||||
if ns.startswith("funcom-seabass-"):
|
|
||||||
logger.info("Auto-detected K8s namespace: %s", ns)
|
|
||||||
self.namespace = ns
|
|
||||||
return ns
|
|
||||||
return None
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
# Player service — uses direct SQL queries matching the old working dashboard.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import List, Any
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
LIKE_PC = '%DunePlayerCharacter_C'
|
|
||||||
|
|
||||||
|
|
||||||
class PlayerService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def search(self, term: str, limit: int = 50) -> list[dict]:
|
|
||||||
where = "a.class LIKE %s"
|
|
||||||
params: list[Any] = [LIKE_PC]
|
|
||||||
if term:
|
|
||||||
where += """ AND (
|
|
||||||
ps.character_name ILIKE %s
|
|
||||||
OR acc.funcom_id ILIKE %s
|
|
||||||
OR ea.user ILIKE %s
|
|
||||||
)"""
|
|
||||||
params.extend([f'%{term}%'] * 3)
|
|
||||||
|
|
||||||
sql = f"""
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.character_name, ps.online_status::text as online_status,
|
|
||||||
ps.life_state, acc.funcom_id, ps.account_id,
|
|
||||||
a.map, a.id as actor_id,
|
|
||||||
pf.faction_id, f.name as faction_name,
|
|
||||||
acc.last_login as last_login_time
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.player_state ps ON (a.properties->>'m_PlayerControllerId')::bigint = ps.player_controller_id
|
|
||||||
LEFT JOIN dune.actor_faction af ON a.id = af.actor_id
|
|
||||||
LEFT JOIN dune.factions f ON af.faction_id = f.id
|
|
||||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.player_controller_id
|
|
||||||
LEFT JOIN dune.entity_actors ea ON a.owner_id = ea.id
|
|
||||||
LEFT JOIN dune.accounts acc ON ea.id = acc.id
|
|
||||||
WHERE {where}
|
|
||||||
ORDER BY ps.character_name
|
|
||||||
LIMIT %s
|
|
||||||
"""
|
|
||||||
params.append(limit)
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, params)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Player search via actor join failed: {e}, trying fallback")
|
|
||||||
return self._search_fallback(term, limit)
|
|
||||||
|
|
||||||
def _search_fallback(self, term: str, limit: int = 50) -> list[dict]:
|
|
||||||
"""Fallback using only player_state and accounts."""
|
|
||||||
where = "1=1"
|
|
||||||
params: list[Any] = []
|
|
||||||
if term:
|
|
||||||
where = """(
|
|
||||||
ps.character_name ILIKE %s
|
|
||||||
OR acc.funcom_id ILIKE %s
|
|
||||||
)"""
|
|
||||||
params = [f'%{term}%', f'%{term}%']
|
|
||||||
sql = f"""
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.character_name, ps.online_status::text as online_status,
|
|
||||||
ps.life_state, acc.funcom_id, ps.account_id,
|
|
||||||
NULL as map, NULL as actor_id,
|
|
||||||
NULL as faction_id, NULL as faction_name,
|
|
||||||
NULL as last_login_time
|
|
||||||
FROM dune.player_state ps
|
|
||||||
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
|
|
||||||
WHERE {where}
|
|
||||||
ORDER BY ps.character_name
|
|
||||||
LIMIT %s
|
|
||||||
"""
|
|
||||||
params.append(limit)
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, params)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Player search fallback failed")
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_detail(self, account_id: int) -> dict | None:
|
|
||||||
sql = """
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.player_pawn_id, ps.character_name,
|
|
||||||
ps.online_status::text as online_status, ps.life_state,
|
|
||||||
ps.account_id, acc.funcom_id, acc.email as account_email,
|
|
||||||
a.map, a.id as actor_id,
|
|
||||||
f.name as faction_name, pf.faction_id,
|
|
||||||
acc.last_login as last_login_time,
|
|
||||||
ps.current_health, ps.max_health,
|
|
||||||
ps.current_stamina, ps.max_stamina,
|
|
||||||
ps.current_water, ps.max_water,
|
|
||||||
ps.current_oxygen, ps.max_oxygen,
|
|
||||||
ps.xp, ps.tech_knowledge
|
|
||||||
FROM dune.player_state ps
|
|
||||||
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
|
|
||||||
LEFT JOIN dune.actors a ON (a.properties->>'m_PlayerControllerId')::bigint = ps.player_controller_id
|
|
||||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.player_controller_id
|
|
||||||
LEFT JOIN dune.factions f ON pf.faction_id = f.id
|
|
||||||
WHERE ps.account_id = %s
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(sql, [account_id])
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Player detail via actor failed: {e}, trying fallback")
|
|
||||||
return self._get_detail_fallback(account_id)
|
|
||||||
|
|
||||||
def _get_detail_fallback(self, account_id: int) -> dict | None:
|
|
||||||
sql = """
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.player_pawn_id, ps.character_name,
|
|
||||||
ps.online_status::text as online_status, ps.life_state,
|
|
||||||
ps.account_id, acc.funcom_id, acc.email as account_email,
|
|
||||||
NULL as map, NULL as actor_id,
|
|
||||||
NULL as faction_name, NULL as faction_id,
|
|
||||||
NULL as last_login_time,
|
|
||||||
NULL as current_health, NULL as max_health,
|
|
||||||
NULL as current_stamina, NULL as max_stamina,
|
|
||||||
NULL as current_water, NULL as max_water,
|
|
||||||
NULL as current_oxygen, NULL as max_oxygen,
|
|
||||||
NULL as xp, NULL as tech_knowledge
|
|
||||||
FROM dune.player_state ps
|
|
||||||
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
|
|
||||||
WHERE ps.account_id = %s
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(sql, [account_id])
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_inventory(self, account_id: int) -> list[dict]:
|
|
||||||
"""Get player inventory items."""
|
|
||||||
sql = """
|
|
||||||
SELECT it.id, it.item_name, it.quantity, it.durability
|
|
||||||
FROM dune.inventory_items it
|
|
||||||
WHERE it.account_id = %s
|
|
||||||
ORDER BY it.item_name
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, [account_id])
|
|
||||||
except Exception:
|
|
||||||