Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a490786827 | ||
|
|
91c7abc771 | ||
|
|
97cdbd3027 | ||
|
|
715845751b | ||
|
|
bd9bd452c9 | ||
|
|
bb5065dd59 | ||
|
|
f48a09e8d3 | ||
|
|
9c61e198fa | ||
|
|
ce241a283d | ||
|
|
91944a0213 |
No files matched your search
+14
-2
@@ -38,6 +38,7 @@ config_local.py
|
||||
dune-tunnel-key
|
||||
dune-awakening-server-sshKey
|
||||
internal-scripts/ssh/sshKey
|
||||
internal-scripts/ssh/known_hosts
|
||||
|
||||
# SSL Certificates
|
||||
ssl/
|
||||
@@ -73,6 +74,8 @@ logs/
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
*.sqlite3
|
||||
instance/
|
||||
|
||||
@@ -80,6 +83,9 @@ instance/
|
||||
*.tmp
|
||||
*.bak
|
||||
|
||||
# Pre-change rollback backups (restorable copies of edited files)
|
||||
rollback/
|
||||
|
||||
# PowerShell profiles
|
||||
Microsoft.PowerShell_profile.ps1
|
||||
|
||||
@@ -103,8 +109,8 @@ find_*.py
|
||||
AI_DOCS/
|
||||
AI_FULL_PROJECT_ANALYSIS_MODE/
|
||||
|
||||
# Version file (generated dynamically)
|
||||
VERSION
|
||||
# VERSION is committed: it is the dashboard's version source of truth
|
||||
# (e.g. 0.7.5-experimental). The updater reads it, never ignores it.
|
||||
|
||||
# Security scripts (contain VM-specific configs)
|
||||
scripts/
|
||||
@@ -122,3 +128,9 @@ node_modules/
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
pnpm-lock.yaml
|
||||
|
||||
# Local browser automation artifacts
|
||||
.playwright-mcp/
|
||||
|
||||
# Shared AI docs copies (top-level AI_DOCS has its own repo)
|
||||
AI_DOCS/
|
||||
@@ -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 comprehensive web-based management dashboard for Dune: Awakening private servers.”
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
@@ -26,26 +24,18 @@ chmod +x start.sh
|
||||
## Features
|
||||
|
||||
- **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
|
||||
- **Director Tools** (battlegroups, world state, transfers)
|
||||
- **SSH File Browser** + **in-browser shell**
|
||||
- **SSH File Browser** (jailed to allowed directories) + **in-browser shell**
|
||||
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
|
||||
- **Nav Layout** — switch between horizontal and vertical sidebar; persists preference; auto-enables sidebar on mobile
|
||||
- **Backup & Restore** — encrypted full-server snapshots with scheduled backups and retention cleanup
|
||||
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources with verification
|
||||
- **Firewall Hardening** via iptables
|
||||
- **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
|
||||
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources (secret, YAML, BattleGroup CR) with verification
|
||||
- **Graceful Shutdown / Restart** — in-game countdown warnings, then `battlegroup stop` / `restart`, with cancel notices
|
||||
- **Custom Notifications** — instant in-game broadcasts, plus scheduled one-shot/daily/weekly/monthly messages
|
||||
- **Scheduled Restarts** — daily/weekly/monthly/one-shot with the same countdown, enable/disable/clear without losing settings
|
||||
- **Battlegroup Update Guard** — update refuses while game servers are online
|
||||
- **Jailed File Browser** — restricted to configured directories with symlink-aware checks
|
||||
- **HTTPS + Remote Access** (self-signed or Let's Encrypt)
|
||||
- **Cross-Platform Launchers** (Windows + Linux/macOS, incl. debug mode and SSH key rotation)
|
||||
|
||||
---
|
||||
|
||||
@@ -70,36 +60,12 @@ DuneDashboard/
|
||||
|
||||
---
|
||||
|
||||
## Security
|
||||
|
||||
- `settings.yaml` is never committed
|
||||
- SSH keys stored with restricted permissions
|
||||
- All DB queries parameterized
|
||||
- No raw SQL console — the old experimental query/execute endpoints were removed entirely
|
||||
- Shell parameters validated and quoted throughout
|
||||
- File browser jailed to allowed directories
|
||||
- All mutations audited
|
||||
- CSP, HSTS, X‑Frame‑Options enforced in production
|
||||
|
||||
> Because letting users run `DROP TABLE` from a web UI is how horror stories begin — so that UI no longer exists.
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
||||
|
||||
---
|
||||
|
||||
## Branching Strategy
|
||||
|
||||
- **main** — stable-ish beta
|
||||
- **experimental** — where chaos becomes innovation
|
||||
|
||||
> “This seemed like a great idea at 3am.” — every experimental commit ever
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Source Available under the **Dune Dashboard Source License (DDSL)**
|
||||
|
||||
+29
-3
@@ -55,6 +55,16 @@ def create_app(settings_path=None):
|
||||
app.config['WTF_CSRF_ENABLED'] = True
|
||||
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.init_app(app)
|
||||
|
||||
@@ -335,8 +345,8 @@ def create_app(settings_path=None):
|
||||
register_api_routes(app, services, settings)
|
||||
register_websocket_handlers(socketio, settings)
|
||||
|
||||
# Start update checker (disabled — being reworked)
|
||||
# updater_svc.start_checker()
|
||||
# Background update check (channel-aware releases; installing is manual only)
|
||||
updater_svc.start_checker()
|
||||
|
||||
@app.teardown_appcontext
|
||||
def cleanup_db(exc):
|
||||
@@ -447,6 +457,8 @@ def create_app(settings_path=None):
|
||||
consecutive_failures = 0
|
||||
max_consecutive_failures = 5
|
||||
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:
|
||||
time.sleep(check_interval)
|
||||
@@ -489,7 +501,14 @@ def create_app(settings_path=None):
|
||||
logging.debug("Connection monitor: All services healthy")
|
||||
else:
|
||||
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
|
||||
if not ssh_ok and ssh_svc:
|
||||
@@ -609,6 +628,13 @@ def _setup_logging(settings):
|
||||
root_logger.addHandler(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_handler = logging.handlers.RotatingFileHandler(
|
||||
'logs/audit.log',
|
||||
|
||||
+108
-35
@@ -43,6 +43,27 @@ def fb_within_roots(canonical, roots):
|
||||
return False
|
||||
|
||||
|
||||
def fb_resolve_canonical(raw, lexical, run_fn, timeout=10):
|
||||
"""Pick a canonical path using the best realpath the target supports.
|
||||
|
||||
- GNU coreutils: ``realpath -m`` works, even for not-yet-existing paths.
|
||||
- BusyBox (e.g. Alpine): no ``-m`` flag, so it is retried as plain
|
||||
``realpath`` (works for existing paths, resolves symlinks).
|
||||
- Otherwise the lexical path is used (``..`` already collapsed, but
|
||||
symlinks stay unresolved).
|
||||
|
||||
``run_fn(command, timeout)`` executes in the target context and returns
|
||||
``(stdout, stderr, returncode)``. Returns the canonical path string.
|
||||
"""
|
||||
out, err, rc = run_fn(f'realpath -m -- {quote_remote(raw)}', timeout)
|
||||
if rc == 0 and (out or '').strip():
|
||||
return (out or '').strip().split('\n')[0].strip()
|
||||
out, err, rc = run_fn(f'realpath -- {quote_remote(raw)}', timeout)
|
||||
if rc == 0 and (out or '').strip():
|
||||
return (out or '').strip().split('\n')[0].strip()
|
||||
return lexical
|
||||
|
||||
|
||||
def register_api_routes(app, services, settings):
|
||||
db = services['db']
|
||||
ssh = services['ssh']
|
||||
@@ -116,8 +137,17 @@ def register_api_routes(app, services, settings):
|
||||
def server_metrics():
|
||||
metrics = k8s.get_node_metrics()
|
||||
if metrics:
|
||||
return jsonify(metrics)
|
||||
return jsonify({'cpu': 'N/A', 'memory': 'N/A'})
|
||||
pass
|
||||
else:
|
||||
metrics = {'cpu': 'N/A', 'memory': 'N/A'}
|
||||
try:
|
||||
row = db.query(
|
||||
"SELECT COUNT(*) AS c FROM dune.player_state "
|
||||
"WHERE online_status::text = 'Online'", one=True) or {}
|
||||
metrics['online'] = int(row.get('c') or 0)
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(metrics)
|
||||
|
||||
# Battlegroup
|
||||
@app.route('/server/battlegroup/status')
|
||||
@@ -1041,14 +1071,15 @@ def register_api_routes(app, services, settings):
|
||||
import posixpath
|
||||
roots = _fb_allowed_roots()
|
||||
lexical = posixpath.normpath(raw)
|
||||
out, err, rc = _fb_exec(f'realpath -m -- {quote_remote(raw)}', pod_name, timeout=timeout)
|
||||
if rc == 0 and (out or '').strip():
|
||||
canonical = (out or '').strip().split('\n')[0].strip()
|
||||
else:
|
||||
# realpath unavailable in this context: fall back to the lexical
|
||||
# path (still blocks '..' escapes; symlinks stay unresolved).
|
||||
logger.warning('File browser: realpath unavailable, using lexical path check')
|
||||
canonical = lexical
|
||||
|
||||
def _run(command, timeout):
|
||||
# Probe commands are expected to fail on minimal toolchains
|
||||
# (e.g. BusyBox realpath without -m): keep them out of the logs.
|
||||
return _fb_exec(command, pod_name, timeout=timeout, quiet=True)
|
||||
|
||||
canonical = fb_resolve_canonical(raw, lexical, _run, timeout)
|
||||
if canonical == lexical:
|
||||
logger.debug('File browser: using lexical path check (no realpath -m support)')
|
||||
if not fb_within_roots(canonical, roots):
|
||||
return '', 'Invalid path: outside allowed directories'
|
||||
return canonical, ''
|
||||
@@ -1083,10 +1114,10 @@ def register_api_routes(app, services, settings):
|
||||
return str(e)
|
||||
return ''
|
||||
|
||||
def _fb_exec(command, pod_name=None, timeout=10):
|
||||
def _fb_exec(command, pod_name=None, timeout=10, quiet=False):
|
||||
"""Execute a command on the VM host or in a K8s pod."""
|
||||
if pod_name in _FB_VM_PODS:
|
||||
return k8s.ssh.run(command, timeout=timeout)
|
||||
return k8s.ssh.run(command, timeout=timeout, quiet=quiet)
|
||||
pod = pod_name or _get_fb_pod()
|
||||
if not pod:
|
||||
return '', 'No pod specified or found', 1
|
||||
@@ -1094,7 +1125,7 @@ def register_api_routes(app, services, settings):
|
||||
if err:
|
||||
return '', f'Invalid pod name: {err}', 1
|
||||
full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}'
|
||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
||||
return k8s.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
|
||||
|
||||
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
||||
"""Write a file to the pod filesystem."""
|
||||
@@ -1484,17 +1515,16 @@ def register_api_routes(app, services, settings):
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
# Update management
|
||||
# Update management (channel-aware, releases-based, never downgrades)
|
||||
@app.route('/api/update/status')
|
||||
@auth_req
|
||||
def api_update_status():
|
||||
updater = services.get('updater')
|
||||
if not updater:
|
||||
return jsonify({'available': False})
|
||||
return jsonify({
|
||||
'available': updater.update_available,
|
||||
'status': updater.update_status,
|
||||
})
|
||||
status = updater.status()
|
||||
status['success'] = True
|
||||
return jsonify(status)
|
||||
|
||||
@app.route('/api/update/apply', methods=['POST'])
|
||||
@auth_req
|
||||
@@ -1502,19 +1532,14 @@ def register_api_routes(app, services, settings):
|
||||
updater = services.get('updater')
|
||||
if not updater:
|
||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||
success, message = updater.apply_update()
|
||||
data = request.get_json() or {}
|
||||
success, message = updater.apply_update(data.get('version'))
|
||||
if audit_svc and success:
|
||||
audit_svc.log('dashboard_update',
|
||||
{'version': data.get('version') or 'latest'},
|
||||
user='admin', severity='warning')
|
||||
return jsonify({'success': success, 'message': message})
|
||||
|
||||
@app.route('/api/update/test', methods=['POST'])
|
||||
@auth_req
|
||||
def api_update_test():
|
||||
"""Force show update banner for testing."""
|
||||
updater = services.get('updater')
|
||||
if updater:
|
||||
updater._update_available = True
|
||||
return jsonify({'success': True, 'message': 'Update banner triggered'})
|
||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||
|
||||
@app.route('/api/update/check', methods=['POST'])
|
||||
@auth_req
|
||||
def api_update_check():
|
||||
@@ -1523,12 +1548,60 @@ def register_api_routes(app, services, settings):
|
||||
if not updater:
|
||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||
updater.check_for_updates()
|
||||
return jsonify({
|
||||
'available': updater.update_available,
|
||||
'status': updater.update_status,
|
||||
'local_version': updater._current_sha,
|
||||
'remote_version': updater._latest_sha,
|
||||
})
|
||||
status = updater.status()
|
||||
status['success'] = True
|
||||
return jsonify(status)
|
||||
|
||||
@app.route('/api/update/preview', methods=['POST'])
|
||||
@auth_req
|
||||
def api_update_preview():
|
||||
"""Set an in-memory preview version to test the banner (never installable)."""
|
||||
updater = services.get('updater')
|
||||
if not updater:
|
||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||
data = request.get_json() or {}
|
||||
try:
|
||||
preview = updater.set_preview(data.get('version'), data.get('notes'))
|
||||
except ValueError as e:
|
||||
return jsonify({'success': False, 'error': str(e)})
|
||||
return jsonify({'success': True, 'preview': preview})
|
||||
|
||||
@app.route('/api/update/preview', methods=['DELETE'])
|
||||
@auth_req
|
||||
def api_update_preview_clear():
|
||||
updater = services.get('updater')
|
||||
if not updater:
|
||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||
updater.clear_preview()
|
||||
return jsonify({'success': True})
|
||||
|
||||
@app.route('/api/update/silence', methods=['POST'])
|
||||
@auth_req
|
||||
def api_update_silence():
|
||||
"""Silence a version, toggle permanent mute, or clear all silence."""
|
||||
updater = services.get('updater')
|
||||
if not updater:
|
||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||
data = request.get_json() or {}
|
||||
action = str(data.get('action') or '').strip().lower()
|
||||
try:
|
||||
if action == 'silence':
|
||||
state = updater.silence_version(data.get('version'))
|
||||
elif action == 'unsilence':
|
||||
state = updater.unsilence_version(data.get('version'))
|
||||
elif action == 'mute':
|
||||
state = updater.set_silence_all(True)
|
||||
elif action == 'unmute':
|
||||
state = updater.set_silence_all(False)
|
||||
elif action == 'clear':
|
||||
state = updater.clear_silence()
|
||||
else:
|
||||
return jsonify({'success': False,
|
||||
'error': 'Unknown action (silence/unsilence/mute/unmute/clear)'})
|
||||
except Exception as e:
|
||||
logger.error(f'Update silence failed: {e}')
|
||||
return jsonify({'success': False, 'error': 'Could not save silence setting'})
|
||||
return jsonify({'success': True, 'silence': state})
|
||||
|
||||
# Audit logs
|
||||
from app.services.audit import AuditService
|
||||
|
||||
+93
-15
@@ -363,27 +363,105 @@ def register_routes(app, services, settings):
|
||||
@app.route('/events')
|
||||
@login_required
|
||||
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 = []
|
||||
event_logs = []
|
||||
|
||||
def safe_query(table, cols, order_col, limit):
|
||||
try:
|
||||
return db.query(f"SELECT {cols} FROM {table} ORDER BY {order_col} DESC LIMIT {limit}") or []
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching {table}: {e}")
|
||||
return []
|
||||
maps = []
|
||||
counts_24h = {}
|
||||
total_24h = 0
|
||||
solaris = []
|
||||
|
||||
try:
|
||||
game_events = safe_query("dune.game_events", "*", "universe_time", 50)
|
||||
except Exception:
|
||||
pass
|
||||
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:
|
||||
logger.error(f"Error fetching event maps: {e}")
|
||||
if map_filter != 'all' and map_filter not in maps:
|
||||
map_filter = 'all'
|
||||
|
||||
try:
|
||||
event_logs = safe_query("dune.event_log", "*", "event_time", 100)
|
||||
except Exception:
|
||||
pass
|
||||
stat_rows = db.query(
|
||||
"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
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching event stats: {e}")
|
||||
|
||||
return render_template('events.html', game_events=game_events, event_logs=event_logs)
|
||||
try:
|
||||
conditions = []
|
||||
params = []
|
||||
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 = []
|
||||
|
||||
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
|
||||
@app.route('/chat')
|
||||
|
||||
@@ -388,7 +388,7 @@ class BackupService:
|
||||
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}')
|
||||
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():
|
||||
@@ -396,7 +396,9 @@ class BackupService:
|
||||
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}')
|
||||
# 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):
|
||||
|
||||
@@ -99,12 +99,14 @@ class ChatService:
|
||||
return 0
|
||||
|
||||
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
|
||||
|
||||
pod_name = self.k8s.get_text_router_pod()
|
||||
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
|
||||
|
||||
logger.debug(f"Attempting to catch up chat from pod: {pod_name}")
|
||||
|
||||
+51
-43
@@ -19,22 +19,26 @@ class DatabaseService:
|
||||
def init_pool(self):
|
||||
if self.pool is None:
|
||||
# Retry up to 10 times with 2s delays (20s total) to handle startup race conditions
|
||||
for attempt in range(10):
|
||||
try:
|
||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||
minconn=self.min_conn,
|
||||
maxconn=self.max_conn,
|
||||
**self.db_config
|
||||
)
|
||||
logger.info("Database connection pool initialized")
|
||||
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
|
||||
try:
|
||||
for attempt in range(10):
|
||||
try:
|
||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||
minconn=self.min_conn,
|
||||
maxconn=self.max_conn,
|
||||
**self.db_config
|
||||
)
|
||||
logger.info("Database connection pool initialized")
|
||||
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
|
||||
except KeyboardInterrupt:
|
||||
print("\n Stopped during database startup.")
|
||||
raise SystemExit(0)
|
||||
return self.pool
|
||||
|
||||
def get_connection(self):
|
||||
@@ -155,33 +159,37 @@ class DashboardDatabaseService:
|
||||
def init_pool(self):
|
||||
if self.pool is not None:
|
||||
return self.pool
|
||||
for attempt in range(10):
|
||||
try:
|
||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||
minconn=self.min_conn,
|
||||
maxconn=self.max_conn,
|
||||
**self.db_config
|
||||
)
|
||||
logger.info("Dashboard database pool initialized")
|
||||
return self.pool
|
||||
except psycopg2.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
|
||||
try:
|
||||
for attempt in range(10):
|
||||
try:
|
||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||
minconn=self.min_conn,
|
||||
maxconn=self.max_conn,
|
||||
**self.db_config
|
||||
)
|
||||
logger.info("Dashboard database pool initialized")
|
||||
return self.pool
|
||||
except psycopg2.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
|
||||
except KeyboardInterrupt:
|
||||
print("\n Stopped during database startup.")
|
||||
raise SystemExit(0)
|
||||
return self.pool
|
||||
|
||||
def _ensure_database(self):
|
||||
|
||||
@@ -256,8 +256,15 @@ class DirectorService:
|
||||
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||
name = self._map_to_scale_name(map_name)
|
||||
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:
|
||||
# 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 json.loads(cm_out)
|
||||
|
||||
|
||||
+2
-2
@@ -11,10 +11,10 @@ class K8sService:
|
||||
self.ssh = ssh_service
|
||||
self.namespace = namespace
|
||||
|
||||
def run(self, kubectl_command, timeout=30):
|
||||
def run(self, kubectl_command, timeout=30, quiet=False):
|
||||
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
|
||||
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
|
||||
if rc != 0:
|
||||
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
||||
|
||||
@@ -199,7 +199,7 @@ class PlayerService:
|
||||
def get_player_detail(self, player_id):
|
||||
player = self.db.query("""
|
||||
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,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
||||
ps.online_status::text as online_status,
|
||||
@@ -235,7 +235,8 @@ class PlayerService:
|
||||
FROM dune.actors WHERE id = %s
|
||||
""", [state_pawn_id], one=True) or {}
|
||||
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 {}
|
||||
|
||||
def get_player_guild(self, player_controller_id):
|
||||
|
||||
+43
-6
@@ -1,6 +1,7 @@
|
||||
"""SSH service - remote command execution via paramiko."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import paramiko
|
||||
|
||||
@@ -12,6 +13,20 @@ KEEPALIVE_INTERVAL = 15
|
||||
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:
|
||||
"""SSH service using paramiko for connection reuse.
|
||||
|
||||
@@ -47,6 +62,13 @@ class SSHService:
|
||||
self._client = None
|
||||
|
||||
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())
|
||||
logger.debug("SSH host key verification policy set to AutoAddPolicy")
|
||||
|
||||
@@ -63,6 +85,12 @@ class SSHService:
|
||||
try:
|
||||
client.connect(**connect_kwargs)
|
||||
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)
|
||||
@@ -79,19 +107,22 @@ class SSHService:
|
||||
self._client = client
|
||||
return self._client
|
||||
|
||||
def run(self, command, timeout=30):
|
||||
def run(self, command, timeout=30, quiet=False):
|
||||
"""Execute a remote command via SSH.
|
||||
|
||||
Args:
|
||||
command: The shell command to execute.
|
||||
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:
|
||||
Tuple of (stdout, stderr, return_code).
|
||||
"""
|
||||
cmd_display = command[:150] + '...' if len(command) > 150 else command
|
||||
logger.debug(f"SSH executing: {cmd_display}")
|
||||
|
||||
|
||||
try:
|
||||
client = self._get_client()
|
||||
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
|
||||
@@ -99,17 +130,23 @@ class SSHService:
|
||||
out = stdout.read().decode('utf-8', errors='replace')
|
||||
err = stderr.read().decode('utf-8', errors='replace')
|
||||
rc = stdout.channel.recv_exit_status()
|
||||
|
||||
|
||||
# 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)}")
|
||||
if err and rc != 0:
|
||||
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||
if quiet:
|
||||
logger.debug(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||
else:
|
||||
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||
if out:
|
||||
logger.debug(f"SSH stdout preview: {out[:200]}")
|
||||
|
||||
|
||||
if rc != 0:
|
||||
cmd_short = command[:80] + '...' if len(command) > 80 else command
|
||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||
if quiet:
|
||||
logger.debug("SSH command rc=%d (quiet): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||
else:
|
||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||
return out, err, rc
|
||||
except paramiko.SSHException as e:
|
||||
logger.error(f"SSH command error ({self.host}): {e}")
|
||||
|
||||
+332
-91
@@ -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 re
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
@@ -11,7 +23,7 @@ import urllib.request
|
||||
import zipfile
|
||||
import tempfile
|
||||
import subprocess
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -28,40 +40,155 @@ PROTECTED_PATHS = {
|
||||
'.env',
|
||||
}
|
||||
|
||||
# File extensions that are always safe to overwrite
|
||||
SAFE_EXTENSIONS = {'.py', '.html', '.css', '.js', '.sh', '.ps1', '.md', '.txt', '.yaml', '.yml', '.json', '.ini', '.cfg'}
|
||||
_VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$")
|
||||
_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:
|
||||
def __init__(self, project_root):
|
||||
self.project_root = project_root
|
||||
self._update_available = False
|
||||
self._latest_sha = None
|
||||
self._current_sha = None
|
||||
self._current_version = self._read_local_version()
|
||||
self._channel = channel_of(self._current_version)
|
||||
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._check_interval = 1800 # 30 minutes
|
||||
self._update_in_progress = False
|
||||
self._update_status = None
|
||||
self._current_branch = self._detect_branch()
|
||||
self._preview = None # {'version', 'notes'} - in-memory test helper
|
||||
|
||||
def _detect_branch(self):
|
||||
"""Detect the current git branch or ZIP branch from folder name."""
|
||||
# ── version / channel ────────────────────────────────────────────
|
||||
|
||||
def _read_local_version(self):
|
||||
try:
|
||||
branch = subprocess.check_output(
|
||||
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
|
||||
cwd=self.project_root, stderr=subprocess.DEVNULL
|
||||
).decode().strip()
|
||||
if branch:
|
||||
return branch
|
||||
with open(os.path.join(self.project_root, 'VERSION')) as f:
|
||||
version = f.read().strip().replace('\r', '').replace('\n', '')
|
||||
if parse_version(version):
|
||||
return version
|
||||
except Exception:
|
||||
pass
|
||||
return '0.0.0'
|
||||
|
||||
folder_name = os.path.basename(self.project_root).lower()
|
||||
if 'nightly' in folder_name:
|
||||
return 'nightly'
|
||||
if 'beta' in folder_name:
|
||||
return 'beta'
|
||||
return 'main'
|
||||
@property
|
||||
def current_version(self):
|
||||
return self._current_version
|
||||
|
||||
@property
|
||||
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):
|
||||
"""Start background update checker thread."""
|
||||
@@ -78,107 +205,219 @@ class UpdateService:
|
||||
logger.debug(f"Update check failed: {e}")
|
||||
time.sleep(self._check_interval)
|
||||
|
||||
def _fetch_releases(self):
|
||||
"""All releases from GitHub (follows pagination)."""
|
||||
releases = []
|
||||
url = f"{GITHUB_API}/releases?per_page=100"
|
||||
while url:
|
||||
req = urllib.request.Request(url)
|
||||
req.add_header('Accept', 'application/vnd.github.v3+json')
|
||||
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
releases.extend(json.loads(resp.read().decode()))
|
||||
url = self._next_page(resp.headers.get('Link', ''))
|
||||
return releases
|
||||
|
||||
@staticmethod
|
||||
def _next_page(link_header):
|
||||
for part in (link_header or '').split(','):
|
||||
segments = part.split(';')
|
||||
if len(segments) == 2 and 'rel="next"' in segments[1]:
|
||||
return segments[0].strip().strip('<>')
|
||||
return ''
|
||||
|
||||
@staticmethod
|
||||
def _collect_channel(releases, channel):
|
||||
"""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):
|
||||
"""Check GitHub for new commits."""
|
||||
"""Refresh latest-version info for our channel (and the other one)."""
|
||||
try:
|
||||
branch = self._current_branch
|
||||
git_dir = os.path.join(self.project_root, '.git')
|
||||
if os.path.isdir(git_dir):
|
||||
# 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('User-Agent', 'DuneDashboard-UpdateChecker')
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
data = json.loads(resp.read().decode())
|
||||
remote_sha = data['sha'][:7]
|
||||
|
||||
version_file = os.path.join(self.project_root, 'VERSION')
|
||||
if os.path.exists(version_file):
|
||||
with open(version_file) as f:
|
||||
local_sha = f.read().strip().replace('\r', '').replace('\n', '')[:7]
|
||||
else:
|
||||
# First run after ZIP download: record current version
|
||||
local_sha = remote_sha
|
||||
with open(version_file, 'w') as f:
|
||||
f.write(remote_sha + '\n')
|
||||
|
||||
self._latest_sha = remote_sha
|
||||
self._current_sha = local_sha
|
||||
self._update_available = remote_sha != local_sha and remote_sha != ""
|
||||
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()
|
||||
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:
|
||||
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
|
||||
def update_available(self):
|
||||
return self._update_available
|
||||
status = self.status()
|
||||
return status['available'] or status['preview'] is not None
|
||||
|
||||
@property
|
||||
def update_status(self):
|
||||
return self._update_status
|
||||
|
||||
def apply_update(self):
|
||||
"""Download and apply the latest update."""
|
||||
# ── apply ────────────────────────────────────────────────────────
|
||||
|
||||
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:
|
||||
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_status = "Downloading update..."
|
||||
self._update_status = f"Downloading {target}..."
|
||||
|
||||
try:
|
||||
# Download latest zip from the detected branch
|
||||
branch = self._current_branch
|
||||
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/{branch}.zip"
|
||||
req = urllib.request.Request(zip_url)
|
||||
req = urllib.request.Request(entry['zipball_url'])
|
||||
req.add_header('Accept', 'application/vnd.github.v3+json')
|
||||
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()
|
||||
if not zip_data.startswith(b'PK\x03\x04'):
|
||||
raise ValueError("Downloaded file is not a zip archive")
|
||||
|
||||
self._update_status = "Extracting update..."
|
||||
|
||||
# Extract to temp directory
|
||||
temp_dir = tempfile.mkdtemp(prefix='dune_update_')
|
||||
zip_path = os.path.join(temp_dir, 'update.zip')
|
||||
with open(zip_path, 'wb') as f:
|
||||
f.write(zip_data)
|
||||
|
||||
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)
|
||||
|
||||
# Find the extracted folder (e.g., dune-dashboard-main)
|
||||
extracted = [d for d in os.listdir(temp_dir) if os.path.isdir(os.path.join(temp_dir, d)) and d != '__MACOSX']
|
||||
extracted = [d for d in os.listdir(temp_dir)
|
||||
if os.path.isdir(os.path.join(temp_dir, d))
|
||||
and d != '__MACOSX']
|
||||
if not extracted:
|
||||
return False, "Failed to extract update"
|
||||
|
||||
source_dir = os.path.join(temp_dir, extracted[0])
|
||||
|
||||
# Create backup
|
||||
backup_dir = os.path.join(self.project_root, 'backups', f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
|
||||
backup_dir = os.path.join(
|
||||
self.project_root, 'backups',
|
||||
f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
|
||||
os.makedirs(backup_dir, exist_ok=True)
|
||||
|
||||
# Copy files, skipping protected paths
|
||||
self._update_status = "Applying files..."
|
||||
files_updated = 0
|
||||
for root, dirs, files in os.walk(source_dir):
|
||||
rel_root = os.path.relpath(root, source_dir)
|
||||
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)):
|
||||
continue
|
||||
|
||||
@@ -190,11 +429,9 @@ class UpdateService:
|
||||
src_file = os.path.join(root, file)
|
||||
dst_file = os.path.join(target_root, file)
|
||||
|
||||
# Skip protected files
|
||||
if file in PROTECTED_PATHS:
|
||||
continue
|
||||
|
||||
# Backup existing file if it exists
|
||||
if os.path.exists(dst_file):
|
||||
backup_file = os.path.join(backup_dir, rel_root, file)
|
||||
os.makedirs(os.path.dirname(backup_file), exist_ok=True)
|
||||
@@ -203,18 +440,15 @@ class UpdateService:
|
||||
shutil.copy2(src_file, dst_file)
|
||||
files_updated += 1
|
||||
|
||||
# Cleanup temp
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
# Update VERSION file to match new version
|
||||
version_file = os.path.join(self.project_root, 'VERSION')
|
||||
with open(version_file, 'w') as f:
|
||||
f.write(self._latest_sha + '\n')
|
||||
with open(os.path.join(self.project_root, 'VERSION'), 'w') as f:
|
||||
f.write(target + '\n')
|
||||
|
||||
self._current_version = target
|
||||
self._channel = channel_of(target)
|
||||
self._update_status = f"Update applied! {files_updated} files updated. Restarting..."
|
||||
self._update_available = False
|
||||
|
||||
# Restart the application
|
||||
self._restart_app()
|
||||
|
||||
return True, f"Update applied successfully ({files_updated} files)"
|
||||
@@ -226,13 +460,20 @@ class UpdateService:
|
||||
return False, str(e)
|
||||
|
||||
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:
|
||||
if os.name == 'nt':
|
||||
launcher = os.path.join(self.project_root, 'launcher.ps1')
|
||||
if os.path.exists(launcher):
|
||||
subprocess.Popen(
|
||||
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', launcher],
|
||||
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', launcher, '-AutoStart'],
|
||||
creationflags=subprocess.CREATE_NEW_CONSOLE
|
||||
)
|
||||
else:
|
||||
@@ -240,7 +481,7 @@ class UpdateService:
|
||||
else:
|
||||
launcher = os.path.join(self.project_root, 'start.sh')
|
||||
if os.path.exists(launcher):
|
||||
subprocess.Popen(['bash', launcher], start_new_session=True)
|
||||
subprocess.Popen(['bash', launcher, '--auto-start'], start_new_session=True)
|
||||
else:
|
||||
subprocess.Popen([sys.executable, os.path.join(self.project_root, 'run.py')], start_new_session=True)
|
||||
os._exit(0)
|
||||
|
||||
@@ -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
|
||||
@@ -69,7 +69,12 @@ def start_watchdog(host, port, use_ssl):
|
||||
failures = 0
|
||||
continue
|
||||
failures += 1
|
||||
logger.warning(f'Watchdog: self-check failed ({failures}/{failures_needed})')
|
||||
# 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 '
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
# This script handles both setup and starting the dashboard.
|
||||
# Run this script and choose what you want to do.
|
||||
|
||||
# -AutoStart skips the menu and starts the dashboard straight away
|
||||
# (used after self-updates so the panel comes back up unattended).
|
||||
param([switch]$AutoStart)
|
||||
|
||||
$ErrorActionPreference = "Continue"
|
||||
|
||||
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
@@ -2819,6 +2823,11 @@ function Rotate-SSHKey {
|
||||
|
||||
Show-Banner
|
||||
|
||||
if ($AutoStart) {
|
||||
Start-Dashboard
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
while ($true) {
|
||||
Show-Menu
|
||||
$choice = Read-Host " Enter your choice"
|
||||
|
||||
@@ -30,6 +30,23 @@ if __name__ == '__main__':
|
||||
cert_path = str(ssl_cert).strip("'\"")
|
||||
key_path = str(ssl_key).strip("'\"")
|
||||
if os.path.exists(cert_path) and os.path.exists(key_path):
|
||||
try:
|
||||
with open(cert_path, 'rb'):
|
||||
pass
|
||||
with open(key_path, 'rb'):
|
||||
pass
|
||||
except OSError:
|
||||
print(f"\n [ERROR] Cannot read SSL files (permission denied):")
|
||||
print(f" [ERROR] {cert_path}")
|
||||
print(f" [ERROR] {key_path}")
|
||||
print(f" [ERROR] The dashboard runs as '{os.environ.get('USERNAME', 'unknown')}'")
|
||||
print(" [ERROR] but these files are only readable by an Administrator.")
|
||||
print(" [ERROR] Fix with ONE of:")
|
||||
print(" [ERROR] 1. Run the launcher as Administrator (right-click -> Run as administrator)")
|
||||
print(" [ERROR] 2. Grant yourself read access, e.g. in an elevated terminal:")
|
||||
print(f' [ERROR] icacls "{cert_path}" /grant "%USERNAME%:(R)"')
|
||||
print(f' [ERROR] icacls "{key_path}" /grant "%USERNAME%:(R)"\n')
|
||||
sys.exit(1)
|
||||
ssl_context = (cert_path, key_path)
|
||||
protocol = "https"
|
||||
else:
|
||||
@@ -101,6 +118,18 @@ if __name__ == '__main__':
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
def handle_error(self, request, client_address):
|
||||
# Scanners constantly connect and vanish mid-request. A reset
|
||||
# or broken pipe on an already-dead socket is routine noise:
|
||||
# debug-log it instead of dumping a traceback on the console.
|
||||
exc = sys.exc_info()[1]
|
||||
if isinstance(exc, (ConnectionResetError, BrokenPipeError)):
|
||||
logging.getLogger(__name__).debug(
|
||||
"Redirect: %s disconnected mid-request",
|
||||
client_address[0] if client_address else '?')
|
||||
return
|
||||
super().handle_error(request, client_address)
|
||||
|
||||
# Try configured redirect port first, fall back to dashboard port+1.
|
||||
# Try 0.0.0.0 first (all interfaces), fall back to 127.0.0.1 (localhost only)
|
||||
http_port = None
|
||||
@@ -147,26 +176,24 @@ if __name__ == '__main__':
|
||||
# Socket.IO keeps working (threading mode = HTTP long-polling, which
|
||||
# runs on any WSGI server).
|
||||
try:
|
||||
from cheroot import wsgi as cheroot_wsgi
|
||||
import cheroot
|
||||
from app.utils.http_server import build_server
|
||||
except ImportError:
|
||||
logging.getLogger(__name__).warning(
|
||||
"cheroot not installed - falling back to dev server "
|
||||
"(no connection timeouts)")
|
||||
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
||||
else:
|
||||
server = cheroot_wsgi.Server(
|
||||
(host, port), app,
|
||||
numthreads=16,
|
||||
request_queue_size=128,
|
||||
timeout=60,
|
||||
accepted_queue_size=128,
|
||||
accepted_queue_timeout=10,
|
||||
)
|
||||
if ssl_context:
|
||||
from cheroot.ssl.builtin import BuiltinSSLAdapter
|
||||
server.ssl_adapter = BuiltinSSLAdapter(cert_path, key_path)
|
||||
print(f" Server: cheroot (16 threads, 60s socket timeout, TLS on)")
|
||||
else:
|
||||
print(f" Server: cheroot (16 threads, 60s socket timeout)")
|
||||
try:
|
||||
if ssl_context:
|
||||
server = build_server(host, port, app, cert_path, key_path)
|
||||
print(f" Server: cheroot (16 threads, 60s socket timeout, TLS on)")
|
||||
else:
|
||||
server = build_server(host, port, app)
|
||||
print(f" Server: cheroot (16 threads, 60s socket timeout)")
|
||||
except OSError as e:
|
||||
print(f"\n [ERROR] Could not start TLS server: {e}")
|
||||
print(" [ERROR] If this is a permission error, run the launcher as Administrator once,\n")
|
||||
sys.exit(1)
|
||||
print(f" Watchdog: enabled (exit code 42 triggers launcher restart)\n")
|
||||
server.start()
|
||||
@@ -1040,6 +1040,13 @@ rotate_ssh_key() {
|
||||
|
||||
# ── Main Loop ───────────────────────────────────────────────────────────
|
||||
|
||||
# --auto-start skips the menu and starts the dashboard straight away
|
||||
# (used after self-updates so the panel comes back up unattended).
|
||||
if [ "$1" = "--auto-start" ] || [ "$1" = "--autostart" ]; then
|
||||
start_dashboard
|
||||
exit $?
|
||||
fi
|
||||
|
||||
show_banner
|
||||
|
||||
while true; do
|
||||
|
||||
@@ -1141,6 +1141,11 @@ td a:hover { text-decoration: underline; }
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modal-wide {
|
||||
max-width: 900px;
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
.modal h3 {
|
||||
margin: 0 0 16px 0;
|
||||
font-size: 18px;
|
||||
@@ -1320,6 +1325,109 @@ body[data-nav-layout="vertical"] .site-footer {
|
||||
margin-left: 216px;
|
||||
}
|
||||
|
||||
/* Update widget: lives in the nav next to the theme button, styled like
|
||||
the theme dropdown (nav-bg surface, nav-text tones) in every theme. */
|
||||
.nav-tools { display: flex; align-items: center; gap: 2px; }
|
||||
.update-banner { display: none; position: relative; }
|
||||
.update-banner .ub-bellwrap { position: relative; display: inline-block; }
|
||||
.update-banner .ub-dot {
|
||||
position: absolute; top: 2px; right: 6px; width: 8px; height: 8px;
|
||||
border-radius: 50%; background: var(--warn);
|
||||
}
|
||||
.update-banner .ub-panel {
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
width: 320px;
|
||||
max-width: calc(100vw - 32px);
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
background: var(--nav-bg);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
||||
z-index: 1000;
|
||||
padding: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--nav-text);
|
||||
}
|
||||
.update-banner .ub-title { font-weight: 700; margin-bottom: 2px; color: #fff; }
|
||||
.update-banner .ub-sub { color: var(--nav-text); opacity: 0.75; font-size: 11px; margin-bottom: 6px; }
|
||||
.update-banner .ub-preview-tag {
|
||||
font-size: 10px; font-weight: 700; color: #fff; background: var(--warn);
|
||||
border-radius: 8px; padding: 0 6px; margin-left: 4px;
|
||||
}
|
||||
.update-banner .ub-notes { margin: 4px 0 6px; }
|
||||
.update-banner .ub-notes summary { cursor: pointer; font-size: 11px; color: var(--nav-text); opacity: 0.75; }
|
||||
.update-banner .ub-notes pre {
|
||||
white-space: pre-wrap; font-size: 11px; max-height: 160px; overflow-y: auto;
|
||||
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1);
|
||||
border-radius: 6px; padding: 8px; margin-top: 4px; color: var(--nav-text);
|
||||
}
|
||||
.update-banner .ub-actions { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; }
|
||||
.update-banner .ub-actions button {
|
||||
padding: 4px 12px; font-size: 12px; cursor: pointer;
|
||||
background: var(--primary); color: #fff; border: none; border-radius: 4px;
|
||||
}
|
||||
.update-banner .ub-actions button.ub-ghost {
|
||||
background: transparent; color: var(--nav-text);
|
||||
border: 1px solid rgba(255,255,255,0.25);
|
||||
}
|
||||
.update-banner .ub-mute { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--nav-text); opacity: 0.75; cursor: pointer; }
|
||||
.update-banner .ub-status { font-size: 11px; color: var(--nav-text); opacity: 0.75; margin-top: 4px; }
|
||||
.update-banner .ub-panel-head { font-weight: 700; margin-bottom: 6px; color: #fff; cursor: pointer; }
|
||||
.update-banner .ub-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-bottom: 6px; font-size: 12px; }
|
||||
.update-banner .ub-row select {
|
||||
padding: 4px 8px; font-size: 12px; color: var(--nav-text);
|
||||
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.15); border-radius: 4px;
|
||||
}
|
||||
.update-banner .ub-row button {
|
||||
padding: 4px 12px; font-size: 12px; cursor: pointer;
|
||||
background: transparent; color: var(--nav-text);
|
||||
border: 1px solid rgba(255,255,255,0.25); border-radius: 4px;
|
||||
}
|
||||
#ub-overlay {
|
||||
position: fixed; inset: 0; z-index: 2000;
|
||||
background: rgba(0,0,0,0.6);
|
||||
display: flex; align-items: center; justify-content: center; padding: 24px;
|
||||
}
|
||||
#ub-overlay .ub-overlay-box {
|
||||
max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto;
|
||||
background: var(--card-bg); color: var(--text);
|
||||
border-radius: 12px; box-shadow: var(--shadow); padding: 16px 18px;
|
||||
}
|
||||
#ub-overlay .ub-overlay-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
|
||||
#ub-overlay .ub-overlay-head button {
|
||||
padding: 4px 14px; font-size: 12px; cursor: pointer;
|
||||
background: var(--primary); color: #fff; border: none; border-radius: 4px;
|
||||
}
|
||||
#ub-overlay pre { white-space: pre-wrap; font-size: 12px; }
|
||||
|
||||
/* Vertical sidebar: tools row sits with the theme button; panel pops upward
|
||||
like the theme dropdown content does. */
|
||||
body[data-nav-layout="vertical"] .nav-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
border-top: 1px solid rgba(255,255,255,0.08);
|
||||
}
|
||||
body[data-nav-layout="vertical"] .nav-tools .theme-dropdown {
|
||||
padding: 0;
|
||||
border-top: none;
|
||||
}
|
||||
body[data-nav-layout="vertical"] .nav-tools .theme-btn {
|
||||
width: auto;
|
||||
}
|
||||
body[data-nav-layout="vertical"] .update-banner .ub-panel {
|
||||
top: auto;
|
||||
bottom: calc(100% + 8px);
|
||||
left: 0;
|
||||
right: auto;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
body[data-nav-layout="vertical"] {
|
||||
padding-left: 0;
|
||||
@@ -1341,3 +1449,115 @@ body[data-nav-layout="vertical"] .site-footer {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Native dropdowns: readable closed box in every theme. Several templates
|
||||
reference background vars that were never defined, so be explicit here.
|
||||
The color-scheme lines make the browser render the native options popup
|
||||
to match (otherwise it pops up white while inheriting light text). */
|
||||
select {
|
||||
background-color: var(--card-bg);
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
[data-theme$="-dark"] select {
|
||||
color-scheme: dark;
|
||||
}
|
||||
/* Explicit option colors: some browsers ignore color-scheme for the
|
||||
native popup, so paint the rows directly (light text on card bg). */
|
||||
[data-theme$="-dark"] select option {
|
||||
background-color: var(--card-bg);
|
||||
color: var(--text);
|
||||
}
|
||||
[data-theme]:not([data-theme$="-dark"]) select {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
/* Theme dropdown: invisible hover bridge so moving the mouse from the
|
||||
button down to the menu never drops hover (no more racing the cursor). */
|
||||
.theme-dropdown::after {
|
||||
content: '';
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 14px;
|
||||
}
|
||||
.theme-dropdown:hover::after {
|
||||
display: block;
|
||||
}
|
||||
body[data-nav-layout="vertical"] .theme-dropdown::after {
|
||||
top: auto;
|
||||
bottom: 100%;
|
||||
}
|
||||
|
||||
/* Nav live stats: CPU/RAM sparklines + online count. Compact strip in the
|
||||
horizontal top bar, stacked block in the vertical sidebar. */
|
||||
.nav-stats-h {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--nav-text);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.nav-stats-h .ns-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
.nav-stats-h canvas {
|
||||
width: 64px;
|
||||
height: 18px;
|
||||
}
|
||||
.nav-stats-h canvas,
|
||||
.nav-stats-v canvas {
|
||||
border: 1px solid rgba(128,128,128,0.35);
|
||||
border-radius: 3px;
|
||||
}
|
||||
.nav-stats-v {
|
||||
padding: 10px 8px;
|
||||
border-top: 1px solid rgba(255,255,255,0.08);
|
||||
font-size: 12px;
|
||||
color: var(--nav-text);
|
||||
}
|
||||
.nav-stats-v .ns-vrow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.nav-stats-v .ns-vrow:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.nav-stats-v .ns-vlabel {
|
||||
opacity: 0.7;
|
||||
font-size: 11px;
|
||||
}
|
||||
.nav-stats-v canvas {
|
||||
flex: 1;
|
||||
height: 28px;
|
||||
min-width: 0;
|
||||
}
|
||||
/* Graph rows share one grid template so both canvases are pixel-identical
|
||||
regardless of label/value text widths. */
|
||||
.nav-stats-v .ns-vgraph {
|
||||
display: grid;
|
||||
grid-template-columns: 34px 1fr 64px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.nav-stats-v .ns-vgraph canvas {
|
||||
width: 100%;
|
||||
}
|
||||
/* Fixed-width value column so CPU and RAM graphs align regardless of
|
||||
label length ("10%" vs "17947Mi"); values sit left, against the graphs. */
|
||||
.nav-stats-v .ns-vrow > span:last-child {
|
||||
min-width: 64px;
|
||||
text-align: left;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.nav-stats-v strong {
|
||||
font-size: 15px;
|
||||
color: #fff;
|
||||
}
|
||||
+17
-17
@@ -46,7 +46,7 @@
|
||||
<div class="card" style="margin-bottom:20px;">
|
||||
<div class="card-header">
|
||||
<span>Scheduled Backups</span>
|
||||
<button onclick="runScheduledNow()" id="run-sched-btn" style="padding:6px 16px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:13px;">Run Now</button>
|
||||
<button onclick="runScheduledNow()" id="run-sched-btn" style="padding:6px 16px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:13px;">Run Now</button>
|
||||
<button onclick="saveSchedule()" id="save-sched-btn" style="padding:6px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Save</button>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
@@ -72,13 +72,13 @@
|
||||
</div>
|
||||
<div id="sched-interval-fields" style="display:flex;gap:6px;align-items:center;">
|
||||
<input type="number" id="sched-days" value="1" min="0" max="365"
|
||||
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
<span style="font-size:12px;color:var(--text-muted);">days</span>
|
||||
<input type="number" id="sched-hours" value="0" min="0" max="23"
|
||||
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
<span style="font-size:12px;color:var(--text-muted);">hours</span>
|
||||
<input type="number" id="sched-mins" value="0" min="0" max="59"
|
||||
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
<span style="font-size:12px;color:var(--text-muted);">mins</span>
|
||||
</div>
|
||||
<div id="sched-schedule-fields" style="display:none;">
|
||||
@@ -110,11 +110,11 @@
|
||||
<div id="sched-times-list">
|
||||
<div style="display:flex;gap:6px;margin-bottom:4px;">
|
||||
<input type="time" class="sched-time" value="05:00"
|
||||
style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<button onclick="addSchedTime()" style="margin-top:4px;padding:4px 12px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:12px;">+ Add time</button>
|
||||
<button onclick="addSchedTime()" style="margin-top:4px;padding:4px 12px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:12px;">+ Add time</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -123,12 +123,12 @@
|
||||
<div style="margin-bottom:8px;">
|
||||
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Keep last N backups (0 = unlimited)</label>
|
||||
<input type="number" id="sched-keep" value="5" min="0" max="100"
|
||||
style="width:100%;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:100%;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
</div>
|
||||
<div style="margin-bottom:8px;">
|
||||
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Encryption password (leave blank for no encryption)</label>
|
||||
<input type="password" id="sched-password" placeholder="Leave blank to keep existing password"
|
||||
style="width:100%;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:100%;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -152,7 +152,7 @@
|
||||
<div class="step-content">
|
||||
<div class="step-title">Select Backup</div>
|
||||
<div class="step-body">
|
||||
<select id="restore-backup-select" style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;margin-bottom:8px;">
|
||||
<select id="restore-backup-select" style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;margin-bottom:8px;">
|
||||
<option value="">-- Select a backup --</option>
|
||||
</select>
|
||||
<div id="restore-preview" style="display:none;font-size:13px;color:var(--text-muted);"></div>
|
||||
@@ -201,15 +201,15 @@
|
||||
<div id="new-ip-group" style="margin:8px 0 0 24px;display:none;">
|
||||
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">New public IP for ping fix</label>
|
||||
<input type="text" id="restore-new-ip" placeholder="Same as VM IP if unchanged"
|
||||
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
</div>
|
||||
<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;cursor:pointer;">
|
||||
<input type="checkbox" id="opt-settings" checked> <span>Restore dashboard settings.yaml</span>
|
||||
</label>
|
||||
<div style="margin:12px 0 0 0;padding:10px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:4px;">
|
||||
<div style="margin:12px 0 0 0;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;">
|
||||
<div style="font-size:12px;color:var(--text-muted);margin-bottom:4px;">Backup password (if encrypted)</div>
|
||||
<input type="password" id="restore-password" placeholder="Leave blank if not password-protected"
|
||||
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -231,7 +231,7 @@
|
||||
<div id="progress-bar" style="height:100%;background:var(--accent);border-radius:4px;width:0%;transition:width 0.5s;"></div>
|
||||
</div>
|
||||
<div id="progress-steps" style="font-size:13px;"></div>
|
||||
<div id="restore-complete" style="display:none;margin-top:12px;padding:12px;background:var(--bg-card);border:1px solid var(--border);border-radius:4px;font-size:13px;"></div>
|
||||
<div id="restore-complete" style="display:none;margin-top:12px;padding:12px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;font-size:13px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -354,7 +354,7 @@ async function loadBackups() {
|
||||
container.innerHTML = '<p style="color:var(--text-muted);font-size:13px;">No backups found. Click "Create Backup" to create one.</p>';
|
||||
return;
|
||||
}
|
||||
let html = '<div style="background:var(--bg-card);border:1px solid var(--border);border-radius:4px;">';
|
||||
let html = '<div style="background:var(--card-bg);border:1px solid var(--border);border-radius:4px;">';
|
||||
html += '<div class="backup-row" style="font-weight:bold;color:var(--text-muted);font-size:12px;">';
|
||||
html += '<div class="backup-name">Name</div><div class="backup-date">Created</div><div class="backup-size">Size</div><div class="backup-actions">Actions</div></div>';
|
||||
for (const b of d.backups) {
|
||||
@@ -511,7 +511,7 @@ function addSchedTime() {
|
||||
const list = document.getElementById('sched-times-list');
|
||||
const div = document.createElement('div');
|
||||
div.style.cssText = 'display:flex;gap:6px;margin-bottom:4px;';
|
||||
div.innerHTML = '<input type="time" class="sched-time" value="05:00" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
|
||||
div.innerHTML = '<input type="time" class="sched-time" value="05:00" style="padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
|
||||
+ '<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">×</button>';
|
||||
list.appendChild(div);
|
||||
}
|
||||
@@ -550,7 +550,7 @@ async function loadSchedule() {
|
||||
times.forEach(t => {
|
||||
const div = document.createElement('div');
|
||||
div.style.cssText = 'display:flex;gap:6px;margin-bottom:4px;';
|
||||
div.innerHTML = '<input type="time" class="sched-time" value="' + t + '" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
|
||||
div.innerHTML = '<input type="time" class="sched-time" value="' + t + '" style="padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">'
|
||||
+ '<button onclick="removeSchedTime(this)" style="padding:6px 10px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">×</button>';
|
||||
list.appendChild(div);
|
||||
});
|
||||
@@ -649,7 +649,7 @@ document.getElementById('restore-backup-select').addEventListener('change', asyn
|
||||
const d = await r.json();
|
||||
if (d.success) {
|
||||
preview.style.display = 'block';
|
||||
let html = '<div style="margin-top:8px;padding:8px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:4px;">';
|
||||
let html = '<div style="margin-top:8px;padding:8px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;">';
|
||||
html += '<strong>Backup contents:</strong><br>';
|
||||
html += 'Created: ' + esc(d.created) + '<br>';
|
||||
const comps = d.components || [];
|
||||
|
||||
+446
-1
@@ -47,6 +47,17 @@
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="nav-stats-h" id="nav-stats-h" style="display:none;">
|
||||
<span class="ns-item"><span class="conn-dot" id="ns-dot-h"></span><strong id="ns-online-h">–</strong> online</span>
|
||||
<span class="ns-item">CPU <canvas id="ns-cpu-h" width="64" height="18"></canvas> <span id="ns-cpuv-h">–</span></span>
|
||||
<span class="ns-item">RAM <canvas id="ns-mem-h" width="64" height="18"></canvas> <span id="ns-memv-h">–</span></span>
|
||||
</div>
|
||||
<div class="nav-stats-v" id="nav-stats-v" style="display:none;">
|
||||
<div class="ns-vrow"><span class="conn-dot" id="ns-dot-v"></span><strong id="ns-online-v">–</strong><span class="ns-vlabel">players online</span></div>
|
||||
<div class="ns-vrow ns-vgraph"><span class="ns-vlabel">CPU</span><canvas id="ns-cpu-v" width="168" height="28"></canvas><span id="ns-cpuv-v">–</span></div>
|
||||
<div class="ns-vrow ns-vgraph"><span class="ns-vlabel">RAM</span><canvas id="ns-mem-v" width="168" height="28"></canvas><span id="ns-memv-v">–</span></div>
|
||||
</div>
|
||||
<div class="nav-tools">
|
||||
<div class="theme-dropdown">
|
||||
<button class="theme-btn" title="Theme">🎨</button>
|
||||
<div class="theme-dropdown-content">
|
||||
@@ -124,6 +135,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="update-banner" id="update-banner" style="display:none;"></div>
|
||||
</div>
|
||||
<span class="nav-conn">
|
||||
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
||||
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
||||
@@ -170,6 +183,7 @@
|
||||
const next = current === 'horizontal' ? 'vertical' : 'horizontal';
|
||||
body.setAttribute('data-nav-layout', next);
|
||||
localStorage.setItem('dune-nav-layout', next);
|
||||
if (typeof applyNavStatsLayout === 'function') applyNavStatsLayout();
|
||||
}
|
||||
|
||||
function initNavLayout() {
|
||||
@@ -187,12 +201,443 @@
|
||||
const isMobile = window.innerWidth <= 768;
|
||||
const current = document.body.getAttribute('data-nav-layout');
|
||||
if (isMobile && current !== 'vertical') {
|
||||
document.body.setAttribute('data-nav-layout', 'vertical');
|
||||
document.body.setAttribute('data-nav-layout', current);
|
||||
}
|
||||
if (typeof applyNavStatsLayout === 'function') applyNavStatsLayout();
|
||||
});
|
||||
|
||||
initTheme();
|
||||
initNavLayout();
|
||||
|
||||
// Update banner (channel-aware self updates)
|
||||
function escHtml(s) {
|
||||
return String(s == null ? '' : s)
|
||||
.replace(/&/g, '&').replace(/</g, '<')
|
||||
.replace(/>/g, '>').replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// Update widget: always-visible bell. Expands into a panel with a
|
||||
// channel dropdown, manual check, patch notes overlay, update and
|
||||
// silence controls. Auto-expands only for a new, non-silenced update.
|
||||
let ubData = null;
|
||||
let ubViewChannel = null; // channel shown in the panel; null = own channel
|
||||
let ubViewVersion = null; // version picked in the dropdown; null = newest
|
||||
let ubExpanded = false;
|
||||
|
||||
function ubChannelLatest(channel) {
|
||||
if (!ubData) return null;
|
||||
if (channel === ubData.channel) {
|
||||
return ubData.latest ? { ...ubData.latest, available: ubData.available } : null;
|
||||
}
|
||||
const other = ubData.other_channel;
|
||||
if (other && other.channel === channel) {
|
||||
return other.latest ? { ...other.latest, available: other.available } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// All known releases for a channel, newest first. Falls back to the
|
||||
// single latest entry when the server payload predates release lists.
|
||||
function ubChannelReleases(channel) {
|
||||
if (!ubData) return [];
|
||||
const lists = ubData.releases || {};
|
||||
if (Array.isArray(lists[channel]) && lists[channel].length) {
|
||||
return lists[channel];
|
||||
}
|
||||
const entry = ubChannelLatest(channel);
|
||||
return entry ? [entry] : [];
|
||||
}
|
||||
|
||||
// Numeric version compare mirroring the server's compare_versions:
|
||||
// compares the X.Y.Z numbers only, so stable and experimental versions
|
||||
// are comparable across channels. Returns -1, 0 or 1.
|
||||
function ubCmpVer(a, b) {
|
||||
const parse = (v) => {
|
||||
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$/.exec(String(v || '').trim());
|
||||
return m ? [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)] : null;
|
||||
};
|
||||
const pa = parse(a), pb = parse(b);
|
||||
if (!pa && !pb) return 0;
|
||||
if (!pa) return -1;
|
||||
if (!pb) return 1;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (pa[i] < pb[i]) return -1;
|
||||
if (pa[i] > pb[i]) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function ubHasNews() {
|
||||
if (!ubData || ubData.silence_all) return false;
|
||||
if (ubData.preview) return true;
|
||||
const silenced = ubData.silenced_versions || [];
|
||||
const cur = ubChannelLatest(ubData.channel);
|
||||
if (cur && cur.available && !silenced.includes(cur.version)) return true;
|
||||
const other = ubData.other_channel;
|
||||
if (other && other.available && other.latest && !silenced.includes(other.latest.version)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async function refreshUpdateBanner(keepOpen) {
|
||||
const el = document.getElementById('update-banner');
|
||||
if (!el) return;
|
||||
try {
|
||||
const resp = await fetch('/api/update/status');
|
||||
ubData = await resp.json();
|
||||
} catch (e) { return; } // leave whatever is shown
|
||||
if (!ubData || !ubData.success) return;
|
||||
if (!ubViewChannel) ubViewChannel = ubData.channel;
|
||||
// Auto-expand for fresh news unless permanently muted.
|
||||
if (!keepOpen && !ubExpanded && ubHasNews()) ubExpanded = true;
|
||||
renderUpdateBanner();
|
||||
}
|
||||
|
||||
// Notes cache keyed by version (versions are server-validated to
|
||||
// digits/dots/dashes only, so they are safe inside onclick quotes).
|
||||
let ubNotesCache = {};
|
||||
function ubSafeVer(v) {
|
||||
return /^[0-9A-Za-z.\-]+$/.test(v || '') ? v : '';
|
||||
}
|
||||
|
||||
function renderUpdateBanner() {
|
||||
const el = document.getElementById('update-banner');
|
||||
if (!el || !ubData) return;
|
||||
if (!ubExpanded) {
|
||||
const dot = ubHasNews() ? '<span class="ub-dot"></span>' : '';
|
||||
const bell = ubData.silence_all ? '🔕' : '🔔';
|
||||
el.style.display = 'block';
|
||||
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(true)">${bell}${dot}</button></span>`;
|
||||
return;
|
||||
}
|
||||
const data = ubData;
|
||||
const channels = [data.channel];
|
||||
if (data.other_channel && data.other_channel.channel &&
|
||||
!channels.includes(data.other_channel.channel)) {
|
||||
channels.push(data.other_channel.channel);
|
||||
}
|
||||
const viewing = ubViewChannel || data.channel;
|
||||
const entry = ubChannelLatest(viewing);
|
||||
const silenced = data.silenced_versions || [];
|
||||
const isSilenced = !!(entry && silenced.includes(entry.version));
|
||||
const canUpdate = !!(entry && entry.available && !isSilenced);
|
||||
|
||||
// Per-version picker: every known release on the viewed channel,
|
||||
// newest first. Older than the running version cannot be installed;
|
||||
// same-numbered is a reinstall (works across channels); newer is
|
||||
// an update. Settings and protected paths are preserved either way.
|
||||
const releases = ubChannelReleases(viewing);
|
||||
let picked = null;
|
||||
if (releases.length) {
|
||||
picked = releases.find(r => r.version === ubViewVersion) || releases[0];
|
||||
if (!ubViewVersion || !releases.some(r => r.version === ubViewVersion)) {
|
||||
ubViewVersion = picked.version;
|
||||
}
|
||||
}
|
||||
const cmp = picked ? ubCmpVer(picked.version, data.current_version) : 0;
|
||||
const pickedSilenced = !!(picked && silenced.includes(picked.version));
|
||||
const pickedCanInstall = !!(picked && cmp >= 0 && !pickedSilenced);
|
||||
|
||||
let opts = '';
|
||||
channels.forEach(ch => {
|
||||
const label = ch === data.channel ? `${ch} (yours)` : ch;
|
||||
opts += `<option value="${escHtml(ch)}"${ch === viewing ? ' selected' : ''}>${escHtml(label)}</option>`;
|
||||
});
|
||||
|
||||
let body = `<div class="ub-sub">You are on ${escHtml(data.current_version)} (${escHtml(data.channel)})</div>`;
|
||||
body += `<div class="ub-row"><label>Channel: <select id="ub-channel" onchange="ubViewChannel=this.value;ubViewVersion=null;renderUpdateBanner();">${opts}</select></label>` +
|
||||
`<button onclick="checkUpdatesNow()">Check now</button></div>`;
|
||||
|
||||
if (releases.length) {
|
||||
let vopts = '';
|
||||
releases.forEach(r => {
|
||||
const c = ubCmpVer(r.version, data.current_version);
|
||||
const tag = c < 0 ? ' — Older' : (c === 0 ? ' — Current (reinstall)' : ' — Update available');
|
||||
vopts += `<option value="${escHtml(r.version)}"${picked && r.version === picked.version ? ' selected' : ''}>${escHtml(r.version)}${escHtml(tag)}</option>`;
|
||||
});
|
||||
body += `<div class="ub-row"><label>Version: <select id="ub-version" onchange="ubViewVersion=this.value;renderUpdateBanner();">${vopts}</select></label></div>`;
|
||||
}
|
||||
|
||||
if (data.preview && ubSafeVer(data.preview.version)) {
|
||||
ubNotesCache[data.preview.version] = data.preview.notes || '';
|
||||
body += `<div class="ub-title">${escHtml(data.preview.version)} <span class="ub-preview-tag">preview</span></div>` +
|
||||
`<div class="ub-actions"><button class="ub-ghost" onclick="openNotesOverlay('${data.preview.version}')">Patch notes</button>` +
|
||||
`<button class="ub-ghost" onclick="clearPreview()">Clear preview</button></div>`;
|
||||
}
|
||||
|
||||
if (picked && ubSafeVer(picked.version)) {
|
||||
ubNotesCache[picked.version] = picked.notes || '';
|
||||
const isCurrent = cmp === 0;
|
||||
const stateLine = cmp < 0
|
||||
? `<div class="ub-sub">${escHtml(picked.version)} is older than your current version — cannot install.</div>`
|
||||
: (!pickedCanInstall && pickedSilenced)
|
||||
? `<div class="ub-sub">${escHtml(picked.version)} silenced - a newer version will show again.</div>`
|
||||
: isCurrent
|
||||
? `<div class="ub-title">Reinstall: ${escHtml(picked.version)} (same as current)</div>`
|
||||
: `<div class="ub-title">Update available: ${escHtml(picked.version)}</div>`;
|
||||
body += stateLine;
|
||||
body += '<div class="ub-actions">' +
|
||||
(picked.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${picked.version}')">Patch notes</button>` : '') +
|
||||
(pickedCanInstall ? (isCurrent
|
||||
? `<button onclick="applyUpdate('${picked.version}')">Reinstall ${escHtml(picked.version)}</button>`
|
||||
: `<button onclick="applyUpdate('${picked.version}')">Update to ${escHtml(picked.version)}</button>`) : '') +
|
||||
(cmp > 0 && !pickedSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${picked.version}')">Silence this version</button>` : '') +
|
||||
'</div>';
|
||||
} else if (entry && ubSafeVer(entry.version)) {
|
||||
ubNotesCache[entry.version] = entry.notes || '';
|
||||
const stateLine = !entry.available
|
||||
? `<div class="ub-sub">${escHtml(viewing)} is up to date at ${escHtml(entry.version)}.</div>`
|
||||
: isSilenced
|
||||
? `<div class="ub-sub">${escHtml(entry.version)} silenced - a newer version will show again.</div>`
|
||||
: `<div class="ub-title">Update available: ${escHtml(entry.version)}</div>`;
|
||||
body += stateLine;
|
||||
body += '<div class="ub-actions">' +
|
||||
(entry.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${entry.version}')">Patch notes</button>` : '') +
|
||||
(canUpdate ? `<button onclick="applyUpdate('${entry.version}')">Update to ${escHtml(entry.version)}</button>` : '') +
|
||||
(entry.available && !isSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${entry.version}')">Silence this version</button>` : '') +
|
||||
'</div>';
|
||||
} else if (!data.preview) {
|
||||
body += `<div class="ub-sub">No ${escHtml(viewing)} releases found yet.</div>`;
|
||||
}
|
||||
|
||||
body += `<label class="ub-mute"><input type="checkbox"${data.silence_all ? ' checked' : ''} onchange="setUpdateMute(this.checked)"> Don't remind me again</label>` +
|
||||
'<div class="ub-status" id="ub-status"></div>';
|
||||
el.style.display = 'block';
|
||||
const bellIcon = data.silence_all ? '🔕' : '🔔';
|
||||
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(false)">${bellIcon}</button></span>` +
|
||||
`<div class="ub-panel"><div class="ub-panel-head">Updates</div>` + body + `</div>`;
|
||||
}
|
||||
|
||||
function toggleUpdatePanel(open) {
|
||||
ubExpanded = open;
|
||||
renderUpdateBanner();
|
||||
}
|
||||
|
||||
async function checkUpdatesNow() {
|
||||
const st = document.getElementById('ub-status');
|
||||
if (st) st.textContent = 'Checking...';
|
||||
try {
|
||||
await csrfFetch('/api/update/check', { method: 'POST' });
|
||||
} catch (e) { /* status refresh below reports */ }
|
||||
refreshUpdateBanner(true);
|
||||
}
|
||||
|
||||
function openNotesOverlay(version) {
|
||||
closeNotesOverlay();
|
||||
const notes = ubNotesCache[version] || '';
|
||||
const ov = document.createElement('div');
|
||||
ov.id = 'ub-overlay';
|
||||
const box = document.createElement('div');
|
||||
box.className = 'ub-overlay-box';
|
||||
const head = document.createElement('div');
|
||||
head.className = 'ub-overlay-head';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = 'Patch notes - ' + version;
|
||||
const close = document.createElement('button');
|
||||
close.textContent = 'Close';
|
||||
close.onclick = closeNotesOverlay;
|
||||
head.appendChild(title);
|
||||
head.appendChild(close);
|
||||
const pre = document.createElement('pre');
|
||||
pre.textContent = notes || 'No notes for this version.';
|
||||
box.appendChild(head);
|
||||
box.appendChild(pre);
|
||||
ov.appendChild(box);
|
||||
ov.onclick = function(e) { if (e.target === ov) closeNotesOverlay(); };
|
||||
document.body.appendChild(ov);
|
||||
}
|
||||
|
||||
function closeNotesOverlay() {
|
||||
const ov = document.getElementById('ub-overlay');
|
||||
if (ov) ov.remove();
|
||||
}
|
||||
|
||||
async function clearPreview() {
|
||||
await csrfFetch('/api/update/preview', { method: 'DELETE' });
|
||||
refreshUpdateBanner(true);
|
||||
}
|
||||
|
||||
async function applyUpdate(version) {
|
||||
const isReinstall = ubData && version === ubData.current_version;
|
||||
const action = isReinstall ? 'Reinstall' : 'Update to';
|
||||
if (!confirm(`${action} ${version}? Settings and protected files are preserved. The dashboard backs itself up, installs, then restarts. Players will be briefly disconnected from the panel (not the game).`)) return;
|
||||
const st = document.getElementById('ub-status');
|
||||
if (st) st.textContent = 'Updating - the panel will restart...';
|
||||
try {
|
||||
const resp = await csrfFetch('/api/update/apply', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ version })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (st) st.textContent = data.success ? (data.message || 'Updating...') : ('Error: ' + (data.message || data.error || 'unknown'));
|
||||
} catch (e) {
|
||||
if (st) st.textContent = 'Error: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function silenceUpdateVersion(version) {
|
||||
await csrfFetch('/api/update/silence', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'silence', version })
|
||||
});
|
||||
refreshUpdateBanner();
|
||||
}
|
||||
|
||||
async function setUpdateMute(on) {
|
||||
await csrfFetch('/api/update/silence', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: on ? 'mute' : 'unmute' })
|
||||
});
|
||||
refreshUpdateBanner();
|
||||
}
|
||||
|
||||
async function unmuteUpdates() {
|
||||
await csrfFetch('/api/update/silence', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'unmute' })
|
||||
});
|
||||
refreshUpdateBanner();
|
||||
}
|
||||
|
||||
refreshUpdateBanner();
|
||||
setInterval(refreshUpdateBanner, 10 * 60 * 1000);
|
||||
|
||||
// Sidebar/topbar live stats: CPU + RAM sparklines and online count.
|
||||
// History persists across page changes in localStorage (30 points,
|
||||
// roughly 5 minutes at the 10s poll rate) and doubles as seed data
|
||||
// for the big Server charts.
|
||||
const NS_MAX = 30;
|
||||
const NS_INTERVAL = 10000;
|
||||
function nsLoad(key) {
|
||||
try {
|
||||
const arr = JSON.parse(localStorage.getItem(key) || '[]');
|
||||
if (!Array.isArray(arr)) return [];
|
||||
// Same freshness rule as the big charts: drop anything older
|
||||
// than 6 minutes so a restart/refresh starts clean instead of
|
||||
// replaying stale history the big graphs have discarded.
|
||||
const cutoff = Date.now() - 6 * 60 * 1000;
|
||||
return arr.filter(p => p && typeof p.v === 'number'
|
||||
&& typeof p.t === 'number' && p.t >= cutoff).slice(-NS_MAX);
|
||||
} catch (e) { return []; }
|
||||
}
|
||||
let nsCpu = nsLoad('dune-metrics-cpu');
|
||||
let nsMem = nsLoad('dune-metrics-mem');
|
||||
function nsSave() {
|
||||
try {
|
||||
localStorage.setItem('dune-metrics-cpu', JSON.stringify(nsCpu.slice(-NS_MAX)));
|
||||
localStorage.setItem('dune-metrics-mem', JSON.stringify(nsMem.slice(-NS_MAX)));
|
||||
} catch (e) { /* storage full or unavailable - keep memory-only */ }
|
||||
}
|
||||
function nsCssVar(name, fallback) {
|
||||
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
return v || fallback;
|
||||
}
|
||||
// Memory total (GiB), latched once like the big charts so the scale
|
||||
// never moves. Persisted so minis open correctly scaled on load.
|
||||
let nsMemTotal = parseFloat(localStorage.getItem('dune-mem-total') || '0') || 0;
|
||||
function drawSpark(canvas, values, color, ymax) {
|
||||
if (!canvas) return;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const w = canvas.clientWidth || canvas.width, h = canvas.clientHeight || canvas.height;
|
||||
if (!w || !h) return;
|
||||
canvas.width = w * dpr;
|
||||
canvas.height = h * dpr;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.scale(dpr, dpr);
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
if (!values.length) return;
|
||||
const min = 0, max = (ymax > 0) ? ymax : 100;
|
||||
const step = values.length > 1 ? w / (NS_MAX - 1) : 0;
|
||||
const x0 = w - step * (values.length - 1);
|
||||
ctx.beginPath();
|
||||
values.forEach((p, i) => {
|
||||
const v = (typeof p === 'number') ? p : p.v;
|
||||
const x = x0 + step * i;
|
||||
const y = h - 2 - ((Math.min(Math.max(v, min), max) - min) / (max - min)) * (h - 4);
|
||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
||||
});
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.stroke();
|
||||
ctx.lineTo(x0 + step * (values.length - 1), h);
|
||||
ctx.lineTo(x0, h);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = color + '33';
|
||||
ctx.fill();
|
||||
}
|
||||
// Last known values so layout switches re-render instantly
|
||||
// instead of waiting for the next poll.
|
||||
let nsLast = { cpu: '–', mem: '–', online: null };
|
||||
function applyNavStatsLayout() {
|
||||
const h = document.getElementById('nav-stats-h');
|
||||
const v = document.getElementById('nav-stats-v');
|
||||
const layout = document.body.getAttribute('data-nav-layout') || 'horizontal';
|
||||
if (h) h.style.display = (layout === 'horizontal') ? '' : 'none';
|
||||
if (v) v.style.display = (layout === 'vertical') ? '' : 'none';
|
||||
}
|
||||
function renderNavStats(cpuStr, memStr, online) {
|
||||
nsLast = { cpu: cpuStr, mem: memStr, online: online };
|
||||
const onlineTxt = (online === null || online === undefined) ? '–' : String(online);
|
||||
const cpuColor = nsCssVar('--primary', '#c9a24e');
|
||||
const memColor = nsCssVar('--success', '#27ae60');
|
||||
[['h'], ['v']].forEach(([sfx]) => {
|
||||
const on = document.getElementById('ns-online-' + sfx);
|
||||
const cv = document.getElementById('ns-cpuv-' + sfx);
|
||||
const mv = document.getElementById('ns-memv-' + sfx);
|
||||
if (on) on.textContent = onlineTxt;
|
||||
if (cv) cv.textContent = cpuStr;
|
||||
if (mv) mv.textContent = memStr;
|
||||
const dot = document.getElementById('ns-dot-' + sfx);
|
||||
if (dot) dot.className = 'conn-dot ' + ((online > 0) ? 'online' : 'offline');
|
||||
drawSpark(document.getElementById('ns-cpu-' + sfx), nsCpu.map(p => p.v), cpuColor, 100);
|
||||
// Pre-GiB entries have no g: skip them rather than plotting
|
||||
// percent values on a GiB scale.
|
||||
drawSpark(document.getElementById('ns-mem-' + sfx),
|
||||
nsMem.filter(p => typeof p.g === 'number').map(p => p.g), memColor,
|
||||
nsMemTotal > 0 ? Math.ceil(nsMemTotal) : 100);
|
||||
});
|
||||
applyNavStatsLayout();
|
||||
}
|
||||
async function pollNavStats() {
|
||||
if (document.hidden) return; // save the server while tab is backgrounded
|
||||
try {
|
||||
const resp = await fetch('/server/metrics');
|
||||
const data = await resp.json();
|
||||
const now = Date.now();
|
||||
if (typeof data.cpu_num === 'number') {
|
||||
nsCpu.push({ t: now, v: data.cpu_num });
|
||||
nsCpu = nsCpu.slice(-NS_MAX);
|
||||
}
|
||||
// Percent only for the graph scale; GiB rides along so the big
|
||||
// Server charts can seed from this same history.
|
||||
if (typeof data.memory_pct_num === 'number') {
|
||||
const gib = (typeof data.memory_gib === 'number') ? data.memory_gib : null;
|
||||
nsMem.push({ t: now, v: data.memory_pct_num, g: gib });
|
||||
nsMem = nsMem.slice(-NS_MAX);
|
||||
// Latch the RAM total once, then only re-latch when the
|
||||
// machine itself actually changed (implied total moved
|
||||
// >5%): per-sample rounding wobble never moves the ruler.
|
||||
if (data.memory_pct_num > 0 && gib > 0) {
|
||||
const implied = gib / (data.memory_pct_num / 100);
|
||||
if (!nsMemTotal || Math.abs(implied - nsMemTotal) / nsMemTotal > 0.05) {
|
||||
nsMemTotal = implied;
|
||||
try { localStorage.setItem('dune-mem-total', String(nsMemTotal)); } catch (e) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Drop stale points on every poll (not just at load) so a
|
||||
// wake-from-sleep recovers on the next poll instead of
|
||||
// replaying old history for minutes.
|
||||
const freshCutoff = Date.now() - 6 * 60 * 1000;
|
||||
nsCpu = nsCpu.filter(p => p && p.t >= freshCutoff);
|
||||
nsMem = nsMem.filter(p => p && p.t >= freshCutoff);
|
||||
nsSave();
|
||||
renderNavStats(data.cpu || '–', data.memory || '–',
|
||||
(data.online === null || data.online === undefined) ? null : data.online);
|
||||
} catch (e) { /* keep last values on failure */ }
|
||||
}
|
||||
pollNavStats();
|
||||
setInterval(pollNavStats, NS_INTERVAL);
|
||||
</script>
|
||||
{% block scripts %}{% endblock %}
|
||||
<style>
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@
|
||||
<label style="display:flex;align-items:center;gap:4px;font-size:13px;color:var(--text-light);cursor:pointer;">
|
||||
<input type="checkbox" id="auto-refresh" style="cursor:pointer;"> Auto-refresh (30s)
|
||||
</label>
|
||||
<select id="filter-channel" style="padding:6px 12px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:13px;">
|
||||
<select id="filter-channel" style="padding:6px 12px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:13px;">
|
||||
<option value="all">All Channels</option>
|
||||
<option value="Proximity">Proximity</option>
|
||||
<option value="Map">Map</option>
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
|
||||
<div>
|
||||
<label>Incoming Transfers:</label>
|
||||
<select id="incoming-transfers" style="width:100%;padding:6px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;margin-top:4px;">
|
||||
<select id="incoming-transfers" style="width:100%;padding:6px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;margin-top:4px;">
|
||||
<option value="0">Default (0)</option>
|
||||
<option value="10">Deny All (10)</option>
|
||||
<option value="20">From Private Only (20)</option>
|
||||
|
||||
+158
-36
@@ -4,8 +4,7 @@
|
||||
|
||||
<div class="page-header">
|
||||
<h1>Game Events</h1>
|
||||
<p>Recent activity from the game event log</p>
|
||||
<p style="font-size:11px;color:var(--text-muted);">Note: Solaris currency events may show incomplete history. Delta values may not sum to current balance.</p>
|
||||
<p>What is happening on your server, in plain language</p>
|
||||
</div>
|
||||
|
||||
{% if tunnel_down %}
|
||||
@@ -14,56 +13,179 @@
|
||||
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
|
||||
{% else %}
|
||||
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
|
||||
<div class="card">
|
||||
<div class="card-header">Game Events ({{ game_events|length }})</div>
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="label">Events (24h)</div>
|
||||
<div class="value">{{ total_24h }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Deaths (24h)</div>
|
||||
<div class="value">{{ counts_24h.get(0, 0) }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Builds Placed (24h)</div>
|
||||
<div class="value">{{ counts_24h.get(10, 0) }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Permission Changes (24h)</div>
|
||||
<div class="value">{{ counts_24h.get(97, 0) }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Active Maps</div>
|
||||
<div class="value">{{ maps|length }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">Event Feed</div>
|
||||
<div class="card-body">
|
||||
<form method="get" action="/events" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;margin-bottom:16px;">
|
||||
<label style="font-size:13px;">Type:
|
||||
<select name="type" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
<option value="all" {% if type_filter == 'all' %}selected{% endif %}>All types</option>
|
||||
{% for tid, tlabel in type_options %}
|
||||
<option value="{{ tid }}" {% if type_filter == tid %}selected{% endif %}>{{ tlabel }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label style="font-size:13px;">Map:
|
||||
<select name="map" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
<option value="all" {% if map_filter == 'all' %}selected{% endif %}>All maps</option>
|
||||
{% for m in maps %}
|
||||
<option value="{{ m }}" {% if map_filter == m %}selected{% endif %}>{{ m }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label style="font-size:13px;">Player-facing:
|
||||
<select name="facing" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
<option value="all" {% if facing_filter == 'all' %}selected{% endif %}>Both</option>
|
||||
<option value="1" {% if facing_filter == '1' %}selected{% endif %}>Yes</option>
|
||||
<option value="0" {% if facing_filter == '0' %}selected{% endif %}>No</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit" style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Filter</button>
|
||||
<a href="/events" style="padding:8px 16px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;font-size:13px;text-decoration:none;">Reset</a>
|
||||
</form>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Time</th><th>Actor</th><th>Map</th><th>Type</th><th>Player</th><th>Position</th></tr>
|
||||
<tr><th>Time</th><th>Event</th><th>Map</th><th>Details</th><th>Position</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for e in game_events[:25] %}
|
||||
<tr>
|
||||
<td style="font-size:11px;white-space:nowrap;">{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}</td>
|
||||
<td><span class="badge">{{ e.label }}</span></td>
|
||||
<td>{{ e.map or '' }}</td>
|
||||
<td style="font-size:12px;">{{ e.summary or '-' }}</td>
|
||||
<td style="font-size:11px;font-family:monospace;">{% if e.x is not none and e.y is not none %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}{% endif %}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="5" class="empty">No events match these filters</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if game_events|length > 25 %}
|
||||
<div style="margin-top:12px;text-align:center;">
|
||||
<button onclick="openEventsModal()" style="padding:8px 20px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Show all {{ game_events|length }} events</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="events-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeEventsModal()">
|
||||
<div class="modal modal-wide">
|
||||
<h3>All Events ({{ game_events|length }})</h3>
|
||||
<div class="table-wrap" style="max-height:60vh;overflow-y:auto;">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Time</th><th>Event</th><th>Map</th><th>Details</th><th>Position</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for e in game_events %}
|
||||
<tr>
|
||||
<td style="font-size:11px;white-space:nowrap;">{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}</td>
|
||||
<td>{{ e.actor_id }}</td>
|
||||
<td><span class="badge">{{ e.label }}</span></td>
|
||||
<td>{{ e.map or '' }}</td>
|
||||
<td>{{ e.event_type }}</td>
|
||||
<td>{% if e.actor_name %}{{ e.actor_name }}{% else %}-{% endif %}</td>
|
||||
<td style="font-size:11px;font-family:monospace;">{% if e.x %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}, {{ e.z|round(0)|int }}{% endif %}</td>
|
||||
<td style="font-size:12px;">{{ e.summary or '-' }}</td>
|
||||
<td style="font-size:11px;font-family:monospace;">{% if e.x is not none and e.y is not none %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}{% endif %}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="6" class="empty">No game events found</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">Event Log ({{ event_logs|length }})</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Time</th><th>Category</th><th>Function</th><th>Message</th><th>Details</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for e in event_logs %}
|
||||
<tr>
|
||||
<td style="font-size:11px;white-space:nowrap;">{{ e.event_time.strftime('%Y-%m-%d %H:%M') if e.event_time else '' }}</td>
|
||||
<td><span class="badge badge-{{ e.category.lower() if e.category else 'none' }}">{{ e.category or '' }}</span></td>
|
||||
<td style="font-size:11px;font-family:monospace;">{{ e.function_name or '' }}</td>
|
||||
<td style="font-size:12px;">{{ e.message or '' }}</td>
|
||||
<td style="font-size:10px;max-width:250px;word-break:break-word;">{% if e.meta %}<pre style="margin:0;font-size:10px;white-space:pre-wrap;">{{ e.meta | json_format }}</pre>{% endif %}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="5" class="empty">No event logs found</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="modal-actions" style="margin-top:12px;text-align:right;">
|
||||
<button onclick="closeEventsModal()" class="btn-cancel">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">Solaris Movements ({{ solaris|length }})</div>
|
||||
<div class="card-body">
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Time</th><th>Player</th><th>Change</th><th>Balance</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for s in solaris[:25] %}
|
||||
<tr>
|
||||
<td style="font-size:11px;white-space:nowrap;">{{ s.event_time.strftime('%Y-%m-%d %H:%M') if s.event_time else '' }}</td>
|
||||
<td style="font-family:monospace;font-size:12px;">{{ s.fls_id or '' }}</td>
|
||||
<td style="font-size:13px;font-weight:600;color:{% if s.delta >= 0 %}#27ae60{% else %}#e74c3c{% endif %};">{{ '+' if s.delta >= 0 else '' }}{{ s.delta | format_number }}</td>
|
||||
<td style="font-size:12px;">{{ s.balance | format_number }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="4" class="empty">No currency movements logged</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if solaris|length > 25 %}
|
||||
<div style="margin-top:12px;text-align:center;">
|
||||
<button onclick="openSolarisModal()" style="padding:8px 20px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Show all {{ solaris|length }} movements</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="solaris-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeSolarisModal()">
|
||||
<div class="modal modal-wide">
|
||||
<h3>All Solaris Movements ({{ solaris|length }})</h3>
|
||||
<div class="table-wrap" style="max-height:60vh;overflow-y:auto;">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Time</th><th>Player</th><th>Change</th><th>Balance</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for s in solaris %}
|
||||
<tr>
|
||||
<td style="font-size:11px;white-space:nowrap;">{{ s.event_time.strftime('%Y-%m-%d %H:%M') if s.event_time else '' }}</td>
|
||||
<td style="font-family:monospace;font-size:12px;">{{ s.fls_id or '' }}</td>
|
||||
<td style="font-size:13px;font-weight:600;color:{% if s.delta >= 0 %}#27ae60{% else %}#e74c3c{% endif %};">{{ '+' if s.delta >= 0 else '' }}{{ s.delta | format_number }}</td>
|
||||
<td style="font-size:12px;">{{ s.balance | format_number }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="modal-actions" style="margin-top:12px;text-align:right;">
|
||||
<button onclick="closeSolarisModal()" class="btn-cancel">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function openEventsModal() { document.getElementById('events-modal').style.display = 'flex'; }
|
||||
function closeEventsModal() { document.getElementById('events-modal').style.display = 'none'; }
|
||||
function openSolarisModal() { document.getElementById('solaris-modal').style.display = 'flex'; }
|
||||
function closeSolarisModal() { document.getElementById('solaris-modal').style.display = 'none'; }
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape') { closeEventsModal(); closeSolarisModal(); }
|
||||
});
|
||||
</script>
|
||||
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
@@ -33,7 +33,7 @@
|
||||
.view-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
|
||||
.view-info { display: flex; gap: 8px; align-items: center; }
|
||||
.view-actions { display: flex; gap: 8px; }
|
||||
.view-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
|
||||
.view-btn { padding: 6px 14px; background: var(--card-bg); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
|
||||
.view-btn:hover { background: var(--bg-hover); }
|
||||
.view-btn.primary { background: var(--primary); color: #fff; border-color: var(--primary); }
|
||||
.view-btn.primary:hover { background: var(--primary-dark); }
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<div class="fm-layout">
|
||||
<div class="fm-panel">
|
||||
<div class="fm-toolbar">
|
||||
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
|
||||
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
|
||||
<option value="">Loading...</option>
|
||||
</select>
|
||||
<span style="flex:1;"></span>
|
||||
@@ -43,7 +43,7 @@
|
||||
.fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
|
||||
.fm-panel { min-height: 0; display: flex; flex-direction: column; }
|
||||
.fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
|
||||
.fm-btn { padding: 6px 12px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
|
||||
.fm-btn { padding: 6px 12px; background: var(--card-bg); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
|
||||
.fm-btn:hover { background: var(--bg-hover); }
|
||||
.fm-btn.danger { color: var(--danger); border-color: var(--danger); }
|
||||
.fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
justify-content: center;
|
||||
}
|
||||
.login-container {
|
||||
background: var(--bg-card);
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 2rem;
|
||||
|
||||
+1
-1
@@ -168,7 +168,7 @@ function initMap() {
|
||||
markerClusterGroup = (typeof L.markerClusterGroup !== 'undefined')
|
||||
? L.markerClusterGroup({
|
||||
chunkedLoading: true,
|
||||
maxClusterRadius: 5,
|
||||
maxClusterRadius: 12,
|
||||
spiderfyOnMaxZoom: true,
|
||||
showCoverageOnHover: false,
|
||||
iconCreateFunction: function(cluster) {
|
||||
|
||||
+118
-34
@@ -107,17 +107,17 @@
|
||||
<div style="margin-bottom:12px;">
|
||||
<label style="display:block;margin-bottom:4px;font-size:13px;">Title</label>
|
||||
<input type="text" id="bc-title" value="Server Notice"
|
||||
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<label style="display:block;margin-bottom:4px;font-size:13px;">Message</label>
|
||||
<textarea id="bc-message" rows="3"
|
||||
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;resize:vertical;"></textarea>
|
||||
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;resize:vertical;"></textarea>
|
||||
</div>
|
||||
<div style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;">
|
||||
<label style="font-size:13px;">Duration (seconds, 5–300):
|
||||
<input type="number" id="bc-duration" value="30" min="5" max="300"
|
||||
style="display:block;width:120px;margin-top:4px;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
style="display:block;width:120px;margin-top:4px;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
</label>
|
||||
<button id="bc-send-btn" style="padding:10px 24px;background:var(--accent);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:14px;">Send Broadcast</button>
|
||||
<span id="bc-msg" style="font-size:12px;color:var(--text-muted);"></span>
|
||||
@@ -142,23 +142,23 @@
|
||||
<div style="margin-bottom:8px;">
|
||||
<label style="display:block;margin-bottom:4px;font-size:13px;">Title</label>
|
||||
<input type="text" id="bn-title" value="Server Notice"
|
||||
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
</div>
|
||||
<div style="margin-bottom:8px;">
|
||||
<label style="display:block;margin-bottom:4px;font-size:13px;">Message</label>
|
||||
<textarea id="bn-message" rows="2"
|
||||
style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;resize:vertical;"></textarea>
|
||||
style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;resize:vertical;"></textarea>
|
||||
</div>
|
||||
<div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:12px;">
|
||||
<label style="font-size:13px;">Duration (5–300s):
|
||||
<input type="number" id="bn-duration" value="30" min="5" max="300"
|
||||
style="width:90px;padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
style="width:90px;padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||
</label>
|
||||
<label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;">
|
||||
<input type="checkbox" id="bn-enabled" checked style="width:16px;height:16px;"> Enabled
|
||||
</label>
|
||||
<label style="font-size:13px;">Repeats:
|
||||
<select id="bn-mode" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);">
|
||||
<select id="bn-mode" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);">
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
<option value="monthly">Monthly</option>
|
||||
@@ -169,7 +169,7 @@
|
||||
<div id="bn-sched-daily" style="margin-bottom:12px;">
|
||||
<div style="font-size:13px;margin-bottom:6px;">Times - pick a time, then Add:</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
|
||||
<input type="time" id="bn-daily-time-pick" value="12:00" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="time" id="bn-daily-time-pick" value="12:00" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<button id="bn-daily-add" style="padding:6px 14px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Add time</button>
|
||||
</div>
|
||||
<div id="bn-daily-chips" style="display:flex;gap:6px;flex-wrap:wrap;"></div>
|
||||
@@ -187,7 +187,7 @@
|
||||
</div>
|
||||
<div style="font-size:13px;margin-bottom:6px;">Times - pick a time, then Add:</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
|
||||
<input type="time" id="bn-weekly-time-pick" value="12:00" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="time" id="bn-weekly-time-pick" value="12:00" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<button id="bn-weekly-add" style="padding:6px 14px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Add time</button>
|
||||
</div>
|
||||
<div id="bn-weekly-chips" style="display:flex;gap:6px;flex-wrap:wrap;"></div>
|
||||
@@ -196,12 +196,12 @@
|
||||
<div style="font-size:13px;margin-bottom:6px;">Days of month - click to select:</div>
|
||||
<div id="bn-monthly-grid" style="display:grid;grid-template-columns:repeat(8, minmax(34px, 44px));gap:6px;margin-bottom:8px;"></div>
|
||||
<label style="font-size:13px;">Time:
|
||||
<input type="time" id="bn-monthly-time" value="12:00" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="time" id="bn-monthly-time" value="12:00" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
</label>
|
||||
</div>
|
||||
<div id="bn-sched-once" style="margin-bottom:12px;display:none;">
|
||||
<label style="font-size:13px;">Date + time - pick from the calendar:
|
||||
<input type="datetime-local" id="bn-once-at" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="datetime-local" id="bn-once-at" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
</label>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
|
||||
@@ -255,7 +255,7 @@
|
||||
<input type="checkbox" id="lc-sched-enabled" style="width:16px;height:16px;"> Enabled
|
||||
</label>
|
||||
<label style="font-size:13px;">Mode:
|
||||
<select id="lc-sched-mode" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);">
|
||||
<select id="lc-sched-mode" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);">
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
<option value="monthly">Monthly</option>
|
||||
@@ -266,7 +266,7 @@
|
||||
<div id="lc-sched-daily" style="margin-bottom:12px;">
|
||||
<div style="font-size:13px;margin-bottom:6px;">Times - pick a time, then Add:</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
|
||||
<input type="time" id="lc-daily-time-pick" value="05:00" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="time" id="lc-daily-time-pick" value="05:00" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<button id="lc-daily-add" style="padding:6px 14px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Add time</button>
|
||||
</div>
|
||||
<div id="lc-daily-chips" style="display:flex;gap:6px;flex-wrap:wrap;"></div>
|
||||
@@ -284,7 +284,7 @@
|
||||
</div>
|
||||
<div style="font-size:13px;margin-bottom:6px;">Times - pick a time, then Add:</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
|
||||
<input type="time" id="lc-weekly-time-pick" value="05:00" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="time" id="lc-weekly-time-pick" value="05:00" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<button id="lc-weekly-add" style="padding:6px 14px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Add time</button>
|
||||
</div>
|
||||
<div id="lc-weekly-chips" style="display:flex;gap:6px;flex-wrap:wrap;"></div>
|
||||
@@ -293,12 +293,12 @@
|
||||
<div style="font-size:13px;margin-bottom:6px;">Days of month - click to select:</div>
|
||||
<div id="lc-monthly-grid" style="display:grid;grid-template-columns:repeat(8, minmax(34px, 44px));gap:6px;margin-bottom:8px;"></div>
|
||||
<label style="font-size:13px;">Time:
|
||||
<input type="time" id="lc-monthly-time" value="05:00" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="time" id="lc-monthly-time" value="05:00" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
</label>
|
||||
</div>
|
||||
<div id="lc-sched-once" style="margin-bottom:12px;display:none;">
|
||||
<label style="font-size:13px;">Date + time - pick from the calendar:
|
||||
<input type="datetime-local" id="lc-once-at" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
<input type="datetime-local" id="lc-once-at" style="padding:6px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;color-scheme:dark;">
|
||||
</label>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
|
||||
@@ -494,7 +494,7 @@
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<textarea id="sat-token" rows="4"
|
||||
style="width:100%;padding:10px 12px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:12px;font-family:monospace;resize:vertical;"
|
||||
style="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:12px;font-family:monospace;resize:vertical;"
|
||||
placeholder="Paste the new ServiceAuthToken JWT here..."></textarea>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
|
||||
@@ -576,7 +576,7 @@
|
||||
{% block scripts %}
|
||||
<script>
|
||||
// ── Node resource charts ──────────────────────────────────────────────
|
||||
const MAX_POINTS = 720; // 1 hour at 5s intervals
|
||||
const MAX_POINTS = 60; // 5 minutes at 5s intervals
|
||||
const SPARKLINE_POINTS = 60; // 5 min for sparkline
|
||||
let metricsHistory = []; // [{cpu_num, memory_gib, memory_pct_num, memory, cpu, ts}]
|
||||
|
||||
@@ -585,6 +585,10 @@ function parseCSSVar(name) {
|
||||
}
|
||||
|
||||
function drawCharts(history) {
|
||||
// Memory plots GiB on a fixed 0-to-total scale set once from the first
|
||||
// good sample - never rescaled after, exactly like CPU's fixed 0-100.
|
||||
// The total is latched in fetchMetrics/seedMetricsHistory, so the mem
|
||||
// chart is only created once it is known (no autoscale window ever).
|
||||
const cpuVals = history.map(p => p.cpu_num);
|
||||
const memVals = history.map(p => p.memory_gib);
|
||||
const primaryColor = parseCSSVar('--primary') || '#c9a24e';
|
||||
@@ -611,29 +615,42 @@ function drawCharts(history) {
|
||||
data: { labels: [], datasets: [{ label: 'CPU %', data: [], borderColor: primaryColor, backgroundColor: primaryColor + '20', fill: true, pointRadius: 0, borderWidth: 2, tension: 0.3 }] },
|
||||
options: { ...commonOpts, scales: { ...commonOpts.scales, y: { ...commonOpts.scales.y, min: 0, max: 100, title: { display: true, text: 'CPU %', color: textColor, font: { size: 11 } } } } }
|
||||
});
|
||||
const memMax = window._totalMemGib ? Math.ceil(window._totalMemGib) : undefined;
|
||||
window._memChart = new Chart(chartMem, {
|
||||
type: 'line',
|
||||
data: { labels: [], datasets: [{ label: 'Memory GiB', data: [], borderColor: successColor, backgroundColor: successColor + '20', fill: true, pointRadius: 0, borderWidth: 2, tension: 0.3 }] },
|
||||
options: { ...commonOpts, scales: { ...commonOpts.scales, y: { ...commonOpts.scales.y, beginAtZero: true, max: memMax, title: { display: true, text: 'GiB', color: textColor, font: { size: 11 } } } } }
|
||||
});
|
||||
if (window._totalMemGib > 0 && !window._memChart) {
|
||||
const memMax = Math.ceil(window._totalMemGib);
|
||||
window._memChart = new Chart(chartMem, {
|
||||
type: 'line',
|
||||
data: { labels: [], datasets: [{ label: 'Memory GiB', data: [], borderColor: successColor, backgroundColor: successColor + '20', fill: true, pointRadius: 0, borderWidth: 2, tension: 0.3 }] },
|
||||
options: { ...commonOpts,
|
||||
plugins: { legend: { display: false },
|
||||
tooltip: { callbacks: { label: (c) => {
|
||||
const p = history[c.dataIndex] || {};
|
||||
const pct = (typeof p.memory_pct_num === 'number') ? ` (${p.memory_pct_num.toFixed(0)}%)` : '';
|
||||
return ` ${c.parsed.y.toFixed(1)} GiB${pct}`;
|
||||
} } } },
|
||||
scales: { ...commonOpts.scales, y: { ...commonOpts.scales.y, min: 0, max: memMax, title: { display: true, text: 'GiB', color: textColor, font: { size: 11 } } } } }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Full-window labels (60 slots = 5 min at 5s each), filled from the
|
||||
// left: the trace starts at the left edge on first sample and grows
|
||||
// right as history accumulates. A category axis clamps min/max to the
|
||||
// data, so padding (not min/max) is what holds the window open.
|
||||
const labels = history.map(p => p.ts);
|
||||
while (labels.length < MAX_POINTS) labels.push('');
|
||||
window._cpuChart.data.labels = labels;
|
||||
window._cpuChart.data.datasets[0].data = cpuVals;
|
||||
window._cpuChart.data.datasets[0].borderColor = primaryColor;
|
||||
window._cpuChart.data.datasets[0].backgroundColor = primaryColor + '20';
|
||||
window._cpuChart.update('none');
|
||||
|
||||
window._memChart.data.labels = labels;
|
||||
window._memChart.data.datasets[0].data = memVals;
|
||||
window._memChart.data.datasets[0].borderColor = successColor;
|
||||
window._memChart.data.datasets[0].backgroundColor = successColor + '20';
|
||||
if (window._totalMemGib) {
|
||||
window._memChart.options.scales.y.max = Math.ceil(window._totalMemGib);
|
||||
if (window._memChart) {
|
||||
window._memChart.data.labels = labels;
|
||||
window._memChart.data.datasets[0].data = memVals;
|
||||
window._memChart.data.datasets[0].borderColor = successColor;
|
||||
window._memChart.data.datasets[0].backgroundColor = successColor + '20';
|
||||
window._memChart.update('none');
|
||||
}
|
||||
window._memChart.update('none');
|
||||
}
|
||||
|
||||
async function fetchMetrics() {
|
||||
@@ -645,16 +662,30 @@ async function fetchMetrics() {
|
||||
|
||||
const memPctNum = data.memory_pct_num || 0;
|
||||
const memGib = data.memory_gib || 0;
|
||||
if (!window._totalMemGib && memPctNum > 0) {
|
||||
window._totalMemGib = memGib / (memPctNum / 100);
|
||||
// Latch once; re-latch only on a real machine change (>5%),
|
||||
// so rounding wobble never moves the ruler but a RAM
|
||||
// upgrade/replacement is picked up within one poll.
|
||||
if (memPctNum > 0 && memGib > 0) {
|
||||
const implied = memGib / (memPctNum / 100);
|
||||
if (!window._totalMemGib ||
|
||||
Math.abs(implied - window._totalMemGib) / window._totalMemGib > 0.05) {
|
||||
window._totalMemGib = implied;
|
||||
if (window._memChart) {
|
||||
window._memChart.options.scales.y.max = Math.ceil(implied);
|
||||
}
|
||||
}
|
||||
}
|
||||
document.getElementById('node-mem').textContent = data.memory;
|
||||
|
||||
const now = new Date();
|
||||
const ts = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0') + ':' + now.getSeconds().toString().padStart(2, '0');
|
||||
const point = { cpu_num: data.cpu_num || 0, memory_gib: memGib, memory_pct_num: memPctNum, memory: data.memory, cpu: data.cpu, ts: ts };
|
||||
const point = { t: now.getTime(), cpu_num: data.cpu_num || 0, memory_gib: memGib, memory_pct_num: memPctNum, memory: data.memory, cpu: data.cpu, ts: ts };
|
||||
metricsHistory.push(point);
|
||||
if (metricsHistory.length > MAX_POINTS) metricsHistory.shift();
|
||||
// Same freshness rule as the sidebar: drop stale points on every
|
||||
// poll so a wake-from-sleep recovers immediately.
|
||||
const freshCutoff = Date.now() - 6 * 60 * 1000;
|
||||
metricsHistory = metricsHistory.filter(p => p && typeof p.t === 'number' && p.t >= freshCutoff);
|
||||
|
||||
drawCharts(metricsHistory);
|
||||
}
|
||||
@@ -670,6 +701,59 @@ function loadChartJS(src) {
|
||||
});
|
||||
}
|
||||
|
||||
function fmtClock(ms) {
|
||||
const d = new Date(ms);
|
||||
return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
|
||||
}
|
||||
|
||||
// Seed the big charts from the sidebar's stored history (same 10s samples
|
||||
// the nav widget collects on every page). Skipped when stale so yesterday
|
||||
// is never plotted as now; live polling takes over seamlessly after.
|
||||
function seedMetricsHistory() {
|
||||
try {
|
||||
const cpu = JSON.parse(localStorage.getItem('dune-metrics-cpu') || '[]');
|
||||
const mem = JSON.parse(localStorage.getItem('dune-metrics-mem') || '[]');
|
||||
if (!Array.isArray(cpu) || !cpu.length) return;
|
||||
// Drop every stale point, not just check the newest: a buffer mixing
|
||||
// an old cluster with fresh points would otherwise plot a span far
|
||||
// wider than the 5-minute window. 6 minutes keeps a full window plus
|
||||
// margin for slow polls.
|
||||
const cutoff = Date.now() - 6 * 60 * 1000;
|
||||
const fresh = cpu.filter(p => p && typeof p.t === 'number'
|
||||
&& typeof p.v === 'number' && p.t >= cutoff);
|
||||
if (!fresh.length) return;
|
||||
const memByT = {};
|
||||
mem.forEach(p => { if (p && typeof p.t === 'number') memByT[p.t] = p; });
|
||||
// Derive total RAM once so GiB-less points can be backfilled.
|
||||
let total = window._totalMemGib || 0;
|
||||
if (!total) {
|
||||
for (let i = fresh.length - 1; i >= 0; i--) {
|
||||
const m = memByT[fresh[i].t];
|
||||
if (m && typeof m.g === 'number' && m.g > 0 && m.v > 0) {
|
||||
total = m.g / (m.v / 100);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (total > 0) window._totalMemGib = total;
|
||||
}
|
||||
const pts = [];
|
||||
fresh.slice(-MAX_POINTS).forEach(p => {
|
||||
const m = memByT[p.t] || {};
|
||||
let gib = (typeof m.g === 'number') ? m.g : 0;
|
||||
const pct = (typeof m.v === 'number') ? m.v : 0;
|
||||
if (!gib && pct > 0 && total > 0) gib = pct / 100 * total;
|
||||
if (!gib && !pct) return;
|
||||
pts.push({
|
||||
t: p.t, cpu_num: p.v, memory_gib: gib, memory_pct_num: pct,
|
||||
memory: '', cpu: '', ts: fmtClock(p.t)
|
||||
});
|
||||
});
|
||||
if (pts.length) metricsHistory = pts;
|
||||
} catch (e) { /* start empty on any problem */ }
|
||||
}
|
||||
|
||||
seedMetricsHistory();
|
||||
|
||||
loadChartJS('https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js').then(() => {
|
||||
fetchMetrics();
|
||||
setInterval(fetchMetrics, 5000);
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<div class="card">
|
||||
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
|
||||
<span>Pod Shell</span>
|
||||
<select id="pod-select" style="padding:4px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;">
|
||||
<select id="pod-select" style="padding:4px;background:var(--card-bg);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;">
|
||||
{% for pod in pods %}
|
||||
<option value="{{ pod.name }}">{{ pod.name }}</option>
|
||||
{% endfor %}
|
||||
@@ -74,7 +74,7 @@
|
||||
<div class="modal" style="max-width:900px;">
|
||||
<div class="modal-header"><h3>Pod Logs - <span id="logs-pod-name"></span></h3></div>
|
||||
<div id="logs-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading logs...</div>
|
||||
<pre id="logs-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||
<pre id="logs-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--card-bg);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||
<button onclick="closeModal('logs-modal')" class="btn-cancel">Close</button>
|
||||
</div>
|
||||
@@ -86,7 +86,7 @@
|
||||
<div class="modal" style="max-width:900px;">
|
||||
<div class="modal-header"><h3>Describe Pod - <span id="describe-pod-name"></span></h3></div>
|
||||
<div id="describe-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading...</div>
|
||||
<pre id="describe-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--bg-card);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||
<pre id="describe-content" style="max-height:500px;overflow:auto;white-space:pre-wrap;display:none;margin:0;padding:16px;font-size:12px;background:var(--card-bg);color:var(--text);border-top:1px solid var(--border);"></pre>
|
||||
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||
<button onclick="closeModal('describe-modal')" class="btn-cancel">Close</button>
|
||||
</div>
|
||||
@@ -99,7 +99,7 @@
|
||||
<div class="modal-header"><h3 id="delete-modal-title">Delete Pod</h3></div>
|
||||
<div class="modal-body" style="padding:20px;">
|
||||
<p id="delete-modal-message">Are you sure you want to delete this pod?</p>
|
||||
<p style="font-family:monospace;font-size:14px;padding:8px 12px;background:var(--bg-card);border-radius:4px;margin:12px 0 0;" id="delete-pod-name-display"></p>
|
||||
<p style="font-family:monospace;font-size:14px;padding:8px 12px;background:var(--card-bg);border-radius:4px;margin:12px 0 0;" id="delete-pod-name-display"></p>
|
||||
</div>
|
||||
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
|
||||
<button onclick="closeModal('delete-modal')" class="btn-cancel">Cancel</button>
|
||||
@@ -116,7 +116,10 @@
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
||||
<script>
|
||||
const socket = io();
|
||||
// Polling only: the server runs in threading mode, which has no true
|
||||
// websocket support. Letting the client attempt a websocket upgrade only
|
||||
// produces "Cannot obtain socket from WSGI environment" tracebacks.
|
||||
const socket = io({ transports: ['polling'] });
|
||||
|
||||
let termVM = null;
|
||||
let termPod = null;
|
||||
|
||||
@@ -11,7 +11,7 @@ class FakeSSH:
|
||||
self.rc = rc
|
||||
self.commands = []
|
||||
|
||||
def run(self, command, timeout=30):
|
||||
def run(self, command, timeout=30, quiet=False):
|
||||
self.commands.append(command)
|
||||
return self.out, '', self.rc
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Tests for game event summaries and solaris log parsing."""
|
||||
|
||||
from app.utils.events import (
|
||||
clean_name,
|
||||
event_label,
|
||||
parse_solaris_meta,
|
||||
summarize_game_event,
|
||||
)
|
||||
|
||||
|
||||
class TestLabels:
|
||||
def test_known_types(self):
|
||||
assert event_label(0) == 'Death'
|
||||
assert event_label(97) == 'Permission change'
|
||||
|
||||
def test_unknown_type_falls_back(self):
|
||||
assert event_label(12345) == 'Event 12345'
|
||||
assert event_label('xyz') == 'Event xyz'
|
||||
|
||||
|
||||
class TestCleanName:
|
||||
def test_strips_hashes(self):
|
||||
assert clean_name('##MediumOrnithopter') == 'MediumOrnithopter'
|
||||
assert clean_name('#Totem') == 'Totem'
|
||||
|
||||
def test_blanks(self):
|
||||
assert clean_name(None) == ''
|
||||
assert clean_name('None') == ''
|
||||
assert clean_name('!!act#0') == ''
|
||||
|
||||
|
||||
class TestSummaries:
|
||||
def test_death(self):
|
||||
msg = summarize_game_event(0, {'m_KillerType': 'NPC', 'm_DamageType': 'None'})
|
||||
assert 'NPC' in msg
|
||||
|
||||
def test_build(self):
|
||||
msg = summarize_game_event(10, {'m_CauserType': 'Player',
|
||||
'm_BuildableName': 'Totem_Small_Placeable'})
|
||||
assert 'Totem_Small_Placeable' in msg
|
||||
|
||||
def test_permission(self):
|
||||
msg = summarize_game_event(97, {'m_PermissionActorName': '##MediumOrnithopter',
|
||||
'm_OldPermissionRank': 'Associate',
|
||||
'm_NewPermissionRank': 'CoOwner'})
|
||||
assert 'Associate -> CoOwner' in msg
|
||||
|
||||
def test_power_hours(self):
|
||||
msg = summarize_game_event(95, {'m_BuildableName': 'Totem_Placeable',
|
||||
'm_PowerTimeLeftSeconds': 35959})
|
||||
assert '9h' in msg
|
||||
|
||||
def test_never_raises(self):
|
||||
assert summarize_game_event(0, 'not json {{{') == '' or True
|
||||
assert summarize_game_event(999, None) == ''
|
||||
assert summarize_game_event(97, {'m_OldPermissionRank': 'x'}) != '' or True
|
||||
|
||||
|
||||
class TestSolarisMeta:
|
||||
def test_python_repr_format(self):
|
||||
parsed = parse_solaris_meta(
|
||||
"{'event': 'adjust_player_virtual_currency_balance', "
|
||||
"'fls_id': 'ABC123', 'solaris_delta': -27562, 'solaris_balance': 23135}")
|
||||
assert parsed == {'fls_id': 'ABC123', 'delta': -27562, 'balance': 23135}
|
||||
|
||||
def test_json_format(self):
|
||||
parsed = parse_solaris_meta(
|
||||
'{"fls_id": "ABC", "solaris_delta": 6000, "solaris_balance": 100}')
|
||||
assert parsed['delta'] == 6000
|
||||
|
||||
def test_garbage_returns_none(self):
|
||||
assert parse_solaris_meta(None) is None
|
||||
assert parse_solaris_meta('just a string') is None
|
||||
assert parse_solaris_meta('[1, 2]') is None
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Tests for the cheroot server builder + handshake-noise filter."""
|
||||
|
||||
import logging
|
||||
|
||||
from app.utils.http_server import build_server, cheroot_error_filter
|
||||
|
||||
|
||||
class TestHandshakeFilter:
|
||||
def test_handshake_drops_go_to_debug_only(self, caplog):
|
||||
calls = []
|
||||
|
||||
def orig(msg='', level=20, traceback=False):
|
||||
calls.append((msg, level))
|
||||
|
||||
with caplog.at_level(logging.DEBUG, logger='app.utils.http_server'):
|
||||
cheroot_error_filter(orig, 'Client (\'1.2.3.4\', 123) lost - peer '
|
||||
'dropped the TLS connection suddenly, during '
|
||||
'handshake: (8, \'[SSL: SSLV3_ALERT_CERTIFICATE_UNKNOWN] \')')
|
||||
assert calls == []
|
||||
assert any('handshake dropped' in r.message for r in caplog.records)
|
||||
assert all(r.levelno == logging.DEBUG for r in caplog.records)
|
||||
|
||||
def test_plain_http_and_dead_socket_go_to_debug_only(self, caplog):
|
||||
calls = []
|
||||
|
||||
def orig(msg='', level=20, traceback=False):
|
||||
calls.append((msg, level))
|
||||
|
||||
noises = [
|
||||
"Client ('1.2.3.4', 123) attempted to speak plain HTTP into a "
|
||||
"TCP connection configured for TLS-only traffic",
|
||||
'[SSL: HTTP_REQUEST] http request (_ssl.c:1081)',
|
||||
'OSError: [WinError 10038] An operation was attempted on '
|
||||
'something that is not a socket',
|
||||
]
|
||||
with caplog.at_level(logging.DEBUG, logger='app.utils.http_server'):
|
||||
for noise in noises:
|
||||
cheroot_error_filter(orig, noise)
|
||||
assert calls == []
|
||||
assert len([r for r in caplog.records
|
||||
if r.levelno == logging.DEBUG]) == len(noises)
|
||||
|
||||
def test_real_errors_pass_through(self):
|
||||
calls = []
|
||||
|
||||
def orig(msg='', level=20, traceback=False):
|
||||
calls.append((msg, level, traceback))
|
||||
|
||||
cheroot_error_filter(orig, 'socket.error 104', level=30, traceback=True)
|
||||
assert calls == [('socket.error 104', 30, True)]
|
||||
|
||||
|
||||
def _self_signed_pair(tmp_path):
|
||||
import datetime
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.x509.oid import NameOID
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'localhost')])
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now).not_valid_after(now + datetime.timedelta(days=1))
|
||||
.sign(key, hashes.SHA256()))
|
||||
cert_path = tmp_path / 'c.pem'
|
||||
key_path = tmp_path / 'k.pem'
|
||||
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
key_path.write_bytes(key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.TraditionalOpenSSL,
|
||||
serialization.NoEncryption()))
|
||||
return str(cert_path), str(key_path)
|
||||
|
||||
|
||||
class TestBuildServer:
|
||||
def test_timeouts_and_queues(self):
|
||||
server = build_server('127.0.0.1', 0, None)
|
||||
try:
|
||||
assert server.numthreads == 16
|
||||
assert server.timeout == 60
|
||||
assert server.request_queue_size == 128
|
||||
finally:
|
||||
server.stop()
|
||||
|
||||
def test_tls_adapter(self, tmp_path):
|
||||
cert, key = _self_signed_pair(tmp_path)
|
||||
server = build_server('127.0.0.1', 0, None, cert, key)
|
||||
try:
|
||||
assert server.ssl_adapter is not None
|
||||
finally:
|
||||
server.stop()
|
||||
@@ -16,7 +16,7 @@ class FakeSSH:
|
||||
def __init__(self):
|
||||
self.commands = []
|
||||
|
||||
def run(self, command, timeout=30):
|
||||
def run(self, command, timeout=30, quiet=False):
|
||||
self.commands.append(command)
|
||||
return ('ok', '', 0)
|
||||
|
||||
|
||||
@@ -2,10 +2,47 @@
|
||||
|
||||
import pytest
|
||||
|
||||
from app.routes.api import fb_within_roots
|
||||
from app.routes.api import fb_resolve_canonical, fb_within_roots
|
||||
from app.services.backup import is_valid_backup_name
|
||||
|
||||
|
||||
class TestCanonicalResolution:
|
||||
def test_gnu_realpath_m(self):
|
||||
calls = []
|
||||
|
||||
def run(cmd, timeout):
|
||||
calls.append(cmd)
|
||||
return '/srv/sub/../file.txt\n', '', 0
|
||||
|
||||
assert fb_resolve_canonical('/srv/file.txt', '/srv/file.txt', run) == \
|
||||
'/srv/sub/../file.txt'
|
||||
assert calls[0].startswith('realpath -m -- ')
|
||||
|
||||
def test_busybox_falls_back_to_plain_realpath(self):
|
||||
def run(cmd, timeout):
|
||||
if cmd.startswith('realpath -m -- '):
|
||||
return '', 'realpath: -m: No such file or directory', 1
|
||||
assert cmd.startswith('realpath -- ')
|
||||
return '/srv/file.txt\n', '', 0
|
||||
|
||||
assert fb_resolve_canonical('/srv/file.txt', '/srv/file.txt', run) == \
|
||||
'/srv/file.txt'
|
||||
|
||||
def test_missing_binary_falls_back_to_lexical(self):
|
||||
def run(cmd, timeout):
|
||||
return '', 'realpath: command not found', 127
|
||||
|
||||
assert fb_resolve_canonical('/srv/a/../b', '/srv/b', run) == '/srv/b'
|
||||
|
||||
def test_missing_file_without_m_support(self):
|
||||
# New file on BusyBox: plain realpath fails too, lexical wins.
|
||||
def run(cmd, timeout):
|
||||
return '', 'No such file or directory', 1
|
||||
|
||||
assert fb_resolve_canonical('/srv/new.txt', '/srv/new.txt', run) == \
|
||||
'/srv/new.txt'
|
||||
|
||||
|
||||
class TestFileBrowserJail:
|
||||
ROOTS = ['/srv', '/home/dune/.dune']
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Tests for SSH known-hosts persistence (kills the unknown-key warning)."""
|
||||
|
||||
import os
|
||||
|
||||
from app.services import ssh as ssh_module
|
||||
from app.services.ssh import SSHService
|
||||
|
||||
|
||||
class _FakeTransport:
|
||||
def is_active(self):
|
||||
return True
|
||||
|
||||
def set_keepalive(self, interval):
|
||||
pass
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
instances = []
|
||||
|
||||
def __init__(self):
|
||||
self.loaded = []
|
||||
self.saved = []
|
||||
self.connected = False
|
||||
_FakeClient.instances.append(self)
|
||||
|
||||
def load_host_keys(self, path):
|
||||
self.loaded.append(path)
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
def set_missing_host_key_policy(self, policy):
|
||||
pass
|
||||
|
||||
def connect(self, **kwargs):
|
||||
self.connected = True
|
||||
|
||||
def get_transport(self):
|
||||
return _FakeTransport()
|
||||
|
||||
def save_host_keys(self, path):
|
||||
self.saved.append(path)
|
||||
with open(path, 'w') as f:
|
||||
f.write('# test known hosts\n')
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _service(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(ssh_module.paramiko, 'SSHClient', _FakeClient)
|
||||
monkeypatch.setenv('DUNE_KNOWN_HOSTS', str(tmp_path / 'known_hosts'))
|
||||
_FakeClient.instances.clear()
|
||||
return SSHService('example.com', 'dune', ssh_key=None)
|
||||
|
||||
|
||||
class TestKnownHosts:
|
||||
def test_saves_after_connect(self, tmp_path, monkeypatch):
|
||||
svc = _service(monkeypatch, tmp_path)
|
||||
client = svc._get_client()
|
||||
assert client.connected is True
|
||||
assert client.saved == [str(tmp_path / 'known_hosts')]
|
||||
assert os.path.exists(str(tmp_path / 'known_hosts'))
|
||||
|
||||
def test_loads_existing_file(self, tmp_path, monkeypatch):
|
||||
hosts = tmp_path / 'known_hosts'
|
||||
hosts.write_text('# existing\n')
|
||||
svc = _service(monkeypatch, tmp_path)
|
||||
client = svc._get_client()
|
||||
assert client.loaded == [str(hosts)]
|
||||
|
||||
def test_reuses_live_client(self, tmp_path, monkeypatch):
|
||||
svc = _service(monkeypatch, tmp_path)
|
||||
first = svc._get_client()
|
||||
second = svc._get_client()
|
||||
assert first is second
|
||||
assert len(_FakeClient.instances) == 1
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Tests for SSHService.run(quiet=...) - log level only, same results."""
|
||||
|
||||
import logging
|
||||
|
||||
from app.services.ssh import SSHService
|
||||
|
||||
|
||||
class _FakeChannel:
|
||||
def __init__(self, rc):
|
||||
self._rc = rc
|
||||
|
||||
def settimeout(self, timeout):
|
||||
pass
|
||||
|
||||
def recv_exit_status(self):
|
||||
return self._rc
|
||||
|
||||
|
||||
class _FakeStream:
|
||||
def __init__(self, data, rc):
|
||||
self._data = data
|
||||
self.channel = _FakeChannel(rc)
|
||||
|
||||
def read(self):
|
||||
return self._data
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
def __init__(self, out=b'', err=b'Error from server (NotFound)', rc=1):
|
||||
self._out = _FakeStream(out, rc)
|
||||
self._err = _FakeStream(err, rc)
|
||||
|
||||
def get_transport(self):
|
||||
return None
|
||||
|
||||
def exec_command(self, command, timeout=None):
|
||||
return None, self._out, self._err
|
||||
|
||||
|
||||
def _service_with_fake_client():
|
||||
svc = SSHService.__new__(SSHService)
|
||||
import threading
|
||||
svc.host = 'h'
|
||||
svc.user = 'u'
|
||||
svc.ssh_key = None
|
||||
svc._client = _FakeClient()
|
||||
svc._lock = threading.Lock()
|
||||
# Bypass reconnect logic: _get_client returns the fake directly when
|
||||
# its transport check is skipped. Patch at instance level.
|
||||
svc._get_client = lambda: svc._client
|
||||
return svc
|
||||
|
||||
|
||||
class TestQuietFlag:
|
||||
def test_results_identical_quiet_or_not(self, caplog):
|
||||
svc = _service_with_fake_client()
|
||||
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||
out1, err1, rc1 = svc.run('kubectl get x', quiet=False)
|
||||
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||
out2, err2, rc2 = svc.run('kubectl get x', quiet=True)
|
||||
assert (out1, err1, rc1) == (out2, err2, rc2) == ('', 'Error from server (NotFound)', 1)
|
||||
|
||||
def test_loud_logs_warning_quiet_logs_debug(self, caplog):
|
||||
svc = _service_with_fake_client()
|
||||
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||
caplog.clear()
|
||||
svc.run('kubectl get x', quiet=False)
|
||||
loud_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||
caplog.clear()
|
||||
svc.run('kubectl get x', quiet=True)
|
||||
quiet_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||
assert logging.WARNING in loud_levels
|
||||
assert logging.WARNING not in quiet_levels
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Tests for channel-aware self updates (no network - releases are stubbed)."""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.updater import (
|
||||
UpdateService,
|
||||
channel_of,
|
||||
compare_versions,
|
||||
parse_version,
|
||||
release_matches_channel,
|
||||
)
|
||||
|
||||
|
||||
def make_releases():
|
||||
return [
|
||||
{'tag_name': 'v0.7.5-experimental', 'body': 'exp notes',
|
||||
'zipball_url': 'https://example.com/exp.zip'},
|
||||
{'tag_name': 'v0.7.4', 'body': 'stable notes',
|
||||
'zipball_url': 'https://example.com/stable.zip'},
|
||||
{'tag_name': 'v0.7.3-Experimental', 'body': 'old exp',
|
||||
'zipball_url': 'https://example.com/old.zip'},
|
||||
{'tag_name': 'v0.7.3', 'draft': True, 'body': 'draft',
|
||||
'zipball_url': 'https://example.com/draft.zip'},
|
||||
{'tag_name': 'not-a-version', 'body': 'x',
|
||||
'zipball_url': 'https://example.com/x.zip'},
|
||||
]
|
||||
|
||||
|
||||
def make_service(tmp_path, version='0.7.4-experimental'):
|
||||
(tmp_path / 'VERSION').write_text(version + '\n')
|
||||
return UpdateService(str(tmp_path))
|
||||
|
||||
|
||||
class TestVersions:
|
||||
def test_parse(self):
|
||||
assert parse_version('v0.7.5-experimental') == ((0, 7, 5), 'experimental')
|
||||
assert parse_version('0.7.3') == ((0, 7, 3), '')
|
||||
assert parse_version(' v1.2.3 ') == ((1, 2, 3), '')
|
||||
assert parse_version('garbage') is None
|
||||
assert parse_version('') is None
|
||||
assert parse_version(None) is None
|
||||
assert parse_version('1.2') is None
|
||||
|
||||
def test_channel(self):
|
||||
assert channel_of('0.7.5-experimental') == 'experimental'
|
||||
assert channel_of('0.7.5-Experimental') == 'experimental'
|
||||
assert channel_of('0.7.3') == 'stable'
|
||||
assert channel_of('garbage') == 'stable'
|
||||
|
||||
def test_compare(self):
|
||||
assert compare_versions('0.7.5-experimental', '0.7.4-experimental') > 0
|
||||
assert compare_versions('0.7.4', '0.7.4') == 0
|
||||
assert compare_versions('0.7.3', '0.7.4') < 0
|
||||
assert compare_versions('0.7.10', '0.7.9') > 0
|
||||
assert compare_versions('garbage', '0.7.4') < 0
|
||||
|
||||
def test_channel_match(self):
|
||||
assert release_matches_channel('v0.7.5-experimental', 'experimental')
|
||||
assert release_matches_channel('v0.7.3-Experimental', 'experimental')
|
||||
assert not release_matches_channel('v0.7.4', 'experimental')
|
||||
assert release_matches_channel('v0.7.4', 'stable')
|
||||
assert not release_matches_channel('v0.7.5-experimental', 'stable')
|
||||
|
||||
|
||||
class TestPickLatest:
|
||||
def test_experimental_picks_max_experimental(self):
|
||||
best = UpdateService._pick_latest(make_releases(), 'experimental')
|
||||
assert best['version'] == '0.7.5-experimental'
|
||||
|
||||
def test_stable_ignores_drafts(self):
|
||||
best = UpdateService._pick_latest(make_releases(), 'stable')
|
||||
assert best['version'] == '0.7.4'
|
||||
|
||||
def test_nothing_matching(self):
|
||||
assert UpdateService._pick_latest([], 'stable') is None
|
||||
|
||||
|
||||
class TestReleaseLists:
|
||||
def test_collect_channel_newest_first(self):
|
||||
releases = UpdateService._collect_channel(make_releases(), 'experimental')
|
||||
assert [e['version'] for e in releases] == [
|
||||
'0.7.5-experimental', '0.7.3-Experimental']
|
||||
|
||||
def test_collect_skips_drafts_and_garbage(self):
|
||||
releases = UpdateService._collect_channel(make_releases(), 'stable')
|
||||
assert [e['version'] for e in releases] == ['0.7.4']
|
||||
|
||||
def test_status_includes_lists_and_find_searches_them(self, tmp_path, monkeypatch):
|
||||
svc = make_service(tmp_path, '0.7.4-experimental')
|
||||
monkeypatch.setattr(svc, '_fetch_releases', make_releases)
|
||||
svc.check_for_updates()
|
||||
status = svc.status()
|
||||
assert [e['version'] for e in status['releases']['experimental']] == [
|
||||
'0.7.5-experimental', '0.7.3-Experimental']
|
||||
assert [e['version'] for e in status['releases']['stable']] == ['0.7.4']
|
||||
# list payload stays lean (no download URLs for the panel)
|
||||
assert 'zipball_url' not in status['releases']['experimental'][0]
|
||||
# an older (non-latest) version is known but refused as a downgrade
|
||||
assert svc._find_release('0.7.3-Experimental')['tag'] == 'v0.7.3-Experimental'
|
||||
ok, msg = svc.apply_update('0.7.3-Experimental')
|
||||
assert ok is False
|
||||
assert 'owngrade' in msg or 'older' in msg
|
||||
|
||||
def test_cross_channel_same_number_is_reinstall(self, tmp_path, monkeypatch):
|
||||
# Stable 0.7.4 installing experimental 0.7.4 is numeric-equal:
|
||||
# allowed past validation (fails later only on download).
|
||||
svc = make_service(tmp_path, '0.7.4')
|
||||
monkeypatch.setattr(svc, '_fetch_releases', lambda: [
|
||||
{'tag_name': 'v0.7.4-experimental', 'body': 'x',
|
||||
'zipball_url': 'https://example.com/x.zip'},
|
||||
])
|
||||
svc.check_for_updates()
|
||||
ok, msg = svc.apply_update('0.7.4-experimental')
|
||||
assert ok is False
|
||||
assert 'owngrade' not in msg and 'Unknown version' not in msg
|
||||
|
||||
|
||||
class TestApplyRules:
|
||||
def test_refuses_downgrade_without_network(self, tmp_path):
|
||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||
svc._latest = {'version': '0.7.6-experimental', 'tag': 'v0.7.6-experimental',
|
||||
'notes': '', 'zipball_url': 'https://example.com/x.zip'}
|
||||
ok, msg = svc.apply_update('0.7.4-experimental')
|
||||
assert ok is False
|
||||
assert 'owngrade' in msg or 'older' in msg
|
||||
assert svc._update_in_progress is False
|
||||
|
||||
def test_refuses_unknown_version(self, tmp_path, monkeypatch):
|
||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||
monkeypatch.setattr(svc, '_fetch_releases', lambda: [])
|
||||
ok, msg = svc.apply_update('9.9.9')
|
||||
assert ok is False
|
||||
assert 'Unknown version' in msg
|
||||
|
||||
def test_refuses_garbage(self, tmp_path):
|
||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||
ok, msg = svc.apply_update('not-a-version!!!')
|
||||
assert ok is False
|
||||
|
||||
def test_same_version_allowed_to_proceed(self, tmp_path, monkeypatch):
|
||||
# Same version = reinstall. Must get past validation (it will then
|
||||
# fail downloading from example.com, which proves the rule passed).
|
||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||
svc._latest = {'version': '0.7.5-experimental', 'tag': 'v0.7.5-experimental',
|
||||
'notes': '', 'zipball_url': 'https://example.com/x.zip'}
|
||||
ok, msg = svc.apply_update('0.7.5-experimental')
|
||||
assert ok is False
|
||||
assert 'owngrade' not in msg and 'Unknown version' not in msg
|
||||
|
||||
|
||||
class TestPreview:
|
||||
def test_set_clear_and_reject_garbage(self, tmp_path):
|
||||
svc = make_service(tmp_path)
|
||||
preview = svc.set_preview('0.7.6-experimental', 'notes here')
|
||||
assert preview == {'version': '0.7.6-experimental', 'notes': 'notes here'}
|
||||
assert svc.status()['preview'] == preview
|
||||
svc.clear_preview()
|
||||
assert svc.status()['preview'] is None
|
||||
with pytest.raises(ValueError):
|
||||
svc.set_preview('garbage!!!')
|
||||
|
||||
|
||||
class TestSilence:
|
||||
def test_round_trip(self, tmp_path):
|
||||
svc = make_service(tmp_path)
|
||||
state = svc.silence_version('0.7.6-experimental')
|
||||
assert state['silenced_versions'] == ['0.7.6-experimental']
|
||||
assert svc.get_silence() == state
|
||||
state = svc.unsilence_version('0.7.6-experimental')
|
||||
assert state['silenced_versions'] == []
|
||||
state = svc.set_silence_all(True)
|
||||
assert state['silence_all'] is True
|
||||
state = svc.clear_silence()
|
||||
assert state == {'silenced_versions': [], 'silence_all': False}
|
||||
|
||||
def test_status_reports_available_and_silence(self, tmp_path):
|
||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
||||
svc._latest = {'version': '0.7.6-experimental', 'tag': 'v0.7.6-experimental',
|
||||
'notes': 'n', 'zipball_url': 'u'}
|
||||
svc._other_latest = None
|
||||
status = svc.status()
|
||||
assert status['available'] is True
|
||||
assert status['latest']['version'] == '0.7.6-experimental'
|
||||
assert status['current_version'] == '0.7.5-experimental'
|
||||
assert status['channel'] == 'experimental'
|
||||
|
||||
|
||||
class TestLocalVersion:
|
||||
def test_reads_version_file(self, tmp_path):
|
||||
svc = make_service(tmp_path, '0.7.3')
|
||||
assert svc.current_version == '0.7.3'
|
||||
assert svc.channel == 'stable'
|
||||
|
||||
def test_missing_file_falls_back(self, tmp_path):
|
||||
svc = UpdateService(str(tmp_path))
|
||||
assert svc.current_version == '0.0.0'
|
||||
Reference in new issue
Block a user