Compare commits

..
12 Commits
Author SHA1 Message Date
Reditus 306ebcc871 feat: vertical/horizontal nav layout toggle with grouped dropdowns, mobile auto-sidebar 2026-06-14 22:54:55 +01:00
Reditus 3486f3b2cb feat: pod management UI (logs, describe, delete, list) with csrfFetch fix 2026-06-14 12:01:27 +01:00
Reditus 42eec81081 fix: SSH keepalive, director fallback, Ctrl+C handler, namespace ordering
- SSH transport keepalive (15s) + stale client cleanup for reliable reconnection
- Ctrl+C signal handler (os._exit) to bypass stuck daemon threads
- Director API fallback: SSH + wget to BGD service cluster IP (no tunnel needed)
- Namespace auto-detection moved before DirectorService creation
- Director host defaults to 127.0.0.1 (configurable via director.host)
- Connection monitor: 60s -> 30s interval
- Backup scheduler: skip if SSH unreachable instead of blocking 300s
2026-06-14 11:09:31 +01:00
Reditus 65a1948fd1 feat: add backup/restore with encryption, scheduling, and node resource charts
- Full backup: game DB, K8s manifests, RMQ config, dashboard schema
- AES-256-GCM encryption with PBKDF2 key derivation
- Restore wizard with SSH-based deployment to new VM
- Dashboard schema backup (bans, audit, chat, player_ips, settings)
- Scheduled backups: interval mode (days/hours/mins) or specific days + multiple times
- Retention policy (auto-delete oldest backups beyond keep limit)
- Password protection with sidecar metadata for preview without unlock
- Verify with optional password for encrypted archives
- Node resource charts (CPU/memory) with 5-min history on server page
- csrfFetch moved to head for correct script execution order
2026-06-14 10:12:27 +01:00
Reditus 1d1d2ab2ee fix: use ON CONFLICT DO NOTHING in migration; replace launcher.ps1 with tested version (SID fix, StrictHostKeyChecking=no, BatchMode=yes, ConnectTimeout) 2026-06-01 07:51:16 +01:00
Reditus 32517999f3 fix: wrap Set-Acl in try/catch to avoid SeSecurityPrivilege error on SSH key rotate 2026-06-01 05:47:04 +01:00
Reditus 5d19f772e5 docs: update README to reflect removal of backend/frontend and launcher-driven workflow 2026-06-01 05:40:45 +01:00
Reditus 9ea0829789 feat: add SSH key rotation menu option [10] 2026-06-01 05:36:41 +01:00
Reditus 5ecf9f2417 chore: remove new dashboard (backend/ + frontend/) from repo and launcher 2026-05-30 04:49:40 +01:00
Reditus 18e85592b7 Merge Experimental into nightly for v0.5.0 sync 2026-05-30 01:42:18 +01:00
Reditus c7a0260569 Revise README
Updated the README
2026-05-30 01:35:39 +01:00
Reditus 17232053ee Revise README
Updated README
2026-05-30 01:34:23 +01:00
95 changed files with 2749 additions and 12340 deletions

No files matched your search

+4
View File
@@ -14,6 +14,10 @@ frontend/.pnpm-store/
frontend/.vite/
frontend/dist/
# New dashboard (removed - legacy only)
backend/
frontend/
# Virtual environments
venv/
env/
+69 -326
View File
@@ -1,361 +1,104 @@
# Dune Awakening Dashboard
A comprehensive web-based management dashboard for Dune: Awakening private servers. Provides real-time monitoring, player management, chat logging, file browsing, and server administration tools.
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.
## Branching Strategy
> “A comprehensive web-based management dashboard for Dune: Awakening private servers.”
This repo follows a git-flow inspired strategy. Here's the breakdown:
- **main** - Current beta release. It's stable enough to use, but things still break occasionally. I'm working toward a proper stable release, but we're not there yet. Don't use main as a reference for "production-ready" code - it's more "production-adjacent."
- **nightly** - The cutting edge. Updated automatically from main with the latest changes. Might have shiny new features, might have shiny new bugs. Generally works but don't be surprised if something catches fire.
- **experimental** - Where ideas go to become features or crash spectacularly. This is where new features are tested, questionable UI decisions are made, and code is written that might make future-me weep. Expect bugs. Expect weirdness. Expect things to break in creative new ways.
> "This seemed like a great idea at 3am" - every experimental commit ever
**Workflow:** Features → experimental → testing → nightly → main (eventually)
If you're testing this project, grab builds from nightly for the latest features, or main for something more stable. Experimental is where I break things on purpose to see what sticks.
---
## Quick Start
### Windows
1. Double-click `launcher.bat` (or run `.\launcher.ps1` in PowerShell)
2. Select option **2** to run Setup on first use
3. Select option **1** to Start Dashboard
### **Windows**
1. Run `launcher.bat` or `.\launcher.ps1`
2. Select **[2] Run Setup** on first launch
3. Select **[1] Start Dashboard** to open the UI
> **Tip**: The launcher automatically finds your SSH key from the Dune Awakening server installation at `%LOCALAPPDATA%\DuneAwakeningServer\sshKey`.
>
> **Note**: If PowerShell blocks running scripts due to execution policy (`launcher.ps1` won't run), use `launcher.bat` instead — it bypasses the restriction automatically. You can also run `powershell.exe -ExecutionPolicy Bypass -File .\launcher.ps1` directly from Command Prompt.
> The launcher automatically finds your Dune Awakening SSH key and politely ignores PowerShell’s opinions about execution policies.
### **Linux / macOS**
```bash
chmod +x start.sh
./start.sh
```
---
## Features
- **Map Features**: Interactive maps with real-world coordinate calibration for Hagga Basin and The Deep Desert. Default view centers on Hagga Basin at 15% zoom. Zoom range: 15%–100%.
- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. Rich detail view with vitals, currency, inventory, vehicles, buildings, landclaims, specialization, keystones, and faction reputation.
- **Chat Logs**: Parsed from text-router pod logs with channel filtering and auto-refresh.
- **Director Controls**: Live battlegroup stats, world state management, and server transfer controls.
- **File Browser**: Secure SSH-based file browser for server configuration and logs.
- **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser.
- **Admin Tools**: Ban management, IP detection, kick/unban functionality, player history, item/currency/vitals editing, and raw SQL query interface.
- **Firewall Security**: Block unauthenticated game server ports (File Browser, Director) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page.
- **Vehicles & Buildings**: Track owned vehicles, modules, and player structures.
- **Auto-Update**: Background checker polls GitHub for new commits. Safe file replacement preserves your settings, logs, and SSH keys. One-click update from the dashboard.
- **Remote Access**: Built-in support for HTTPS and binding to `0.0.0.0` for secure remote management.
- **Let's Encrypt**: Optionally set up publicly trusted SSL certs during setup with automatic renewal via certbot.
- **Settings Migration**: Automatically adds new configuration options to `settings.yaml` when updating, so you never miss a feature.
- **Cross-Platform**: Works on Windows (`.bat`/`.ps1`) and Linux/macOS (`.sh`).
- **Organized Logging**: Launcher logs are automatically categorized by type (SSH, K8s, database, etc.) with sensitive data redacted. Old logs are cleaned up after 30 days, oversized files are truncated at 10 MB.
- **Debug Mode**: Enable verbose debug logging via launcher (option 6) or the Server page UI. Logs detailed information about all HTTP requests/responses, SSH commands, database queries, Kubernetes operations, and service health checks. All sensitive data (passwords, tokens, keys) is automatically sanitized before writing to log files. Debug logs are written to `logs/debug.log`.
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
- **Chat Logs** with channel filtering and auto-refresh
- **Director Tools** (battlegroups, world state, transfers)
- **SSH File Browser** + **in-browser shell**
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
- **Nav Layout** — switch between horizontal and vertical sidebar; persists preference; auto-enables sidebar on mobile
- **Firewall Hardening** via iptables
- **Auto‑Update** with safe file replacement
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
- **Cross‑Platform Launchers**
- **Organized Logging** with automatic cleanup and redaction
- **Debug Mode** with full SSH/K8s tracing
- **SSH Key Rotation** — scan all key locations and sync the newest key
- **Backup & Restore** — full server snapshots (game DB, K8s resources, RMQ config, dashboard schema) with optional AES-256 encryption and password protection
- **Scheduled Backups** — configurable interval or day/time-based scheduling with automatic retention cleanup
## License
This project is **Source Available** under the [Dune Dashboard Source License (DDSL)](LICENSE).
- Source code is available for inspection and security auditing.
- **No redistribution** (modified or unmodified).
- **No claiming of credit** or authorship.
- Personal, non-commercial use only.
## Requirements
- Python 3.8+
- Node.js 18+ (for frontend development/build)
- OpenSSH client
- `kubectl` access to the Dune: Awakening Kubernetes cluster
- SSH access to the game server VM
## Setup
### Windows
1. **Run the Launcher**
```powershell
.\launcher.ps1
```
2. **Choose an option from the menu:**
- **[1] Start Dashboard** — Launch the dashboard web interface
- **[2] Run Setup** — Configure the dashboard for the first time (or reconfigure)
- **[3] Run Diagnostics** — Check your system for common issues
- **[4] Install CA Certificate** — Install the local CA into Windows Trusted Root store (removes browser SSL warnings)
- **[5] Clean & Reinstall CA Certificate** — Remove old CA certificates and install a fresh one
- **[6] Start Dashboard (Debug Mode)** — Launch with full debug logging enabled
- **[7] Start New Dashboard (React + ChakraUI)** — Launch the modern React dashboard with auto-installed dependencies
- **[8] Reset to Factory Defaults** — Wipe all data (settings, logs, certs, cache, node_modules) and return to a clean state
- **[9] Repair Game Database** — Fix dashboard schema ownership so game updates won't break servers
- **[10] Clean up Old Dashboard Schema** — Drop the old `dashboard` schema from the game database (after migration)
- **[Q] Quit** — Exit the launcher
3. **First-time Setup** (option 2)
The setup script will:
- Install Python dependencies
- Find your SSH key (automatically detects the Dune Awakening server key)
- Auto-detect your VM IP from Hyper-V or SSH history
- Generate SSL certificates (local CA or Let's Encrypt)
- Configure firewall rules and security hardening
During setup you'll be prompted for:
- **VM External IP** — the IP you SSH into (e.g., `<YOUR_VM_IP>`)
- **Host External IP** — the public IP for SSL certificate SANs (e.g., `<YOUR_HOST_IP>`)
- **Let's Encrypt** — optionally set up a publicly trusted SSL cert with auto-renewal via certbot
- **Firewall rules** — only prompted if no `DuneDashboard` rule exists yet
> **Note**: Setup will retry SSH up to 12 times (60 seconds) to accommodate fresh VM boot times. If SSH isn't ready yet, you can still continue and enter your Kubernetes namespace manually.
4. **Start Dashboard** (option 1)
The launcher will:
- Establish an SSH tunnel to your game server
- Set up database and Director port-forwards via kubectl
- Scale up the BGD deployment if needed
- Launch the dashboard web interface
### Linux / macOS
1. **Start Dashboard**
```bash
chmod +x start.sh
./start.sh
```
The launcher will prompt you to run setup if `settings.yaml` is missing.
## Configuration
All settings are stored in `settings.yaml`. The setup script generates this automatically. Key settings include:
- `server.host`: Game server VM IP
- `server.ssh_key`: Path to your SSH private key
- `kubernetes.namespace`: Auto-detected K8s namespace
- `database.port`: Local port for database tunnel
- `auth.username` / `auth.password_hash`: Dashboard login credentials (password_hash is Argon2 hash, generated by setup)
### Remote Access
During setup, answer **y** to "Enable remote access?" to:
- Bind to `0.0.0.0` (accessible from other machines)
- Auto-generate SSL certificates for HTTPS
- Enable secure remote connections via `https://YOUR_IP:5050`
**Firewall rules** are created automatically during setup. On subsequent starts, `start.ps1`/`start.sh` will only prompt if the `DuneDashboard` rule is missing.
You can also manually edit `settings.yaml` later:
```yaml
dashboard:
host: 0.0.0.0
ssl_cert: ssl/cert.pem
ssl_key: ssl/key.pem
```
### Let's Encrypt (Publicly Trusted Certs)
During setup, answer **y** when asked to enable Let's Encrypt. The setup script will:
1. Install `certbot` (tries `winget`, `pip`, and `python -m` fallbacks on Windows)
2. Run `certbot certonly --standalone` to validate your domain
3. Configure auto-renewal via Windows Scheduled Task or Linux cron
4. Point the dashboard to the Let's Encrypt cert paths
> **Note**: Port 80 must be free during certbot validation. The dashboard's HTTP redirect server will release port 80 temporarily for this.
### Local CA Utilities (Windows)
Available from the launcher menu (`.\launcher.ps1`):
- **Option 4: Install CA Certificate** — Installs the local CA (`ssl/ca.pem`) into Windows Trusted Root store. Run as Administrator. Removes browser warnings.
- **Option 5: Clean & Reinstall CA Certificate** — Removes all old Dune Dashboard CA certificates from Windows Trusted Root store and installs a fresh one. Use if you have duplicate or expired CA certificates.
### SSL Configuration
The dashboard supports both self-signed and CA-signed certificates.
**Local CA (auto-generated during setup):**
- A local Certificate Authority (`ssl/ca.pem`) is created during setup
- Server certificates are signed by this CA
- Server certs include SAN for the server IP + `127.0.0.1` + `localhost`
- Valid for 365 days
**Remove browser warnings (Windows):**
1. Run `.\launcher.ps1` and select option **4** (Install CA Certificate)
2. Restart your browser
3. Access `https://localhost:5050` — no more warnings
**Remove browser warnings (Linux):**
```bash
sudo cp ssl/ca.pem /usr/local/share/ca-certificates/dune-dashboard-ca.crt
sudo update-ca-certificates
```
**Let's Encrypt or custom CA:**
```yaml
dashboard:
host: 0.0.0.0
ssl_cert: /etc/letsencrypt/live/yourdomain.com/fullchain.pem
ssl_key: /etc/letsencrypt/live/yourdomain.com/privkey.pem
```
When SSL is enabled:
- Session cookies are marked `Secure` (sent only over HTTPS)
- HTTP-to-HTTPS redirect runs on port+1 (e.g., `http://localhost:5051` → `https://localhost:5050`)
- Certificate expiry is checked at startup (warning if < 30 days)
**Regenerate certificates:**
Delete `ssl/cert.pem`, `ssl/key.pem`, and `ssl/ca*.pem`, then re-run setup.
### Auto-Renewal
SSL certificates are automatically regenerated when they approach expiry:
- A background thread checks the certificate every 24 hours (configurable)
- If the certificate expires within 30 days (configurable), a new one is generated
- The server does **not** need to restart — Flask-SocketIO picks up the new cert on the next connection
- Configure thresholds in `settings.yaml` under the `ssl:` section
---
## Project Structure
```
DuneDashboard/
├── backend/ # New Flask backend (API + services)
│ ├── app/
│ │ ├── routes/ # HTTP route handlers (API, auth, health, server, files, director, chat)
│ │ ├── services/ # Business logic (DB, SSH, K8s, BGD, RMQ, player, economy, guild, world, etc.)
│ │ ├── models/ # Pydantic v2 models
│ │ ├── websocket/ # Socket.IO shell handler
│ │ ├── config.py # Settings loader
│ │ └── factory.py # App factory (services, blueprints, security)
│ ├── run.py # Entry point
│ └── requirements.txt # Python dependencies
│
├── frontend/ # New React SPA (Vite + TypeScript + Tailwind)
│ ├── src/
│ │ ├── components/ # Pages (overview, players, guilds, vehicles, buildings, map, accounts, server, admin, chat, shell, files, director, settings)
│ │ ├── api/ # Axios client
│ │ ├── stores/ # React Context (app state, auth, theme)
│ │ ├── hooks/ # Custom hooks (realtime, debounce)
│ │ └── styles/ # Tailwind + 14 Dune themes
│ ├── index.html
│ ├── package.json
│ ├── vite.config.ts
│ └── tsconfig.json
│
├── app/ # Legacy Flask/Jinja2 dashboard (untouched, still functional)
│ ├── routes/
│ ├── services/
│ ├── utils/
│ └── websocket/
├── templates/ # Legacy Jinja2 HTML templates
├── static/ # Legacy CSS and frontend assets
├── scripts/ # Pre-flight utilities (db_check.py)
├── launcher.ps1 # Unified launcher (setup, start, diagnostics, CA tools)
├── start.sh # Linux/macOS entry point
├── settings.yaml # Configuration (gitignored)
└── settings.yaml.example # Reference configuration
├── app/ # Flask/Jinja2 dashboard
├── launcher.ps1 # Windows launcher
├── start.sh # Linux/macOS launcher
└── settings.yaml # Generated config (gitignored)
```
> **Note**: The legacy `app/`, `templates/`, and `static/` directories remain untouched and functional. The new system lives in `backend/` and `frontend/`. Both can coexist during migration.
---
## Architecture
## Requirements
### Frontend
- **React 18** with TypeScript
- **Vite** for fast builds and HMR
- **Tailwind CSS** for styling with 14 Dune house themes
- **SWR** for server state caching and revalidation
- **Axios** for HTTP requests with 401 redirect handling
- **Socket.IO Client** for the remote terminal
- **xterm.js** for the in-browser shell
- Python 3.8+
- OpenSSH client
- `kubectl` access to your Dune Awakening cluster
- SSH access to the game server VM
### Backend
- **Flask 3** with Blueprint-based routing
- **Pydantic v2** for request/response validation
- **psycopg3** with connection pooling for PostgreSQL
- **Flask-SocketIO** for the interactive shell
- **Flask-Login** for session-based authentication (Argon2 password hashing)
- **Flask-Limiter** for rate limiting
- **SSE (Server-Sent Events)** for real-time updates (battlegroup, chat, metrics)
---
### Services
- `DatabaseService` — psycopg3 pool, stored procedure executor, audit table DDL
- `SSHService` — paramiko SSH client for tunneling and remote commands
- `K8sService` — kubectl-over-SSH for pod/deployment management
- `BgDirectorService` — HTTP client for the Battlegroup Director API
- `RmqAdminService` — RabbitMQ Management HTTP API client
- `RmqGameService` — RabbitMQ Game HTTP API client (broadcasts, chat intercept)
- `RealtimeService` — SSE broadcaster with background polling loops
- `PlayerService` / `EconomyService` / `GuildService` / `WorldService` / `ProgressionService` / `CharacterService` — DB-function-only domain services
- `AuditService` — persistent PostgreSQL audit logging
- `ChatService` — chat history + pod log catch-up
## Security
## Security Notes
- `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
- Never commit `settings.yaml` to version control.
- SSH keys are copied to `%TEMP%` with restricted permissions during startup.
- All database queries use parameterized statements to prevent SQL injection.
- Dashboard authentication is required by default.
- Raw SQL query endpoint (`/api/query`) is **read-only SELECT** — INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/GRANT/TRUNCATE are blocked.
- All mutations are audited to PostgreSQL.
- CSP, HSTS, X-Frame-Options, and other security headers are enforced in production mode.
> “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.
## Logging
The launcher automatically organizes and sanitizes logs to protect sensitive information.
### Log Categories
```
logs/
├── launcher/
│ ├── general/ # General launcher events
│ ├── ssh/ # SSH tunnel and connection logs
│ ├── k8s/ # Kubernetes operations
│ ├── database/ # Database port-forward and connections
│ ├── dashboard/ # Dashboard startup and runtime
│ ├── setup/ # Setup wizard logs
│ └── diagnostics/ # Diagnostic tool output
├── app.log # Python application log (rotating, 10 MB max, 5 backups)
└── audit.log # Security audit log (rotating, 10 MB max, 5 backups)
```
### Sensitive Data Redaction
All launcher log files are automatically sanitized before writing. The following are redacted:
- IP addresses → `<IP_REDACTED>`
- JWT tokens → `<JWT_REDACTED>`
- Base64 secrets → `<BASE64_REDACTED>`
- SSH key paths → `<SSH_KEY_PATH_REDACTED>`
- K8s namespaces → `<NAMESPACE_REDACTED>`
- Host IDs → `<HOST_ID_REDACTED>`
- Passwords/tokens → `<REDACTED>`
- Funcom IDs → `<FUNCOM_ID_REDACTED>`
Console output is **not** sanitized so you can see full details during operation.
### Automatic Cleanup
- Log files older than **30 days** are deleted
- Files exceeding **10 MB** are truncated (keeps last 5000 lines)
- Empty category directories are removed
- Cleanup runs automatically on every launcher start
---
## Development
### Frontend Development
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 # Vite dev server with API proxy to localhost:5050
npm run build # Production build to frontend/dist/
```
---
### Backend Development
## Branching Strategy
```bash
cd backend
pip install -r requirements.txt
python run.py # Or: flask --app run:app run
```
- **main** — stable-ish beta
- **nightly** — latest features
- **experimental** — where chaos becomes innovation
### Themes
> “This seemed like a great idea at 3am.” — every experimental commit ever
The dashboard supports 14 Dune house themes. Switch via the theme picker in the top-right nav bar:
Classic Dune, House Atreides, House Harkonnen, Fremen, Bene Gesserit, Spacing Guild, Emperor, House Corrino, Mentat, Sardaukar, Bene Tleilax, House Ordos, Ix, CHOAM.
---
## License
Source Available under the **Dune Dashboard Source License (DDSL)**
- No redistribution
- No claiming authorship
- Personal, non-commercial use only
- Basically: look, learn, enjoy — just don’t repost it as “Dune Dashboard Pro Deluxe Edition”.
Themes are implemented via CSS custom properties (`var(--primary)`, `var(--bg)`, etc.) and switched by setting `data-theme` on the `<html>` element.
+1
View File
@@ -46,6 +46,7 @@ DEFAULTS = {
'battlegroup_script': '/home/dune/.dune/bin/battlegroup',
},
'director': {
'host': '',
'port': 32479,
},
'filebrowser': {
+52 -10
View File
@@ -6,6 +6,7 @@ import time
import logging
import logging.handlers
import threading
from datetime import datetime
from flask import Flask, request, g
from flask_login import current_user
from flask_socketio import SocketIO
@@ -25,6 +26,7 @@ from app.services.admin import AdminService
from app.services.updater import UpdateService
from app.services.director import DirectorService
from app.services.rmq import RmqService
from app.services.backup import BackupService
from app.utils.cache import MultiCache
from app.routes.main import register_routes
from app.routes.api import register_api_routes
@@ -236,6 +238,16 @@ def create_app(settings_path=None):
)
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
# Auto-detect namespace if not set in config — must run before
# services that consume the namespace (director, backup, etc.).
if settings['kubernetes']['namespace'] == '':
try:
k8s_service.auto_detect_namespace()
if k8s_service.namespace:
settings['kubernetes']['namespace'] = k8s_service.namespace
except Exception as e:
logging.warning(f"Could not auto-detect K8s namespace: {e}")
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
player_svc = PlayerService(db_service, dash_db=dash_db_service)
@@ -247,7 +259,7 @@ def create_app(settings_path=None):
updater_svc = UpdateService(base_dir)
logging.debug("UpdateService initialized")
director_svc = DirectorService(
host='127.0.0.1',
host=settings.get('director', {}).get('host') or '127.0.0.1',
node_port=settings.get('director', {}).get('port', 32479),
k8s_service=k8s_service,
ssh_service=ssh_service,
@@ -262,6 +274,9 @@ 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)}")
backup_svc = BackupService(ssh_service, k8s_service, rmq_svc, settings)
logging.debug("BackupService initialized")
services = {
'db': db_service,
'dash_db': dash_db_service,
@@ -275,6 +290,7 @@ def create_app(settings_path=None):
'updater': updater_svc,
'director': director_svc,
'rmq': rmq_svc,
'backup': backup_svc,
}
logging.debug(f"All services registered: {list(services.keys())}")
@@ -313,14 +329,6 @@ def create_app(settings_path=None):
def cleanup_db(exc):
pass
if settings['kubernetes']['namespace'] == '':
try:
k8s_service.auto_detect_namespace()
if k8s_service.namespace:
settings['kubernetes']['namespace'] = k8s_service.namespace
except Exception as e:
logging.warning(f"Could not auto-detect K8s namespace: {e}")
# Check SSL certificate expiry and start background monitor
if ssl_enabled:
try:
@@ -422,7 +430,7 @@ def create_app(settings_path=None):
def _connection_monitor():
"""Background thread that monitors and auto-reconnects services."""
import time
check_interval = 60 # Check every 60 seconds
check_interval = 30 # Check every 30 seconds
consecutive_failures = 0
max_consecutive_failures = 5
last_ssh_ok = True # Track SSH state to detect reconnection
@@ -496,6 +504,40 @@ def create_app(settings_path=None):
except Exception as 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}')
app.dune_settings = settings
app.dune_services = services
+179
View File
@@ -38,6 +38,7 @@ def register_api_routes(app, services, settings):
chat_svc = services['chat']
admin_svc = services['admin']
vehicle_svc = services['vehicle']
backup_svc = services.get('backup')
audit_svc = services.get('audit')
# Get or create rate limiter - use existing one from factory if available
@@ -1114,6 +1115,79 @@ def register_api_routes(app, services, settings):
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
# Pod actions (list, logs, delete, describe)
@app.route('/api/pods')
@auth_req
def api_pods_list():
try:
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(
f'sudo kubectl get pods -n {ns} -o custom-columns=NAME:.metadata.name,ROLE:.metadata.labels.role,STATUS:.status.phase')
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list pods'})
pods = []
for line in (out or '').strip().split('\n')[1:]:
parts = line.split(None, 2)
if len(parts) >= 3:
pods.append({
'name': parts[0],
'role': parts[1] if parts[1] != '<none>' else '',
'status': parts[2],
})
return jsonify({'success': True, 'pods': pods})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pod/logs', methods=['POST'])
@auth_req
def api_pod_logs():
try:
data = request.get_json(force=True) or {}
pod = data.get('pod', '').strip()
if not pod:
return jsonify({'success': False, 'error': 'pod name required'})
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(
f'sudo kubectl logs -n {ns} {pod} --tail=300 2>/dev/null || echo "NO_LOGS"', timeout=15)
if rc != 0 and 'NO_LOGS' not in (out or ''):
return jsonify({'success': False, 'error': err or 'Failed to get logs'})
logs = (out or '').replace('NO_LOGS\n', '').replace('NO_LOGS', '')
return jsonify({'success': True, 'logs': logs, 'pod': pod})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pod/delete', methods=['POST'])
@auth_req
def api_pod_delete():
try:
data = request.get_json(force=True) or {}
pod = data.get('pod', '').strip()
if not pod:
return jsonify({'success': False, 'error': 'pod name required'})
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(f'sudo kubectl delete pod -n {ns} {pod} --wait=false', timeout=30)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to delete pod'})
return jsonify({'success': True, 'message': f'Pod {pod} deleted (will be recreated by its controller)'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pod/describe', methods=['POST'])
@auth_req
def api_pod_describe():
try:
data = request.get_json(force=True) or {}
pod = data.get('pod', '').strip()
if not pod:
return jsonify({'success': False, 'error': 'pod name required'})
ns = settings['kubernetes']['namespace']
out, err, rc = ssh.run(f'sudo kubectl describe pod -n {ns} {pod}', timeout=30)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to describe pod'})
return jsonify({'success': True, 'describe': out or '', 'pod': pod})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
# Update management
@app.route('/api/update/status')
@auth_req
@@ -1981,3 +2055,108 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'SQL prefix not allowed'})
success, result = admin_svc.admin_db_execute(sql)
return jsonify({'success': success, 'result': result if success else str(result)})
# ── Backup Endpoints ──────────────────────────────────────────────
if backup_svc:
@app.route('/api/backup/list')
@auth_req
def api_backup_list():
return jsonify({'success': True, 'backups': backup_svc.list_backups()})
@app.route('/api/backup/create', methods=['POST'])
@auth_req
def api_backup_create():
data = request.get_json() or {}
password = data.get('password', '')
result = backup_svc.create_backup(password=password)
return jsonify(result)
@app.route('/api/backup/info', methods=['POST'])
@auth_req
def api_backup_info():
data = request.get_json() or {}
name = data.get('name', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
'backups', f'{name}.tar.gz')
info = backup_svc.get_backup_info(path)
return jsonify({'success': True, 'info': info})
@app.route('/api/backup/delete', methods=['POST'])
@auth_req
def api_backup_delete():
data = request.get_json() or {}
name = data.get('name', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
deleted = backup_svc.delete_backup(name)
return jsonify({'success': deleted})
@app.route('/api/backup/verify', methods=['POST'])
@auth_req
def api_backup_verify():
data = request.get_json() or {}
name = data.get('name', '')
password = data.get('password', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
result = backup_svc.verify_backup(name, password=password)
return jsonify(result)
@app.route('/api/backup/restore/preview', methods=['POST'])
@auth_req
def api_backup_restore_preview():
data = request.get_json() or {}
name = data.get('name', '')
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
result = backup_svc.restore_preview(name)
return jsonify(result)
@app.route('/api/backup/restore/test-connection', methods=['POST'])
@auth_req
def api_backup_test_connection():
result = backup_svc.test_connection()
return jsonify(result)
@app.route('/api/backup/restore/start', methods=['POST'])
@auth_req
def api_backup_restore_start():
data = request.get_json() or {}
name = data.get('name', '')
options = data.get('options', {})
if not name:
return jsonify({'success': False, 'error': 'Backup name required'})
result = backup_svc.start_restore(name, options)
return jsonify(result)
@app.route('/api/backup/restore/status', methods=['POST'])
@auth_req
def api_backup_restore_status():
data = request.get_json() or {}
restore_id = data.get('restore_id', '')
if not restore_id:
return jsonify({'success': False, 'error': 'Restore ID required'})
result = backup_svc.get_restore_status(restore_id)
return jsonify(result)
@app.route('/api/backup/schedule', methods=['GET'])
@auth_req
def api_backup_schedule_get():
return jsonify({'success': True, 'schedule': backup_svc.get_schedule()})
@app.route('/api/backup/schedule', methods=['POST'])
@auth_req
def api_backup_schedule_set():
data = request.get_json() or {}
result = backup_svc.update_schedule(data)
return jsonify({'success': True, 'schedule': result})
@app.route('/api/backup/run-scheduled', methods=['POST'])
@auth_req
def api_backup_run_scheduled():
result = backup_svc.run_scheduled_backup()
return jsonify(result)
+8 -1
View File
@@ -4,7 +4,7 @@ import json
import logging
from flask import Blueprint, render_template, request, jsonify
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.services.player import LIKE_PC
@@ -49,6 +49,7 @@ def register_routes(app, services, settings):
)
return dict(
nav_pages=NAV_PAGES,
nav_groups=NAV_GROUPS,
current_path=request.path if request else '/',
fmt_role=fmt_role,
conn_ok=conn_ok,
@@ -535,6 +536,12 @@ def register_routes(app, services, settings):
def admin_experimental():
return render_template('admin_experimental.html')
# Backup / Restore
@app.route('/backup')
@login_required
def backup_page():
return render_template('backup.html')
# Map - shows locations of players, vehicles, buildings
@app.route('/map')
@login_required
+809
View File
@@ -0,0 +1,809 @@
"""Backup service - backup creation, restore orchestration, backup management"""
import base64
import json
import logging
import os
import shlex
import shutil
import subprocess
import tarfile
import threading
import time
from datetime import datetime, timedelta
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
logger = logging.getLogger(__name__)
class BackupError(Exception):
pass
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:
cfg['password'] = data['password']
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.warning(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:
logger.warning(f'Could not read metadata from {path}: {e}')
return {}
def delete_backup(self, name):
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=''):
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 Exception as e:
return {'success': False, 'valid': False, 'error': str(e)}
# ── Restore Orchestration ─────────────────────────────────────────
def restore_preview(self, 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):
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()
r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > /tmp/restore-{backup_name}.tar.gz', 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:
r = ssh_cmd(
f'mkdir -p /tmp/restore-{backup_name} && '
f'cd /tmp/restore-{backup_name} && '
f'tar xzf /tmp/restore-{backup_name}.tar.gz --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']:
r = ssh_cmd(
f'sudo kubectl apply -n {ns} -f {d}/k8s-manifests/{fname} 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}'
r = ssh_cmd(
f'sudo kubectl apply -f {d}/k8s-manifests/battlegroup-crd.yaml', 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 {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 {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 /tmp/restore-{backup_name} && '
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 {ns} -l role=db -o name | head -1) && '
f'echo {shlex.quote(b64_sql)} | base64 -d | '
f'sudo kubectl exec -n {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 {ns} -l role=db -o name | head -1) && '
f'sudo kubectl exec -n {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:
r = ssh_cmd('hostname', timeout=10)
hostname = r.stdout.strip()
new_ip = opts['new_ip']
for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']:
full_name = f'{ns}-{deploy_suffix}'
ssh_cmd(
f'sudo kubectl set env deploy/{full_name} -n {ns} '
f'HOST_DATACENTER_ID={hostname} '
f'HOST_DATACENTER_IP_ADDRESS={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 {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()
for cmd in [
f'rabbitmqctl add_user dashboard_admin {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 {ns} {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}'
r = ssh_cmd(f'cat {d}/settings.yaml', 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 /tmp/restore-{backup_name} /tmp/restore-{backup_name}.tar.gz',
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()
+1 -1
View File
@@ -219,7 +219,7 @@ class DashboardDatabaseService:
for row in old_rows:
vals = [row[c] for c in cols]
self.execute(
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders}) ON CONFLICT DO NOTHING",
vals,
)
migrated = True
+66 -3
View File
@@ -2,6 +2,7 @@
import json
import logging
import urllib.error
import urllib.request
import configparser
import io
@@ -10,6 +11,9 @@ from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
# Internal port the BGD container listens on (used with service cluster IP)
_BGD_CONTAINER_PORT = 11717
class DirectorService:
"""Service for interacting with the game server's battlegroup director.
@@ -27,6 +31,7 @@ class DirectorService:
self.k8s = k8s_service
self.ssh = ssh_service
self.namespace = namespace
self._bgd_svc_url = None # cached cluster URL for SSH fallback
resource_prefix = namespace
for prefix in ['funcom-seabass-']:
if resource_prefix.startswith(prefix):
@@ -35,9 +40,31 @@ class DirectorService:
self.resource_prefix = resource_prefix
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
def _resolve_bgd_svc_url(self):
"""Find the BGD Service cluster IP via kubectl (stable across pod restarts)."""
out, err, rc = self.k8s.run('get svc -o name', timeout=10)
if rc != 0:
return None
for line in (out or '').split('\n'):
line = line.strip()
if 'bgd-svc' in line:
svc_name = line.split('/')[-1]
ip_out, ip_err, ip_rc = self.k8s.run(
f'get svc {svc_name} -o jsonpath={{.spec.clusterIP}}', timeout=10)
if ip_rc == 0 and ip_out:
ip = ip_out.strip()
logger.info("Director: resolved BGD svc cluster IP %s", ip)
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
return None
def _request(self, path: str, method: str = 'GET', data: Any = None,
timeout: int = 15, raw_data: bool = False) -> str:
"""Execute HTTP request to director service via NodePort.
"""Execute HTTP request to director service.
Tries local HTTP first (SSH tunnel + kubectl port-forward).
Falls back to SSH + wget directly to the BGD service cluster IP,
which survives server restarts without needing a port-forward.
Args:
path: URL path (e.g., '/v0/battlegroup').
@@ -67,8 +94,44 @@ class DirectorService:
method=method
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode()
# Try local HTTP first (SSH tunnel + kubectl port-forward on VM)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode()
except (urllib.error.URLError, ConnectionError, OSError) as e:
logger.debug("Director local HTTP failed, trying SSH fallback: %s", e)
# Fallback: SSH to BGD service cluster IP (always works, no tunnel needed)
if not self._bgd_svc_url:
self._bgd_svc_url = self._resolve_bgd_svc_url()
if self._bgd_svc_url:
svc_url = f"{self._bgd_svc_url}{path}"
logger.debug("Director SSH fallback: %s %s", method, svc_url)
if method == 'GET':
out, err, rc = self.ssh.run(f'wget -qO- {svc_url}', timeout=timeout)
else:
body_bytes = None
if raw_data and isinstance(data, str):
body_bytes = data.encode()
elif data is not None:
body_bytes = json.dumps(data).encode()
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
self.ssh.run(f'echo {body_b64} | base64 -d > {tmp}', timeout=5)
try:
out, err, rc = self.ssh.run(
f'wget -qO- --post-file={tmp} '
f'--header="Content-Type: application/json" {svc_url}',
timeout=timeout)
finally:
self.ssh.run(f'rm -f {tmp}', timeout=5)
if rc == 0 and out:
return out
logger.warning("Director SSH fallback failed (rc=%d): %s",
rc, err[:100] if err else 'none')
self._bgd_svc_url = None # stale cache, re-resolve next time
raise ConnectionError("Connection refused: Director unreachable via local HTTP or SSH fallback")
# ── Director API methods ──────────────────────────────────────────
+27 -3
View File
@@ -60,6 +60,23 @@ class K8sService:
return []
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):
out, err, rc = self.run('top nodes')
if rc == 0 and out.strip():
@@ -67,10 +84,17 @@ class K8sService:
if len(lines) >= 2:
parts = lines[1].split()
if len(parts) >= 4:
cpu_pct_str = parts[2]
mem_str = parts[3]
mem_pct_str = parts[4] if len(parts) >= 5 else ''
return {
'cpu': parts[2],
'memory': parts[3],
'cpu_pct': parts[1]
'cpu': cpu_pct_str,
'memory': mem_str,
'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 {}
+10
View File
@@ -7,6 +7,8 @@ import paramiko
from app.utils.ssh_key import resolve_ssh_key
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
KEEPALIVE_INTERVAL = 15
logger = logging.getLogger(__name__)
@@ -37,6 +39,11 @@ class SSHService:
transport = self._client.get_transport()
if transport and transport.is_active():
return self._client
logger.debug("SSH: closing stale client before reconnect")
try:
self._client.close()
except Exception:
pass
self._client = None
client = paramiko.SSHClient()
@@ -56,6 +63,9 @@ class SSHService:
try:
client.connect(**connect_kwargs)
logger.debug("SSH connection established to %s@%s", self.user, self.host)
transport = client.get_transport()
if transport:
transport.set_keepalive(KEEPALIVE_INTERVAL)
except paramiko.AuthenticationException:
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
raise
+26
View File
@@ -82,4 +82,30 @@ NAV_PAGES = [
('/buildings', 'Buildings'),
('/map', 'Map'),
('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]
NAV_GROUPS = [
('/', 'Overview'),
('Server', [
('/server', 'Server'),
('/director', 'Director'),
('/shell', 'Shell'),
('/files', 'Files'),
]),
('Players', [
('/players', 'Players'),
('/vehicles', 'Vehicles'),
('/guilds', 'Guilds'),
('/buildings', 'Buildings'),
]),
('World', [
('/events', 'Events'),
('/chat', 'Chat'),
('/map', 'Map'),
]),
('System', [
('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]),
]
-1
View File
@@ -1 +0,0 @@
# Backend package init.
-287
View File
@@ -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")