diff --git a/.gitignore b/.gitignore index 12fbce2..c6d1e9b 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/VERSION b/VERSION index 972ef76..5b209ea 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.7.9 +0.7.10 diff --git a/app/factory.py b/app/factory.py index 496b773..939dd62 100644 --- a/app/factory.py +++ b/app/factory.py @@ -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) @@ -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', diff --git a/app/routes/main.py b/app/routes/main.py index 058eb43..4acfa25 100644 --- a/app/routes/main.py +++ b/app/routes/main.py @@ -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') diff --git a/app/services/chat.py b/app/services/chat.py index 0aaf489..7a1d2f9 100644 --- a/app/services/chat.py +++ b/app/services/chat.py @@ -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}") diff --git a/app/services/player.py b/app/services/player.py index cef09e5..ed1d4a8 100644 --- a/app/services/player.py +++ b/app/services/player.py @@ -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): diff --git a/app/services/ssh.py b/app/services/ssh.py index 4d6874d..b9ebd12 100644 --- a/app/services/ssh.py +++ b/app/services/ssh.py @@ -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) diff --git a/app/utils/events.py b/app/utils/events.py new file mode 100644 index 0000000..df820cc --- /dev/null +++ b/app/utils/events.py @@ -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 " 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 diff --git a/app/utils/http_server.py b/app/utils/http_server.py index 982fc0d..d417ca9 100644 --- a/app/utils/http_server.py +++ b/app/utils/http_server.py @@ -10,13 +10,19 @@ import logging logger = logging.getLogger(__name__) -# Fragments identifying a peer that vanished mid-handshake (typically an -# internet scanner hitting the public HTTPS port). Never real failures. +# 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', ) diff --git a/app/utils/watchdog.py b/app/utils/watchdog.py index 679e910..ec74b29 100644 --- a/app/utils/watchdog.py +++ b/app/utils/watchdog.py @@ -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 ' diff --git a/run.py b/run.py index c62b743..545f943 100644 --- a/run.py +++ b/run.py @@ -118,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 diff --git a/static/style.css b/static/style.css index 4d8fd73..0ad4892 100644 --- a/static/style.css +++ b/static/style.css @@ -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; @@ -1444,3 +1449,44 @@ body[data-nav-layout="vertical"] .update-banner .ub-panel { 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%; +} diff --git a/templates/backup.html b/templates/backup.html index 5f87e2a..dedc73c 100644 --- a/templates/backup.html +++ b/templates/backup.html @@ -46,7 +46,7 @@
Scheduled Backups - +
@@ -72,13 +72,13 @@
+ style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;"> days + style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;"> hours + style="width:60px;padding:6px 8px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;"> mins
@@ -123,12 +123,12 @@
+ style="width:100%;padding:6px 8px;background:var(--card-bg);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;">
@@ -152,7 +152,7 @@
Select Backup
- @@ -201,15 +201,15 @@ -
+
Backup password (if encrypted)
+ style="width:100%;padding:8px 10px;background:var(--card-bg);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
@@ -231,7 +231,7 @@
- + @@ -354,7 +354,7 @@ async function loadBackups() { container.innerHTML = '

No backups found. Click "Create Backup" to create one.

'; return; } - let html = '
'; + let html = '
'; html += '
'; html += '
Name
Created
Size
Actions
'; 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 = '' + div.innerHTML = '' + ''; 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 = '' + div.innerHTML = '' + ''; 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 = '
'; + let html = '
'; html += 'Backup contents:
'; html += 'Created: ' + esc(d.created) + '
'; const comps = d.components || []; diff --git a/templates/chat.html b/templates/chat.html index 793c80c..69c9440 100644 --- a/templates/chat.html +++ b/templates/chat.html @@ -18,7 +18,7 @@ - diff --git a/templates/director.html b/templates/director.html index cad4d32..4284d39 100644 --- a/templates/director.html +++ b/templates/director.html @@ -85,7 +85,7 @@
- diff --git a/templates/events.html b/templates/events.html index 0d2a8c6..6ca2c56 100644 --- a/templates/events.html +++ b/templates/events.html @@ -4,8 +4,7 @@ {% if tunnel_down %} @@ -14,56 +13,179 @@
Database Error: {{ db_error }}
{% else %} -
-
-
Game Events ({{ game_events|length }})
+
+
+
Events (24h)
+
{{ total_24h }}
+
+
+
Deaths (24h)
+
{{ counts_24h.get(0, 0) }}
+
+
+
Builds Placed (24h)
+
{{ counts_24h.get(10, 0) }}
+
+
+
Permission Changes (24h)
+
{{ counts_24h.get(97, 0) }}
+
+
+
Active Maps
+
{{ maps|length }}
+
+
+ +
+
Event Feed
+
+
+ + + + + Reset +
- + + + + {% for e in game_events[:25] %} + + + + + + + + {% else %} + + {% endfor %} + +
TimeActorMapTypePlayerPosition
TimeEventMapDetailsPosition
{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}{{ e.label }}{{ e.map or '' }}{{ e.summary or '-' }}{% if e.x is not none and e.y is not none %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}{% endif %}
No events match these filters
+
+ {% if game_events|length > 25 %} +
+ +
+ {% endif %} +
+
+ +