Show the server's public IP with click to copy, and VPS network graphs
Cards show the VPS's public IP (PUBLIC_IP, else the default route's source address) instead of the page's hostname; clicking the address copies it. VPS resources gets stacked download/upload graphs of the last 5 minutes, kept server side. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
cb9a6d1970
commit
3ae03160e8
4 changed files with 93 additions and 5 deletions
24
app/app.py
24
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
|
||||
|
||||
|
|
|
|||
|
|
@ -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) => `<button type="button" class="copy-addr" data-addr="${esc(addr)}" data-tip="${
|
||||
copied.addr === addr ? esc(copied.text) : 'Click to copy'}">${esc(addr)}</button>`;
|
||||
|
||||
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() {
|
|||
<div class="server-top">
|
||||
<div>
|
||||
<div class="server-name">${esc(s.server_name)}<span class="badge ${badgeCls}">${isBusy ? 'Working…' : s.busy ? esc(s.busy) : STATE_LABEL[s.state] || esc(s.state)}</span></div>
|
||||
<div class="server-meta">${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world <b>${esc(s.world)}</b>`} · connect to <b>${esc(host)}:${s.port}</b></div>
|
||||
<div class="server-meta">${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world <b>${esc(s.world)}</b>`} · connect to ${copyAddr(`${host}:${s.port}`)}</div>
|
||||
${running ? playersLine(st) : s.last_online ? `<div class="server-last-online" title="${esc(new Date(s.last_online).toLocaleString())}">Last online ${esc(timeAgo(s.last_online))}</div>` : ''}
|
||||
</div>
|
||||
<div class="server-actions">
|
||||
|
|
@ -190,6 +227,8 @@ function renderServers() {
|
|||
}
|
||||
|
||||
$('#server-list').addEventListener('click', async (e) => {
|
||||
const addr = e.target.closest('.copy-addr');
|
||||
if (addr) return copyToClipboard(addr.dataset.addr);
|
||||
const btn = e.target.closest('button[data-act]');
|
||||
if (!btn) return;
|
||||
const card = btn.closest('.server');
|
||||
|
|
|
|||
|
|
@ -42,8 +42,13 @@
|
|||
<div class="meter"><div class="meter-label"><span>Memory</span><span id="m-mem">–</span></div><div class="bar"><div id="b-mem"></div></div></div>
|
||||
<div class="meter"><div class="meter-label"><span>Swap</span><span id="m-swap">–</span></div><div class="bar"><div id="b-swap"></div></div></div>
|
||||
<div class="meter"><div class="meter-label"><span>Disk</span><span id="m-disk">–</span></div><div class="bar"><div id="b-disk"></div></div></div>
|
||||
<div class="meter net-meter">
|
||||
<div class="meter-label"><span>Download</span><span id="m-rx">–</span></div>
|
||||
<svg class="graph rx" id="g-rx" viewBox="0 0 100 24" preserveAspectRatio="none"><path class="area"/><path class="line"/></svg>
|
||||
<div class="meter-label graph-gap"><span>Upload</span><span id="m-tx">–</span></div>
|
||||
<svg class="graph tx" id="g-tx" viewBox="0 0 100 24" preserveAspectRatio="none"><path class="area"/><path class="line"/></svg>
|
||||
</div>
|
||||
</div>
|
||||
<p class="net" id="m-net"></p>
|
||||
</div>
|
||||
|
||||
<h2 class="section-title">Servers</h2>
|
||||
|
|
|
|||
|
|
@ -80,7 +80,15 @@ a { color: var(--accent); }
|
|||
.meter-label span:last-child { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.bar { height: 8px; background: var(--bar); border-radius: 4px; overflow: hidden; }
|
||||
.bar > div { height: 100%; width: 0; background: var(--ok); transition: width .5s, background .5s; }
|
||||
.net { margin: 12px 0 0; font-size: 13px; color: var(--muted); }
|
||||
.net-meter { grid-column: 1 / -1; }
|
||||
.graph { display: block; width: 100%; height: 24px; background: var(--bar); border-radius: 4px; }
|
||||
.graph .line { fill: none; stroke-width: 1.5; vector-effect: non-scaling-stroke; }
|
||||
.graph .area { stroke: none; opacity: .25; }
|
||||
.graph.rx .line { stroke: var(--ok); }
|
||||
.graph.rx .area { fill: var(--ok); }
|
||||
.graph.tx .line { stroke: #79c0ff; }
|
||||
.graph.tx .area { fill: #79c0ff; }
|
||||
.graph-gap { margin-top: 8px; }
|
||||
|
||||
.section-title { margin: 24px 0 12px; }
|
||||
.empty { color: var(--muted); text-align: center; padding: 24px; }
|
||||
|
|
@ -94,6 +102,18 @@ a { color: var(--accent); }
|
|||
.server-top { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: flex-start; }
|
||||
.server-name { font-weight: 600; font-size: 16px; }
|
||||
.server-meta { color: var(--muted); font-size: 13px; }
|
||||
.copy-addr {
|
||||
font: inherit; font-weight: 600; color: var(--text); background: none; border: 0; padding: 0; border-radius: 0;
|
||||
text-decoration: underline; text-underline-offset: 2px; cursor: pointer; position: relative;
|
||||
}
|
||||
.copy-addr::after {
|
||||
content: attr(data-tip); position: absolute; left: 50%; bottom: calc(100% + 6px); transform: translateX(-50%);
|
||||
background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 6px;
|
||||
padding: 3px 8px; font-size: 12px; font-weight: normal; white-space: nowrap; pointer-events: none;
|
||||
opacity: 0; transition: opacity .15s;
|
||||
}
|
||||
.copy-addr:hover::after, .copy-addr:focus-visible::after, .copy-addr[data-tip="Copied!"]::after,
|
||||
.copy-addr[data-tip="Copy failed"]::after { opacity: 1; }
|
||||
.badge { display: inline-block; font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid currentColor; margin-left: 6px; vertical-align: 2px; }
|
||||
.badge.online { color: var(--ok); }
|
||||
.badge.starting { color: var(--warn); }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue