400 lines
14 KiB
JavaScript
400 lines
14 KiB
JavaScript
/* Admin /status monitoring client.
|
|
*
|
|
* - Opens the existing socket.io connection, joins the admin-only "monitor"
|
|
* room, and renders live bars (CPU/RAM/Storage/Network/RPS) once per second
|
|
* while the page is open.
|
|
* - Renders a fixed one-month calendar; clicking a day fetches that day's
|
|
* per-minute history via REST and draws it into the graph. Default view is
|
|
* today.
|
|
* - Everything here is read-only and admin-gated server-side.
|
|
*/
|
|
(function () {
|
|
"use strict";
|
|
|
|
var SOCKET = null;
|
|
var watching = false;
|
|
|
|
// ---- helpers -----------------------------------------------------------
|
|
function $(id) { return document.getElementById(id); }
|
|
|
|
function clampPct(n) {
|
|
n = Number(n);
|
|
if (!isFinite(n) || n < 0) return 0;
|
|
if (n > 100) return 100;
|
|
return n;
|
|
}
|
|
|
|
function fmtBytesPerSec(bps) {
|
|
bps = Number(bps) || 0;
|
|
var units = ["B/s", "KB/s", "MB/s", "GB/s"];
|
|
var i = 0;
|
|
while (bps >= 1024 && i < units.length - 1) { bps /= 1024; i++; }
|
|
return (bps < 10 ? bps.toFixed(1) : Math.round(bps)) + " " + units[i];
|
|
}
|
|
|
|
function fmtUptime(ms) {
|
|
var s = Math.floor((Number(ms) || 0) / 1000);
|
|
var d = Math.floor(s / 86400); s -= d * 86400;
|
|
var h = Math.floor(s / 3600); s -= h * 3600;
|
|
var m = Math.floor(s / 60); s -= m * 60;
|
|
var parts = [];
|
|
if (d) parts.push(d + "d");
|
|
if (h || d) parts.push(h + "h");
|
|
parts.push(m + "m");
|
|
parts.push(s + "s");
|
|
return parts.join(" ");
|
|
}
|
|
|
|
// ---- bar rendering -----------------------------------------------------
|
|
function setBar(key, percent, valueText) {
|
|
var fill = document.querySelector('[data-bar-fill="' + key + '"]');
|
|
var pctEl = document.querySelector('[data-bar-pct="' + key + '"]');
|
|
var valEl = document.querySelector('[data-bar-value="' + key + '"]');
|
|
var p = clampPct(percent);
|
|
|
|
// Update circular ring progress
|
|
if (fill) {
|
|
var circumference = 2 * Math.PI * 15.9155;
|
|
var offset = circumference - (p / 100) * circumference;
|
|
fill.style.strokeDasharray = p + ', 100';
|
|
}
|
|
|
|
if (pctEl) pctEl.textContent = p.toFixed(1) + "%";
|
|
if (valEl && valueText != null) valEl.textContent = valueText;
|
|
}
|
|
|
|
// Network bars are scaled relative to a rolling observed peak so the bar is
|
|
// meaningful even without a hard cap. The peak decays toward the floor on
|
|
// every sample (~1min half-life at the 1s sample cadence) so a single burst
|
|
// doesn't flatten the ring for the rest of the session; sustained traffic
|
|
// keeps the peak pinned at its own level.
|
|
var NET_PEAK_FLOOR = 1024 * 256; // bytes/s lower bound for the scale
|
|
var NET_PEAK_DECAY = 0.99; // per-sample peak multiplier
|
|
var netPeak = { rx: NET_PEAK_FLOOR, tx: NET_PEAK_FLOOR };
|
|
function netPercent(dir, bps) {
|
|
bps = Number(bps) || 0;
|
|
var peak = netPeak[dir] * NET_PEAK_DECAY;
|
|
if (peak < NET_PEAK_FLOOR) peak = NET_PEAK_FLOOR;
|
|
if (bps > peak) peak = bps;
|
|
netPeak[dir] = peak;
|
|
return (bps / peak) * 100;
|
|
}
|
|
|
|
function applySample(s) {
|
|
if (!s) return;
|
|
setBar("cpu", s.cpu, (Number(s.cpu) || 0).toFixed(1) + "% of " + (s.cores || 1) + " cores");
|
|
setBar("mem", s.memPercent, bytesPair(s.memUsed, s.memTotal));
|
|
setBar("disk", s.diskPercent != null ? s.diskPercent : 0,
|
|
s.diskUsed != null ? bytesPair(s.diskUsed, s.diskTotal) : "n/a");
|
|
if (s.netRx != null) setBar("netrx", netPercent("rx", s.netRx), fmtBytesPerSec(s.netRx));
|
|
if (s.netTx != null) setBar("nettx", netPercent("tx", s.netTx), fmtBytesPerSec(s.netTx));
|
|
|
|
var rpsEl = $("metricRps");
|
|
if (rpsEl) rpsEl.textContent = (Number(s.rps) || 0).toFixed(1);
|
|
var upEl = $("metricUptime");
|
|
if (upEl && s.uptimeMs != null) upEl.textContent = fmtUptime(s.uptimeMs);
|
|
|
|
if (s.services) applyServices(s.services);
|
|
pushLive(s);
|
|
}
|
|
|
|
function bytesPair(used, total) {
|
|
return fmtBytes(used) + " / " + fmtBytes(total);
|
|
}
|
|
function fmtBytes(b) {
|
|
b = Number(b) || 0;
|
|
var units = ["B", "KB", "MB", "GB", "TB"];
|
|
var i = 0;
|
|
while (b >= 1024 && i < units.length - 1) { b /= 1024; i++; }
|
|
return (b < 10 ? b.toFixed(1) : Math.round(b)) + " " + units[i];
|
|
}
|
|
|
|
// ---- services ----------------------------------------------------------
|
|
function dot(ok) { return ok ? "ok" : "bad"; }
|
|
function applyServices(sv) {
|
|
var db = $("svcDatabase");
|
|
if (db) {
|
|
db.dataset.state = dot(sv.database && sv.database.ok);
|
|
var lat = sv.database && sv.database.latencyMs != null ? sv.database.latencyMs + "ms" : "offline";
|
|
var dbv = $("svcDatabaseVal"); if (dbv) dbv.textContent = lat;
|
|
}
|
|
setSvcText("svcNodes", sv.nodes ? (sv.nodes.online + "/" + sv.nodes.total + " online") : "n/a",
|
|
sv.nodes && sv.nodes.total > 0 && sv.nodes.online === sv.nodes.total);
|
|
// Real state, not a hardcoded "ok": stopped containers flag the row the
|
|
// same way offline nodes do, and a missing payload (probe failure or an
|
|
// older panel build) must not render green. "0 connected" is also flagged:
|
|
// anyone viewing this page live is a socket themselves, so a zero count
|
|
// means the realtime layer is down and the page is on REST fallback.
|
|
setSvcText("svcContainers",
|
|
sv.containers ? (sv.containers.running + " running, " + sv.containers.stopped + " stopped") : "n/a",
|
|
!!sv.containers && sv.containers.stopped === 0);
|
|
setSvcText("svcSsh",
|
|
sv.sshSessions != null ? sv.sshSessions + " active" : "n/a",
|
|
sv.sshSessions != null);
|
|
setSvcText("svcSockets",
|
|
sv.activeSockets != null ? sv.activeSockets + " connected" : "n/a",
|
|
Number(sv.activeSockets) > 0);
|
|
var ver = $("svcVersion");
|
|
if (ver && sv.panelVersion) ver.textContent = sv.panelVersion;
|
|
}
|
|
function setSvcText(id, text, ok) {
|
|
var el = $(id);
|
|
if (!el) return;
|
|
el.textContent = text;
|
|
var row = el.closest("[data-svc-row]");
|
|
if (row) row.dataset.state = ok ? "ok" : "warn";
|
|
}
|
|
|
|
// ---- live sparkline buffer (current day, client-side) ------------------
|
|
var liveBuffer = [];
|
|
function pushLive(s) {
|
|
liveBuffer.push({ ts: s.ts, cpu: s.cpu, mem: s.memPercent });
|
|
if (liveBuffer.length > 600) liveBuffer.shift();
|
|
}
|
|
|
|
// ---- history graph -----------------------------------------------------
|
|
var graphMode = "today"; // or a YYYY-MM-DD string
|
|
// Last drawn day, kept so a resize can re-render at the new canvas size
|
|
// without refetching /api/status/metrics/day.
|
|
var lastGraphPoints = null;
|
|
var lastGraphLabel = "";
|
|
function drawGraph(points, label) {
|
|
lastGraphPoints = points || null;
|
|
lastGraphLabel = label || "";
|
|
var canvas = $("metricsGraph");
|
|
if (!canvas) return;
|
|
var ctx = canvas.getContext("2d");
|
|
var w = canvas.width = canvas.clientWidth * (window.devicePixelRatio || 1);
|
|
var h = canvas.height = canvas.clientHeight * (window.devicePixelRatio || 1);
|
|
ctx.clearRect(0, 0, w, h);
|
|
var lbl = $("graphLabel");
|
|
if (lbl) lbl.textContent = label || "";
|
|
|
|
if (!points || !points.length) {
|
|
ctx.fillStyle = "rgba(255,255,255,0.35)";
|
|
ctx.font = (14 * (window.devicePixelRatio || 1)) + "px system-ui";
|
|
ctx.textAlign = "center";
|
|
ctx.fillText("No data recorded for this day yet", w / 2, h / 2);
|
|
return;
|
|
}
|
|
|
|
var pad = 8 * (window.devicePixelRatio || 1);
|
|
function line(series, color) {
|
|
ctx.beginPath();
|
|
for (var i = 0; i < points.length; i++) {
|
|
var x = pad + (i / (points.length - 1 || 1)) * (w - pad * 2);
|
|
var v = clampPct(points[i][series]);
|
|
var y = h - pad - (v / 100) * (h - pad * 2);
|
|
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
|
}
|
|
ctx.strokeStyle = color;
|
|
ctx.lineWidth = 2 * (window.devicePixelRatio || 1);
|
|
ctx.lineJoin = "round";
|
|
ctx.stroke();
|
|
}
|
|
// gridlines
|
|
ctx.strokeStyle = "rgba(255,255,255,0.06)";
|
|
ctx.lineWidth = 1;
|
|
for (var g = 0; g <= 4; g++) {
|
|
var gy = pad + (g / 4) * (h - pad * 2);
|
|
ctx.beginPath(); ctx.moveTo(pad, gy); ctx.lineTo(w - pad, gy); ctx.stroke();
|
|
}
|
|
line("cpu", "#0EA5E9");
|
|
line("mem", "#8B5CF6");
|
|
}
|
|
|
|
function loadDay(dayStr) {
|
|
fetch("/api/status/metrics/day?day=" + encodeURIComponent(dayStr), { credentials: "include" })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (data) {
|
|
if (!data || !data.ok) { drawGraph([], dayStr); return; }
|
|
drawGraph(data.points, formatDayLabel(dayStr));
|
|
})
|
|
.catch(function () { drawGraph([], dayStr); });
|
|
}
|
|
|
|
function formatDayLabel(dayStr) {
|
|
try {
|
|
var d = new Date(dayStr + "T00:00:00Z");
|
|
return d.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
|
|
} catch (_) { return dayStr; }
|
|
}
|
|
|
|
// ---- calendar (fixed one month) ----------------------------------------
|
|
function buildCalendar(summaryDays) {
|
|
var grid = $("calendarGrid");
|
|
if (!grid) return;
|
|
grid.innerHTML = "";
|
|
|
|
var now = new Date();
|
|
var year = now.getUTCFullYear();
|
|
var month = now.getUTCMonth();
|
|
var first = new Date(Date.UTC(year, month, 1));
|
|
var daysInMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
|
|
var startWeekday = first.getUTCDay(); // 0=Sun
|
|
|
|
var monthLabel = $("calendarMonth");
|
|
if (monthLabel) {
|
|
monthLabel.textContent = first.toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" });
|
|
}
|
|
|
|
var summaryByDay = {};
|
|
(summaryDays || []).forEach(function (d) {
|
|
var key = new Date(d.ts).toISOString().slice(0, 10);
|
|
summaryByDay[key] = d;
|
|
});
|
|
|
|
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
weekdays.forEach(function (wd) {
|
|
var head = document.createElement("div");
|
|
head.className = "cal-weekday";
|
|
head.textContent = wd;
|
|
grid.appendChild(head);
|
|
});
|
|
|
|
for (var i = 0; i < startWeekday; i++) {
|
|
var blank = document.createElement("div");
|
|
blank.className = "cal-cell cal-cell--blank";
|
|
grid.appendChild(blank);
|
|
}
|
|
|
|
var todayKey = now.toISOString().slice(0, 10);
|
|
for (var day = 1; day <= daysInMonth; day++) {
|
|
(function (day) {
|
|
var dateStr = year + "-" + String(month + 1).padStart(2, "0") + "-" + String(day).padStart(2, "0");
|
|
var cell = document.createElement("button");
|
|
cell.type = "button";
|
|
cell.className = "cal-cell";
|
|
cell.dataset.day = dateStr;
|
|
if (dateStr === todayKey) cell.classList.add("cal-cell--today");
|
|
|
|
var num = document.createElement("span");
|
|
num.className = "cal-cell__num";
|
|
num.textContent = day;
|
|
cell.appendChild(num);
|
|
|
|
cell.addEventListener("click", function () {
|
|
document.querySelectorAll(".cal-cell--active").forEach(function (c) { c.classList.remove("cal-cell--active"); });
|
|
cell.classList.add("cal-cell--active");
|
|
graphMode = dateStr;
|
|
loadDay(dateStr);
|
|
});
|
|
|
|
grid.appendChild(cell);
|
|
})(day);
|
|
}
|
|
}
|
|
|
|
function loadSnapshot() {
|
|
fetch("/api/status/snapshot", { credentials: "include" })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (data) {
|
|
if (data && data.ok && data.snapshot) {
|
|
applySample(data.snapshot);
|
|
}
|
|
})
|
|
.catch(function (err) {
|
|
console.warn("[monitor] snapshot fetch error:", err);
|
|
});
|
|
}
|
|
|
|
function loadSummaryAndCalendar() {
|
|
fetch("/api/status/metrics/summary", { credentials: "include" })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (data) {
|
|
buildCalendar(data && data.ok ? data.days : []);
|
|
// default: today's graph + mark today active
|
|
var todayKey = new Date().toISOString().slice(0, 10);
|
|
var todayCell = document.querySelector('.cal-cell[data-day="' + todayKey + '"]');
|
|
if (todayCell) todayCell.classList.add("cal-cell--active");
|
|
loadDay(todayKey);
|
|
})
|
|
.catch(function () {
|
|
buildCalendar([]);
|
|
// The resize redraw reuses the last drawn day; populate it here too,
|
|
// otherwise a summary fetch failure leaves nothing for the resize
|
|
// handler to re-render.
|
|
loadDay(new Date().toISOString().slice(0, 10));
|
|
});
|
|
}
|
|
|
|
// ---- socket wiring -----------------------------------------------------
|
|
function connectSocket() {
|
|
if (typeof io !== "function") return;
|
|
if (window._monitorSocket) {
|
|
SOCKET = window._monitorSocket;
|
|
if (SOCKET.connected) {
|
|
watching = false;
|
|
subscribe();
|
|
}
|
|
return;
|
|
}
|
|
SOCKET = io({ withCredentials: true, transports: ['websocket', 'polling'] });
|
|
window._monitorSocket = SOCKET;
|
|
|
|
SOCKET.on("connect", function () {
|
|
watching = false;
|
|
subscribe();
|
|
});
|
|
SOCKET.on("monitor:snapshot", function (snap) { applySample(snap); });
|
|
SOCKET.on("monitor:sample", function (s) { applySample(s); });
|
|
SOCKET.on("monitor:error", function (e) {
|
|
console.warn("[monitor]", e && e.error);
|
|
});
|
|
|
|
if (SOCKET.connected) {
|
|
watching = false;
|
|
subscribe();
|
|
}
|
|
}
|
|
|
|
function subscribe() {
|
|
if (watching) return;
|
|
watching = true;
|
|
SOCKET.emit("monitor:subscribe");
|
|
}
|
|
function unsubscribe() {
|
|
if (!watching || !SOCKET) return;
|
|
watching = false;
|
|
SOCKET.emit("monitor:unsubscribe");
|
|
}
|
|
|
|
// Pause intensive sampling when the tab is hidden (keeps cost near zero).
|
|
document.addEventListener("visibilitychange", function () {
|
|
if (document.hidden) unsubscribe();
|
|
else if (SOCKET) { watching = false; subscribe(); }
|
|
});
|
|
window.addEventListener("beforeunload", unsubscribe);
|
|
|
|
function init() {
|
|
loadSnapshot();
|
|
connectSocket();
|
|
loadSummaryAndCalendar();
|
|
|
|
// Fallback REST polling every 3 seconds to guarantee metrics stay live
|
|
setInterval(function () {
|
|
if (!document.hidden) {
|
|
loadSnapshot();
|
|
}
|
|
}, 3000);
|
|
|
|
// Redraw the already-fetched graph at the new canvas size (debounced).
|
|
// The old handler fired a /api/status/metrics/day fetch per resize
|
|
// event, so a window drag turned into a request storm.
|
|
var resizeTimer = null;
|
|
window.addEventListener("resize", function () {
|
|
if (resizeTimer) clearTimeout(resizeTimer);
|
|
resizeTimer = setTimeout(function () {
|
|
resizeTimer = null;
|
|
if (lastGraphPoints) drawGraph(lastGraphPoints, lastGraphLabel);
|
|
}, 150);
|
|
});
|
|
}
|
|
|
|
if (document.readyState === "loading") {
|
|
document.addEventListener("DOMContentLoaded", init);
|
|
} else {
|
|
init();
|
|
}
|
|
})();
|