diff --git a/app/app.py b/app/app.py index d2f1571..47da364 100644 --- a/app/app.py +++ b/app/app.py @@ -2,6 +2,7 @@ import asyncio import hmac +import ipaddress import json import io import os @@ -12,6 +13,7 @@ import socket import threading import time import zipfile +from collections import deque from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -129,6 +131,24 @@ def _read_meminfo(): return info +def _public_ip(): + """The address players connect to: PUBLIC_IP if set, else the source address of the default route + (gsm runs on the host network). None behind NAT; the UI then falls back to the page's hostname.""" + if os.environ.get("PUBLIC_IP"): + return os.environ["PUBLIC_IP"] + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("1.1.1.1", 80)) # UDP: picks a route, sends nothing + ip = s.getsockname()[0] + return ip if ipaddress.ip_address(ip).is_global else None + except OSError: + return None + + +PUBLIC_IP = _public_ip() +NET_HISTORY = 100 # samples (one per 3 s) kept for the VPS network graphs + + def _read_net(): rx = tx = 0 for line in Path("/proc/net/dev").read_text().splitlines()[2:]: @@ -323,6 +343,7 @@ def stats_loop(): prev_cpu = _read_cpu() prev_net = _read_net() prev_t = time.time() + net_history = deque(maxlen=NET_HISTORY) pool = ThreadPoolExecutor(max_workers=8) while True: time.sleep(3) @@ -336,6 +357,7 @@ def stats_loop(): rx, tx = _read_net() now = time.time() dt = now - prev_t + net_history.append([round((rx - prev_net[0]) / dt), round((tx - prev_net[1]) / dt)]) host = { "cpu_percent": round(cpu_pct, 1), "cpu_count": os.cpu_count(), @@ -347,6 +369,8 @@ def stats_loop(): "disk_used": du.used, "net_rx_rate": (rx - prev_net[0]) / dt, "net_tx_rate": (tx - prev_net[1]) / dt, + "net_history": list(net_history), # [[rx, tx] bytes/s], oldest first + "public_ip": PUBLIC_IP, } prev_net, prev_t = (rx, tx), now diff --git a/app/static/app.js b/app/static/app.js index 425b93d..c743eb6 100644 --- a/app/static/app.js +++ b/app/static/app.js @@ -89,7 +89,28 @@ function renderHost() { setBar('#b-swap', h.swap_total ? (100 * h.swap_used) / h.swap_total : 0); $('#m-disk').textContent = `${fmtBytes(h.disk_used)} / ${fmtBytes(h.disk_total)}`; setBar('#b-disk', (100 * h.disk_used) / h.disk_total); - $('#m-net').textContent = `Network: ↓ ${fmtRate(h.net_rx_rate)} ↑ ${fmtRate(h.net_tx_rate)}`; + $('#m-rx').textContent = fmtRate(h.net_rx_rate); + $('#m-tx').textContent = fmtRate(h.net_tx_rate); + const hist = h.net_history || []; + drawGraph('#g-rx', hist.map((x) => x[0])); + drawGraph('#g-tx', hist.map((x) => x[1])); +} + +// Area graph of the last NET_HISTORY samples (app.py), right-aligned so it fills in from the right after a +// restart. Each graph scales to its own peak, shown in the tooltip. +const GRAPH_POINTS = 100; +function drawGraph(id, vals) { + const svg = $(id); + const peak = Math.max(1, ...vals); + const step = 100 / (GRAPH_POINTS - 1); + const x0 = 100 - (vals.length - 1) * step; + const pts = vals.map((v, i) => `${(x0 + i * step).toFixed(2)},${(24 - (22 * v) / peak).toFixed(2)}`); + const line = pts.length > 1 ? `M${pts.join('L')}` : ''; + svg.querySelector('.line').setAttribute('d', line); + svg.querySelector('.area').setAttribute('d', line && `${line}L100,24L${x0.toFixed(2)},24Z`); + let title = svg.querySelector('title'); + if (!title) title = svg.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'title')); + title.textContent = `Peak ${fmtRate(peak)} in the last ${(GRAPH_POINTS * 3) / 60} minutes`; } function fmtDuration(sec) { @@ -149,11 +170,27 @@ function timeAgo(iso) { return `on ${t.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}`; } +// The server address on each card copies itself when clicked. Cards re-render every poll, so the +// "Copied!" state is kept here rather than on the element. +let copied = { addr: null, text: '' }; +let copiedTimer = null; +const copyAddr = (addr) => ``; + +async function copyToClipboard(addr) { + let text = 'Copied!'; + try { await navigator.clipboard.writeText(addr); } catch { text = 'Copy failed'; } + copied = { addr, text }; + renderServers(); + clearTimeout(copiedTimer); + copiedTimer = setTimeout(() => { copied = { addr: null, text: '' }; renderServers(); }, 1500); +} + const STATE_LABEL = { online: 'Online', starting: 'Starting…', exited: 'Stopped', created: 'Stopped', restarting: 'Restarting…' }; function renderServers() { $('#empty-msg').classList.toggle('hidden', servers.length > 0); - const host = location.hostname; + const host = stats.host.public_ip || location.hostname; $('#server-list').innerHTML = servers.map((s) => { const st = stats.servers[s.id]; const running = s.state === 'online' || s.state === 'starting'; @@ -167,7 +204,7 @@ function renderServers() {