v0.7.10: events tab rework, quieter logs, known hosts, dropdown theme fixes
This commit is contained in:
1 parent
97cdbd3027
commit
91c7abc771
24 files changed
+740
-103
No files matched your search
+27
-1
@@ -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',
|
||||
|
||||
+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')
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -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',
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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 '
|
||||
|
||||
Reference in new issue
Block a user