feat: add process resource monitor
This commit is contained in:
@@ -718,6 +718,126 @@ h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; }
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.process-resource-panel {
|
||||
margin-top: 8px;
|
||||
border: 1px solid var(--line-soft);
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255,255,255,0.025), transparent 28%),
|
||||
#0b141b;
|
||||
}
|
||||
.process-resource-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 8px 9px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
}
|
||||
.process-resource-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
.process-resource-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
}
|
||||
.process-table-wrap {
|
||||
max-height: 420px;
|
||||
overflow: auto;
|
||||
}
|
||||
.process-resource-table {
|
||||
min-width: 1120px;
|
||||
}
|
||||
.process-resource-table th,
|
||||
.process-resource-table td {
|
||||
padding: 6px 8px;
|
||||
}
|
||||
.process-sort-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
text-transform: inherit;
|
||||
letter-spacing: inherit;
|
||||
}
|
||||
.process-sort-button span {
|
||||
color: var(--faint);
|
||||
font-size: 10px;
|
||||
}
|
||||
.process-sort-button.active span {
|
||||
color: var(--accent-2);
|
||||
}
|
||||
.process-name-cell {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
min-width: 260px;
|
||||
max-width: 420px;
|
||||
}
|
||||
.process-name-cell strong {
|
||||
color: #e3eef0;
|
||||
}
|
||||
.process-command {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.process-state {
|
||||
display: inline-flex;
|
||||
min-width: 22px;
|
||||
justify-content: center;
|
||||
padding: 1px 5px;
|
||||
border: 1px solid var(--line-soft);
|
||||
color: var(--muted);
|
||||
background: rgba(255,255,255,0.025);
|
||||
font-family: "Cascadia Mono", "IBM Plex Mono", "Liberation Mono", monospace;
|
||||
}
|
||||
.process-meter {
|
||||
position: relative;
|
||||
min-width: 104px;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line-soft);
|
||||
background: rgba(255,255,255,0.025);
|
||||
}
|
||||
.process-meter span {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: linear-gradient(90deg, rgba(78, 183, 168, 0.58), rgba(78, 183, 168, 0.12));
|
||||
}
|
||||
.process-meter.cpu span {
|
||||
background: linear-gradient(90deg, rgba(215, 161, 58, 0.64), rgba(215, 161, 58, 0.12));
|
||||
}
|
||||
.process-meter b {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: block;
|
||||
padding: 2px 6px;
|
||||
color: #eaf3f2;
|
||||
font-family: "Cascadia Mono", "IBM Plex Mono", "Liberation Mono", monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
.process-io-cell {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
min-width: 146px;
|
||||
}
|
||||
.process-io-cell strong {
|
||||
color: #d7e3e7;
|
||||
}
|
||||
.process-io-cell span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.monitor-side-stack {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
@@ -1833,6 +1953,16 @@ input:focus, select:focus, textarea:focus { border-color: var(--accent-2); }
|
||||
}
|
||||
.metric-grid, .policy-grid, .security-board, .dispatch-form, .docker-metrics, .monitor-chart-grid, .monitor-summary-grid, .gateway-record-grid, .met-detail-kv { grid-template-columns: 1fr; }
|
||||
.compact-row, .heartbeat-row, .log-row, .endpoint-list article, .volume-route, .findjob-hero, .pipeline-hero { grid-template-columns: 1fr; align-items: start; }
|
||||
.process-resource-head {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
.process-resource-actions {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.process-table-wrap {
|
||||
max-height: 360px;
|
||||
}
|
||||
.met-tree-header, .met-tree-row {
|
||||
grid-template-columns: minmax(220px, 1fr) 72px 62px 76px 96px;
|
||||
min-width: 560px;
|
||||
|
||||
@@ -104,6 +104,17 @@ function fmtPercent(value: any): string {
|
||||
return Number.isFinite(number) ? `${Math.max(0, Math.min(100, number)).toFixed(1)}%` : "--";
|
||||
}
|
||||
|
||||
function fmtLoosePercent(value: any): string {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? `${Math.max(0, number).toFixed(1)}%` : "--";
|
||||
}
|
||||
|
||||
function fmtBytesRate(value: any): string {
|
||||
const bytes = Number(value);
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B/s";
|
||||
return `${fmtBytes(bytes)}/s`;
|
||||
}
|
||||
|
||||
function asNumber(value: any, fallback = 0): number {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : fallback;
|
||||
@@ -719,6 +730,7 @@ function NodeMonitorPage({ nodes, systemStatuses, tasks, onRaw, refresh }: AnyRe
|
||||
h(MetricCard, { label: "硬盘已用", value: fmtBytes(disk.usedBytes), hint: fmtPercent(disk.percent) }),
|
||||
h(MetricCard, { label: "更新时间", value: fmtDate(active.systemUpdatedAt || current.collectedAt), hint: active.providerId }),
|
||||
),
|
||||
h(ProcessResourceTable, { current, onRaw }),
|
||||
),
|
||||
),
|
||||
h("div", { className: "monitor-side-stack" },
|
||||
@@ -729,6 +741,7 @@ function NodeMonitorPage({ nodes, systemStatuses, tasks, onRaw, refresh }: AnyRe
|
||||
h("article", null, h("b", null, "CPU"), h("span", null, "从 /proc/stat 计算相邻采样差值,首个采样用 load/cores 近似")),
|
||||
h("article", null, h("b", null, "Memory"), h("span", null, "实际内存 = MemTotal - MemFree - Buffers - Cached - SReclaimable + Shmem,不把 page cache / buffer 计入占用")),
|
||||
h("article", null, h("b", null, "Disk"), h("span", null, "使用 df -PB1 对配置路径采样,默认监控根文件系统")),
|
||||
h("article", null, h("b", null, "Process"), h("span", null, "从 /proc/[pid] 采集进程 CPU、实际内存 RSS、线程数和磁盘 I/O 速率;表格默认按内存占用降序")),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -736,6 +749,119 @@ function NodeMonitorPage({ nodes, systemStatuses, tasks, onRaw, refresh }: AnyRe
|
||||
);
|
||||
}
|
||||
|
||||
type ProcessSortKey = "memory" | "cpu" | "disk" | "pid" | "name" | "user" | "threads" | "runtime";
|
||||
|
||||
function processSortValue(row: AnyRecord, key: ProcessSortKey): string | number {
|
||||
if (key === "memory") return asNumber(row.rssBytes);
|
||||
if (key === "cpu") return asNumber(row.cpuPercent);
|
||||
if (key === "disk") return asNumber(row.readBytesPerSecond) + asNumber(row.writeBytesPerSecond);
|
||||
if (key === "pid") return asNumber(row.pid);
|
||||
if (key === "threads") return asNumber(row.threads);
|
||||
if (key === "runtime") return asNumber(row.elapsedSeconds);
|
||||
if (key === "user") return String(row.user || "");
|
||||
return String(row.name || row.command || "");
|
||||
}
|
||||
|
||||
function ProcessMeter({ value, label, tone }: AnyRecord) {
|
||||
const width = Math.max(1, Math.min(100, asNumber(value)));
|
||||
return h("div", { className: `process-meter ${tone || ""}` },
|
||||
h("span", { style: { width: `${width}%` } }),
|
||||
h("b", null, label),
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessResourceTable({ current, onRaw }: AnyRecord) {
|
||||
const [sort, setSort] = useState({ key: "memory", direction: "desc" });
|
||||
const processSummary = current?.processSummary && typeof current.processSummary === "object" ? current.processSummary : {};
|
||||
const processes = Array.isArray(current?.processes) ? current.processes : [];
|
||||
const rows = useMemo(() => {
|
||||
const direction = sort.direction === "asc" ? 1 : -1;
|
||||
return [...processes].sort((left: AnyRecord, right: AnyRecord) => {
|
||||
const a = processSortValue(left, sort.key);
|
||||
const b = processSortValue(right, sort.key);
|
||||
if (typeof a === "string" || typeof b === "string") return String(a).localeCompare(String(b), "zh-CN") * direction;
|
||||
return (a - b) * direction || asNumber(left.pid) - asNumber(right.pid);
|
||||
});
|
||||
}, [processes, sort.key, sort.direction]);
|
||||
|
||||
const sortHeader = (label: string, key: ProcessSortKey) => {
|
||||
const active = sort.key === key;
|
||||
const ariaSort = active ? (sort.direction === "asc" ? "ascending" : "descending") : "none";
|
||||
return h("th", { "aria-sort": ariaSort },
|
||||
h("button", {
|
||||
type: "button",
|
||||
className: `process-sort-button ${active ? "active" : ""}`,
|
||||
"data-testid": `process-sort-${key}`,
|
||||
onClick: () => setSort((previous: AnyRecord) => ({
|
||||
key,
|
||||
direction: previous.key === key && previous.direction === "desc" ? "asc" : "desc",
|
||||
})),
|
||||
}, label, h("span", null, active ? (sort.direction === "desc" ? "↓" : "↑") : "↕")),
|
||||
);
|
||||
};
|
||||
|
||||
return h("section", { className: "process-resource-panel", "data-testid": "process-resource-panel" },
|
||||
h("div", { className: "process-resource-head" },
|
||||
h("div", null,
|
||||
h("p", { className: "panel-eyebrow" }, "Windows Resource Monitor Style"),
|
||||
h("h3", null, "进程资源占用"),
|
||||
),
|
||||
h("div", { className: "process-resource-actions" },
|
||||
h("span", { className: "data-chip" }, "默认按内存排序"),
|
||||
h("span", { className: "data-chip" }, `${asNumber(processSummary.visible, rows.length)} / ${asNumber(processSummary.total, rows.length)} 进程`),
|
||||
h(RawButton, { title: "Process Resource Snapshot", data: { processSummary, processes }, onOpen: onRaw, testId: "raw-process-resources" }),
|
||||
),
|
||||
),
|
||||
rows.length === 0 ? h(EmptyState, { title: "暂无进程资源数据", text: "等待 provider-gateway 上报 /proc/[pid] 采样;旧版 provider 需要先升级到支持进程资源表的版本" }) :
|
||||
h("div", { className: "process-table-wrap" },
|
||||
h("table", { className: "process-resource-table", "data-testid": "process-resource-table" },
|
||||
h("thead", null, h("tr", null,
|
||||
sortHeader("进程", "name"),
|
||||
sortHeader("PID", "pid"),
|
||||
sortHeader("用户", "user"),
|
||||
h("th", null, "状态"),
|
||||
sortHeader("CPU", "cpu"),
|
||||
sortHeader("内存", "memory"),
|
||||
h("th", null, "RSS"),
|
||||
sortHeader("磁盘 I/O", "disk"),
|
||||
sortHeader("线程", "threads"),
|
||||
sortHeader("运行时长", "runtime"),
|
||||
)),
|
||||
h("tbody", null, rows.map((row: AnyRecord) => {
|
||||
const diskRate = asNumber(row.readBytesPerSecond) + asNumber(row.writeBytesPerSecond);
|
||||
return h("tr", {
|
||||
key: `${row.pid}-${row.startedAt}`,
|
||||
"data-testid": `process-row-${safeId(row.pid)}`,
|
||||
"data-memory-bytes": String(asNumber(row.rssBytes)),
|
||||
"data-cpu-percent": String(asNumber(row.cpuPercent)),
|
||||
"data-disk-bps": String(diskRate),
|
||||
"data-pid": String(asNumber(row.pid)),
|
||||
},
|
||||
h("td", null,
|
||||
h("div", { className: "process-name-cell" },
|
||||
h("strong", null, row.name || "--"),
|
||||
h("span", { className: "process-command" }, row.command || "--"),
|
||||
),
|
||||
),
|
||||
h("td", null, h("code", null, row.pid || "--")),
|
||||
h("td", null, row.user || `uid:${row.uid ?? "--"}`),
|
||||
h("td", null, h("span", { className: `process-state state-${safeId(row.state || "unknown")}` }, row.state || "?")),
|
||||
h("td", null, h(ProcessMeter, { value: row.cpuPercent, label: fmtLoosePercent(row.cpuPercent), tone: "cpu" })),
|
||||
h("td", null, h(ProcessMeter, { value: row.memoryPercent, label: fmtPercent(row.memoryPercent), tone: "memory" })),
|
||||
h("td", null, fmtBytes(row.rssBytes)),
|
||||
h("td", null, h("div", { className: "process-io-cell" },
|
||||
h("strong", null, fmtBytesRate(diskRate)),
|
||||
h("span", null, `R ${fmtBytesRate(row.readBytesPerSecond)} / W ${fmtBytesRate(row.writeBytesPerSecond)}`),
|
||||
)),
|
||||
h("td", null, row.threads || 0),
|
||||
h("td", null, fmtDuration(asNumber(row.elapsedSeconds))),
|
||||
);
|
||||
})),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function MetricChart({ title, metricKey, current, points, detail, tone, testId }: AnyRecord) {
|
||||
const values = points.map((point: any) => Math.max(0, Math.min(100, asNumber(point[metricKey]))));
|
||||
const chartValues = values.length > 1 ? values : [values[0] || 0, values[0] || 0];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@unidesk/provider-gateway",
|
||||
"version": "0.2.5",
|
||||
"version": "0.2.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import {
|
||||
type CoreDispatchMessage,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type DockerStatusSnapshot,
|
||||
type DockerVolumeSummary,
|
||||
type JsonValue,
|
||||
type ProcessResourceSummary,
|
||||
type ProviderLabels,
|
||||
type ProviderTaskStatusMessage,
|
||||
type SystemStatusSnapshot,
|
||||
@@ -56,6 +57,10 @@ let systemStatusTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let dockerStatusRunning = false;
|
||||
let systemStatusRunning = false;
|
||||
let previousCpuSample: { idle: number; total: number } | null = null;
|
||||
let previousProcessSamples = new Map<number, { totalTicks: number; sampledAtMs: number; readBytes: number; writeBytes: number }>();
|
||||
let passwdCache: Map<number, string> | null = null;
|
||||
let clockTicksCache: number | null = null;
|
||||
let pageSizeCache: number | null = null;
|
||||
let reconnectAttempt = 0;
|
||||
let stopping = false;
|
||||
let upgradeSleepUntil = 0;
|
||||
@@ -261,6 +266,7 @@ async function sendSystemStatus(): Promise<void> {
|
||||
cpuPercent: status.cpu.percent,
|
||||
memoryPercent: status.memory.percent,
|
||||
diskPercent: status.disk.percent,
|
||||
processCount: status.processes?.length ?? 0,
|
||||
});
|
||||
} catch (error) {
|
||||
logger("error", "system_status_failed", { error: error instanceof Error ? error.message : String(error) });
|
||||
@@ -384,6 +390,11 @@ function clampPercent(value: number): number {
|
||||
return Math.max(0, Math.min(100, Number(value.toFixed(1))));
|
||||
}
|
||||
|
||||
function roundMetric(value: number, digits = 1): number {
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.max(0, Number(value.toFixed(digits)));
|
||||
}
|
||||
|
||||
function readCpuSample(): { idle: number; total: number; cores: number } {
|
||||
const stat = readFileSync("/proc/stat", "utf8");
|
||||
const lines = stat.split("\n");
|
||||
@@ -415,6 +426,211 @@ function readMemInfo(): Record<string, number> {
|
||||
return result;
|
||||
}
|
||||
|
||||
async function readGetconfNumber(name: string, fallback: number): Promise<number> {
|
||||
const result = await runProcessCommand("getconf", [name], 1000);
|
||||
const parsed = Number(result.stdout.trim());
|
||||
return result.ok && Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
async function systemClockTicks(): Promise<number> {
|
||||
if (clockTicksCache !== null) return clockTicksCache;
|
||||
clockTicksCache = await readGetconfNumber("CLK_TCK", 100);
|
||||
return clockTicksCache;
|
||||
}
|
||||
|
||||
async function systemPageSize(): Promise<number> {
|
||||
if (pageSizeCache !== null) return pageSizeCache;
|
||||
pageSizeCache = await readGetconfNumber("PAGESIZE", 4096);
|
||||
return pageSizeCache;
|
||||
}
|
||||
|
||||
function usernameForUid(uid: number): string {
|
||||
if (passwdCache === null) {
|
||||
passwdCache = new Map<number, string>();
|
||||
try {
|
||||
for (const line of readFileSync("/etc/passwd", "utf8").split("\n")) {
|
||||
const parts = line.split(":");
|
||||
const parsedUid = Number(parts[2]);
|
||||
if (parts[0] && Number.isFinite(parsedUid)) passwdCache.set(parsedUid, parts[0]);
|
||||
}
|
||||
} catch {
|
||||
// Provider containers may not have the host passwd database; fall back to uid labels.
|
||||
}
|
||||
}
|
||||
return passwdCache.get(uid) ?? `uid:${uid}`;
|
||||
}
|
||||
|
||||
function readProcessStatus(pid: number): { uid: number; threads: number; name: string } {
|
||||
const status = readFileSync(`/proc/${pid}/status`, "utf8");
|
||||
let uid = -1;
|
||||
let threads = 0;
|
||||
let name = "";
|
||||
for (const line of status.split("\n")) {
|
||||
if (line.startsWith("Uid:")) {
|
||||
const parsed = Number(line.trim().split(/\s+/)[1]);
|
||||
if (Number.isFinite(parsed)) uid = parsed;
|
||||
} else if (line.startsWith("Threads:")) {
|
||||
const parsed = Number(line.trim().split(/\s+/)[1]);
|
||||
if (Number.isFinite(parsed)) threads = parsed;
|
||||
} else if (line.startsWith("Name:")) {
|
||||
name = line.slice("Name:".length).trim();
|
||||
}
|
||||
}
|
||||
return { uid, threads, name };
|
||||
}
|
||||
|
||||
function readProcessCommand(pid: number, fallback: string): string {
|
||||
try {
|
||||
const raw = readFileSync(`/proc/${pid}/cmdline`, "utf8");
|
||||
const command = raw.split("\0").filter(Boolean).join(" ").trim();
|
||||
return (command || fallback).slice(0, 500);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function readProcessIo(pid: number): { readBytes: number; writeBytes: number } {
|
||||
try {
|
||||
const result = { readBytes: 0, writeBytes: 0 };
|
||||
for (const line of readFileSync(`/proc/${pid}/io`, "utf8").split("\n")) {
|
||||
const match = line.match(/^(read_bytes|write_bytes):\s+(\d+)/);
|
||||
if (!match) continue;
|
||||
const parsed = Number(match[2]);
|
||||
if (!Number.isFinite(parsed)) continue;
|
||||
if (match[1] === "read_bytes") result.readBytes = parsed;
|
||||
if (match[1] === "write_bytes") result.writeBytes = parsed;
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return { readBytes: 0, writeBytes: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
function readUptimeSeconds(): number {
|
||||
const uptime = Number(readFileSync("/proc/uptime", "utf8").trim().split(/\s+/)[0]);
|
||||
return Number.isFinite(uptime) ? uptime : 0;
|
||||
}
|
||||
|
||||
function parseProcessStat(raw: string): {
|
||||
pid: number;
|
||||
name: string;
|
||||
state: string;
|
||||
ppid: number;
|
||||
totalTicks: number;
|
||||
startTicks: number;
|
||||
vmsBytes: number;
|
||||
rssPages: number;
|
||||
threads: number;
|
||||
} | null {
|
||||
const open = raw.indexOf("(");
|
||||
const close = raw.lastIndexOf(")");
|
||||
if (open < 0 || close <= open) return null;
|
||||
const pid = Number(raw.slice(0, open).trim());
|
||||
const name = raw.slice(open + 1, close);
|
||||
const fields = raw.slice(close + 1).trim().split(/\s+/);
|
||||
if (!Number.isFinite(pid) || fields.length < 22) return null;
|
||||
const value = (index: number): number => {
|
||||
const parsed = Number(fields[index]);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
};
|
||||
return {
|
||||
pid,
|
||||
name,
|
||||
state: fields[0] || "?",
|
||||
ppid: value(1),
|
||||
totalTicks: value(11) + value(12),
|
||||
threads: value(17),
|
||||
startTicks: value(19),
|
||||
vmsBytes: value(20),
|
||||
rssPages: value(21),
|
||||
};
|
||||
}
|
||||
|
||||
async function collectProcessResources(totalMemoryBytes: number, cpuCores: number): Promise<{
|
||||
processes: ProcessResourceSummary[];
|
||||
summary: Record<string, JsonValue>;
|
||||
}> {
|
||||
const [clockTicks, pageSize] = await Promise.all([systemClockTicks(), systemPageSize()]);
|
||||
const uptimeSeconds = readUptimeSeconds();
|
||||
const sampledAtMs = Date.now();
|
||||
const rows: ProcessResourceSummary[] = [];
|
||||
const seen = new Set<number>();
|
||||
let skipped = 0;
|
||||
const hasPreviousProcessSample = previousProcessSamples.size > 0;
|
||||
|
||||
for (const entry of readdirSync("/proc")) {
|
||||
if (!/^\d+$/.test(entry)) continue;
|
||||
const pid = Number(entry);
|
||||
try {
|
||||
const stat = parseProcessStat(readFileSync(`/proc/${entry}/stat`, "utf8"));
|
||||
if (stat === null) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const status = readProcessStatus(pid);
|
||||
const io = readProcessIo(pid);
|
||||
const previous = previousProcessSamples.get(pid);
|
||||
const elapsedSampleSeconds = previous ? Math.max(0.001, (sampledAtMs - previous.sampledAtMs) / 1000) : 0;
|
||||
const elapsedProcessSeconds = Math.max(0, uptimeSeconds - stat.startTicks / clockTicks);
|
||||
const cpuPercent = previous
|
||||
? ((Math.max(0, stat.totalTicks - previous.totalTicks) / clockTicks) / elapsedSampleSeconds) * 100
|
||||
: elapsedProcessSeconds > 0
|
||||
? ((stat.totalTicks / clockTicks) / elapsedProcessSeconds) * 100
|
||||
: 0;
|
||||
const ioSeconds = previous ? elapsedSampleSeconds : 0;
|
||||
const readBytesPerSecond = previous && ioSeconds > 0 ? Math.max(0, io.readBytes - previous.readBytes) / ioSeconds : 0;
|
||||
const writeBytesPerSecond = previous && ioSeconds > 0 ? Math.max(0, io.writeBytes - previous.writeBytes) / ioSeconds : 0;
|
||||
const rssBytes = Math.max(0, stat.rssPages * pageSize);
|
||||
const name = status.name || stat.name;
|
||||
const uid = status.uid >= 0 ? status.uid : 0;
|
||||
rows.push({
|
||||
pid: stat.pid,
|
||||
ppid: stat.ppid,
|
||||
uid,
|
||||
user: usernameForUid(uid),
|
||||
name,
|
||||
command: readProcessCommand(pid, name),
|
||||
state: stat.state,
|
||||
cpuPercent: roundMetric(Math.min(cpuPercent, Math.max(1, cpuCores) * 100)),
|
||||
memoryPercent: totalMemoryBytes > 0 ? clampPercent((rssBytes / totalMemoryBytes) * 100) : 0,
|
||||
rssBytes,
|
||||
vmsBytes: Math.max(0, stat.vmsBytes),
|
||||
threads: status.threads || stat.threads,
|
||||
readBytes: io.readBytes,
|
||||
writeBytes: io.writeBytes,
|
||||
readBytesPerSecond: roundMetric(readBytesPerSecond, 0),
|
||||
writeBytesPerSecond: roundMetric(writeBytesPerSecond, 0),
|
||||
elapsedSeconds: roundMetric(elapsedProcessSeconds, 0),
|
||||
startedAt: new Date(Date.now() - elapsedProcessSeconds * 1000).toISOString(),
|
||||
});
|
||||
previousProcessSamples.set(pid, {
|
||||
totalTicks: stat.totalTicks,
|
||||
sampledAtMs,
|
||||
readBytes: io.readBytes,
|
||||
writeBytes: io.writeBytes,
|
||||
});
|
||||
seen.add(pid);
|
||||
} catch {
|
||||
skipped += 1;
|
||||
}
|
||||
}
|
||||
|
||||
previousProcessSamples = new Map([...previousProcessSamples].filter(([pid]) => seen.has(pid)));
|
||||
rows.sort((a, b) => b.rssBytes - a.rssBytes || b.cpuPercent - a.cpuPercent || a.pid - b.pid);
|
||||
return {
|
||||
processes: rows.slice(0, 120),
|
||||
summary: {
|
||||
total: rows.length,
|
||||
visible: Math.min(rows.length, 120),
|
||||
skipped,
|
||||
defaultSort: "memory_desc",
|
||||
scope: "provider_pid_namespace",
|
||||
cpuPercentMode: hasPreviousProcessSample ? "delta_ticks_per_sample" : "lifetime_average_first_sample",
|
||||
diskIoMode: "proc_pid_io_delta_bytes_per_second",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readDiskUsage(path: string): Promise<{ mount: string; totalBytes: number; usedBytes: number; availableBytes: number; percent: number }> {
|
||||
const result = await runProcessCommand("df", ["-PB1", path], 3000);
|
||||
if (!result.ok) throw new Error(`df failed with exit ${result.exitCode}: ${result.stderr}`);
|
||||
@@ -485,6 +701,18 @@ async function collectSystemStatus(): Promise<SystemStatusSnapshot> {
|
||||
errors.push({ source: "proc.meminfo", error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
|
||||
let processes: ProcessResourceSummary[] = [];
|
||||
let processSummary: Record<string, JsonValue> = { total: 0, visible: 0, defaultSort: "memory_desc" };
|
||||
try {
|
||||
const totalMemoryBytes = typeof memory.totalBytes === "number" ? memory.totalBytes : 0;
|
||||
const cpuCores = typeof cpu.cores === "number" ? cpu.cores : 1;
|
||||
const collected = await collectProcessResources(totalMemoryBytes, cpuCores);
|
||||
processes = collected.processes;
|
||||
processSummary = collected.summary;
|
||||
} catch (error) {
|
||||
errors.push({ source: "proc.processes", error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
|
||||
let disk: Record<string, JsonValue> = { path: config.monitorDiskPath, mount: "", totalBytes: 0, usedBytes: 0, availableBytes: 0, percent: 0 };
|
||||
try {
|
||||
disk = { path: config.monitorDiskPath, ...(await readDiskUsage(config.monitorDiskPath)) };
|
||||
@@ -492,7 +720,7 @@ async function collectSystemStatus(): Promise<SystemStatusSnapshot> {
|
||||
errors.push({ source: "df", path: config.monitorDiskPath, error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
|
||||
return { ok: errors.length === 0, collectedAt, cpu, memory, disk, errors };
|
||||
return { ok: errors.length === 0, collectedAt, cpu, memory, disk, processes, processSummary, errors };
|
||||
}
|
||||
|
||||
async function collectDockerStatus(): Promise<DockerStatusSnapshot> {
|
||||
@@ -975,6 +1203,7 @@ function upgradePlan(taskId: string): Record<string, JsonValue> {
|
||||
"docker run -d",
|
||||
`--name ${shellQuote(candidateName)}`,
|
||||
"--restart no",
|
||||
"--pid host",
|
||||
"$network_arg",
|
||||
`--env-file "$candidate_env_file"`,
|
||||
`--label ${shellQuote(`com.docker.compose.project=${config.upgradeComposeProject}`)}`,
|
||||
@@ -1053,6 +1282,7 @@ function upgradePlan(taskId: string): Record<string, JsonValue> {
|
||||
candidateUsesOldContainerNetworks: true,
|
||||
candidateUsesOldContainerExtraHosts: true,
|
||||
candidateUsesOldContainerEnvironment: true,
|
||||
candidateUsesHostPidNamespace: true,
|
||||
removeScope: {
|
||||
projectLabel: config.upgradeComposeProject,
|
||||
serviceLabel: config.upgradeService,
|
||||
|
||||
@@ -18,12 +18,35 @@ export interface ProviderHeartbeatMessage {
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface ProcessResourceSummary {
|
||||
pid: number;
|
||||
ppid: number;
|
||||
uid: number;
|
||||
user: string;
|
||||
name: string;
|
||||
command: string;
|
||||
state: string;
|
||||
cpuPercent: number;
|
||||
memoryPercent: number;
|
||||
rssBytes: number;
|
||||
vmsBytes: number;
|
||||
threads: number;
|
||||
readBytes: number;
|
||||
writeBytes: number;
|
||||
readBytesPerSecond: number;
|
||||
writeBytesPerSecond: number;
|
||||
elapsedSeconds: number;
|
||||
startedAt: string;
|
||||
}
|
||||
|
||||
export interface SystemStatusSnapshot {
|
||||
ok: boolean;
|
||||
collectedAt: string;
|
||||
cpu: Record<string, JsonValue>;
|
||||
memory: Record<string, JsonValue>;
|
||||
disk: Record<string, JsonValue>;
|
||||
processes?: ProcessResourceSummary[];
|
||||
processSummary?: Record<string, JsonValue>;
|
||||
errors: JsonValue[];
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user