From 72aa411d2b7930f8e377ba760c4100e5fbac899c Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Fri, 4 Dec 2026 13:12:20 -0800 Subject: [PATCH] feat(services): add aggregate 2x2 resource charts to Docker Compose Dashboard (#8125) The Compose project Dashboard gets a Project Resource Usage grid under its Services table: CPU, memory, disk I/O and network I/O summed over the stack's containers, reusing the container charts and fed by the existing 3-second stats poll (no extra streams). Scrubbing the charts shows each service's stats at that moment in the table above, I/O rates are computed per container before summing, and memory bars of uncapped stacks scale by each service's share of the stack. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- e2e/services.spec.ts | 216 ++++++++++++++++++ .../services/ContainerStatsCharts.tsx | 82 +++++-- src/features/services/composeStats.test.ts | 127 ++++++++++ src/features/services/composeStats.ts | 196 ++++++++++++++++ src/features/services/containerStats.ts | 18 +- src/features/services/dashboard.tsx | 119 +++++++++- src/features/services/dashboardStats.test.tsx | 118 +++++++++- src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + 9 files changed, 844 insertions(+), 36 deletions(-) create mode 100644 src/features/services/composeStats.test.ts create mode 100644 src/features/services/composeStats.ts diff --git a/e2e/services.spec.ts b/e2e/services.spec.ts index 192ec841a0..38ec18f357 100644 --- a/e2e/services.spec.ts +++ b/e2e/services.spec.ts @@ -1275,3 +1275,219 @@ test("Docker container dashboard renders synchronized 2x2 metrics charts and col expect(Math.abs(narrowCpu.x - narrowMem.x)).toBeLessThan(2); expect(narrowMem.y).toBeGreaterThan(narrowCpu.y + narrowCpu.height - 2); }); + +test("Compose Project dashboard renders Services table above aggregate Project Resource Usage charts with synchronized scrub attribution", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(async () => { + const makeContainer = (idx: number) => ({ + id: `runner-${idx}`, + name: `selfhost-runner-github-runner-${idx}`, + image: "selfhost-runner-github-runner", + command: "/entrypoint.sh", + state: "running", + status: "Up 4 minutes", + ports: "", + createdAt: "2026-12-04T18:12:06Z", + composeProject: "selfhost-runner", + composeService: "github-runner", + composeWorkingDir: "/Users/dev/openidea/scripts/selfhost-runner", + composeFiles: ["/Users/dev/openidea/scripts/selfhost-runner/docker-compose.yml"], + mounts: ["selfhost-runner_runner-persist"], + networks: ["selfhost-runner_default"], + labels: {}, + }); + const snapshot = { + availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" }, + executable: "/usr/local/bin/docker", + containers: [makeContainer(1), makeContainer(2), makeContainer(3), makeContainer(4)], + images: [], + volumes: [ + { + name: "selfhost-runner_runner-persist", + driver: "local", + mountpoint: "/var/lib/docker/volumes/selfhost-runner_runner-persist/_data", + composeProject: "selfhost-runner", + scope: "local", + labels: { "com.docker.compose.project": "selfhost-runner", "com.docker.compose.volume": "runner-persist" }, + }, + ], + networks: [], + errors: [], + }; + const liveStats: Record> = { + "runner-1": { + cpuPerc: "0.20%", + memUsage: "71.46MiB / 114.3GiB", + memPerc: "0.06%", + netIo: "200kB / 18kB", + blockIo: "36MB / 1.2MB", + pids: "17", + }, + "runner-2": { + cpuPerc: "0.15%", + memUsage: "38.18MiB / 114.3GiB", + memPerc: "0.03%", + netIo: "190kB / 16kB", + blockIo: "300kB / 560kB", + pids: "17", + }, + "runner-3": { + cpuPerc: "2.10%", + memUsage: "117.2MiB / 114.3GiB", + memPerc: "0.10%", + netIo: "210kB / 20kB", + blockIo: "90MB / 1.4MB", + pids: "16", + }, + "runner-4": { + cpuPerc: "0.05%", + memUsage: "38.5MiB / 114.3GiB", + memPerc: "0.03%", + netIo: "180kB / 15kB", + blockIo: "280kB / 540kB", + pids: "18", + }, + }; + + window.__ipc.handlers.docker_settings = () => ({ + connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], + registries: [], + }); + window.__ipc.handlers.docker_snapshot = () => snapshot; + window.__ipc.handlers.docker_events = () => new Promise(() => {}); + window.__ipc.handlers.docker_volume_sizes = () => ({ "selfhost-runner_runner-persist": "1.269MB" }); + window.__ipc.handlers.docker_container_stats = ({ id }) => liveStats[String(id)]; + window.__ipc.handlers.cancel_request = () => null; + + const storeMod = "/src/features/services/store.ts"; + const treeMod = "/src/features/services/tree.ts"; + const composeMod = "/src/features/services/composeStats.ts"; + const { useServices } = await import(/* @vite-ignore */ storeMod); + const { useServicesTree } = await import(/* @vite-ignore */ treeMod); + const { composeStatsScope, pushComposeStatsTick } = await import(/* @vite-ignore */ composeMod); + + const scope = composeStatsScope("local", "selfhost-runner"); + const t0 = Date.now() - 30_000; + // Seed an earlier CPU spike on runner-3 (92.40%) so scrubbing attributes it in the Services table. + pushComposeStatsTick( + scope, + { + "runner-1": { + cpuPerc: "0.02%", + memUsage: "70MiB / 114.3GiB", + memPerc: "0.06%", + netIo: "170kB / 14kB", + blockIo: "34MB / 1MB", + pids: "17", + }, + "runner-2": { + cpuPerc: "0.11%", + memUsage: "38MiB / 114.3GiB", + memPerc: "0.03%", + netIo: "172kB / 15kB", + blockIo: "260kB / 520kB", + pids: "17", + }, + "runner-3": { + cpuPerc: "92.40%", + memUsage: "115MiB / 114.3GiB", + memPerc: "0.10%", + netIo: "176kB / 14kB", + blockIo: "85MB / 1.1MB", + pids: "16", + }, + "runner-4": { + cpuPerc: "0.02%", + memUsage: "38MiB / 114.3GiB", + memPerc: "0.03%", + netIo: "175kB / 15kB", + blockIo: "266kB / 528kB", + pids: "18", + }, + }, + t0, + ); + pushComposeStatsTick( + scope, + { + "runner-1": { + cpuPerc: "0.10%", + memUsage: "71MiB / 114.3GiB", + memPerc: "0.06%", + netIo: "185kB / 16kB", + blockIo: "35MB / 1.1MB", + pids: "17", + }, + "runner-2": { + cpuPerc: "0.12%", + memUsage: "38MiB / 114.3GiB", + memPerc: "0.03%", + netIo: "180kB / 15.5kB", + blockIo: "280kB / 540kB", + pids: "17", + }, + "runner-3": { + cpuPerc: "44.00%", + memUsage: "116MiB / 114.3GiB", + memPerc: "0.10%", + netIo: "195kB / 18kB", + blockIo: "88MB / 1.3MB", + pids: "16", + }, + "runner-4": { + cpuPerc: "0.03%", + memUsage: "38.2MiB / 114.3GiB", + memPerc: "0.03%", + netIo: "178kB / 15kB", + blockIo: "272kB / 535kB", + pids: "18", + }, + }, + t0 + 3000, + ); + + useServices.setState({ + settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] }, + conns: { local: { snapshot, loading: false, error: null } }, + detailTab: "dashboard", + }); + useServicesTree.setState({ + expanded: new Set(["docker:local", "docker:local:compose:selfhost-runner"]), + selectedKey: "docker:local:compose:selfhost-runner", + selectedKeys: new Set(["docker:local:compose:selfhost-runner"]), + }); + }); + + await page.keyboard.press("Meta+8"); + const services = page.getByRole("region", { name: "Services", exact: true }); + const detail = services.locator("[data-panel][id=services-detail]"); + + const table = detail.locator("table"); + const cpuCard = detail.getByRole("group", { name: "CPU" }); + const memCard = detail.getByRole("group", { name: "Memory" }); + await expect(table).toBeVisible(); + await expect(detail.getByText("Project Resource Usage")).toBeVisible(); + await cpuCard.scrollIntoViewIfNeeded(); + await expect(cpuCard).toBeVisible(); + await expect(memCard).toBeVisible(); + + // Services table stays above the 2x2 Project Resource Usage charts. + const tableBox = (await table.boundingBox())!; + const cpuBox = (await cpuCard.boundingBox())!; + const memBox = (await memCard.boundingBox())!; + expect(cpuBox.y).toBeGreaterThan(tableBox.y + tableBox.height - 2); + expect(Math.abs(cpuBox.y - memBox.y)).toBeLessThan(2); + expect(memBox.x).toBeGreaterThan(cpuBox.x + cpuBox.width - 2); + + // Keyboard scrubbing to the first tick attributes the 92.40% CPU spike to runner-3 in the Services table. + const metricsRegion = detail.getByRole("region", { name: "Container resource metrics" }); + await metricsRegion.focus(); + await page.keyboard.press("Home"); + await expect(detail.getByText(/^Snapshot /)).toBeVisible(); + await expect(detail.locator("tr", { hasText: "selfhost-runner-github-runner-3" })).toContainText("92.40%"); + await page.keyboard.press("Escape"); + await expect(detail.getByText(/^Snapshot /)).toHaveCount(0); + await expect(detail.locator("tr", { hasText: "selfhost-runner-github-runner-3" })).toContainText("2.10%"); +}); diff --git a/src/features/services/ContainerStatsCharts.tsx b/src/features/services/ContainerStatsCharts.tsx index ee80df915c..ed13f6a6c8 100644 --- a/src/features/services/ContainerStatsCharts.tsx +++ b/src/features/services/ContainerStatsCharts.tsx @@ -418,12 +418,17 @@ function MetricChartCard({ } export interface ContainerStatsChartsProps { + bannerTitle?: React.ReactNode; + statusMeta?: React.ReactNode; + /** True when CPU% sums multiple containers without a known shared CPU cap. */ + multiContainer?: boolean; samples: readonly StatsSample[]; running: boolean; paused: boolean; statsLoading: boolean; onTogglePause: () => void; onClear: () => void; + onActiveTimestampChange?: (timestampMs: number | null) => void; cpuLimit: number | null; cpuLimitText: string | null; vmCpuText: string | null; @@ -439,12 +444,16 @@ export interface ContainerStatsChartsProps { * responsive 2×2 synchronized metrics grid (CPU, Memory, Disk I/O, Network I/O). */ export function ContainerStatsCharts({ + bannerTitle, + statusMeta, + multiContainer = false, samples, running, paused, statsLoading, onTogglePause, onClear, + onActiveTimestampChange, cpuLimit, cpuLimitText, vmCpuText, @@ -464,6 +473,34 @@ export function ContainerStatsCharts({ const { points } = useMemo(() => deriveStatsSeries(samples, TIME_WINDOW_MS[timeWindow]), [samples, timeWindow]); + const notifyScrub = useCallback( + (nextHover: number | null, nextKey: number | null) => { + if (!onActiveTimestampChange) return; + const idx = nextHover ?? nextKey; + const ts = idx !== null && idx >= 0 && idx < points.length ? points[idx]!.sample.timestampMs : null; + onActiveTimestampChange(ts); + }, + [onActiveTimestampChange, points], + ); + + const handleHoverIndex = useCallback( + (idx: number | null) => { + setHoverIndex(idx); + notifyScrub(idx, keyboardIndex); + }, + [keyboardIndex, notifyScrub], + ); + + const handleTimeWindowChange = useCallback( + (next: StatsTimeWindow) => { + setHoverIndex(null); + setKeyboardIndex(null); + onActiveTimestampChange?.(null); + setStatsTimeWindow(next); + }, + [onActiveTimestampChange], + ); + const rawActiveIndex = hoverIndex ?? keyboardIndex; const activeIndex = rawActiveIndex !== null && rawActiveIndex >= 0 && rawActiveIndex < points.length ? rawActiveIndex : null; @@ -494,7 +531,9 @@ export function ContainerStatsCharts({ ? (displaySample.cpuPercent / cpuCapPct) * 100 : displaySample.onlineCpus ? (displaySample.cpuPercent / (displaySample.onlineCpus * 100)) * 100 - : displaySample.cpuPercent + : multiContainer + ? 0 + : displaySample.cpuPercent : 0; const cpuLevel = pressureForRatio(cpuPressureRatio); const cpuValueText = displaySample @@ -622,27 +661,27 @@ export function ContainerStatsCharts({ if (e.key === "Escape") { setKeyboardIndex(null); setHoverIndex(null); + onActiveTimestampChange?.(null); return; } + let nextKey: number | null = null; if (e.key === "ArrowLeft") { e.preventDefault(); - setKeyboardIndex((prev) => { - const base = prev ?? points.length - 1; - return Math.max(0, base - 1); - }); + nextKey = Math.max(0, (keyboardIndex ?? points.length - 1) - 1); } else if (e.key === "ArrowRight") { e.preventDefault(); - setKeyboardIndex((prev) => { - if (prev === null) return points.length - 1; - return Math.min(points.length - 1, prev + 1); - }); + nextKey = keyboardIndex === null ? points.length - 1 : Math.min(points.length - 1, keyboardIndex + 1); } else if (e.key === "Home") { e.preventDefault(); - setKeyboardIndex(0); + nextKey = 0; } else if (e.key === "End") { e.preventDefault(); - setKeyboardIndex(points.length - 1); + nextKey = points.length - 1; + } else { + return; } + setKeyboardIndex(nextKey); + notifyScrub(hoverIndex, nextKey); }; const scrubbedClock = activeIndex !== null && displaySample ? formatLocalClock(displaySample.timestampMs) : null; @@ -661,13 +700,12 @@ export function ContainerStatsCharts({ <>
- - Resource Usage - + {bannerTitle ?? Resource Usage} + {statusMeta && {statusMeta}} {pids && {tx`PIDs ${pids}`}} {scrubbedClock && ( @@ -682,7 +720,7 @@ export function ContainerStatsCharts({ aria-label="Time window" value={timeWindow} options={WINDOW_OPTIONS} - onChange={setStatsTimeWindow} + onChange={handleTimeWindowChange} /> { setHoverIndex(null); setKeyboardIndex(null); + onActiveTimestampChange?.(null); onClear(); }} /> @@ -741,7 +780,10 @@ export function ContainerStatsCharts({ role="region" aria-label={txFn("Container resource metrics")} onKeyDown={handleGridKeyDown} - onBlur={() => setKeyboardIndex(null)} + onBlur={() => { + setKeyboardIndex(null); + notifyScrub(hoverIndex, null); + }} >
`${Number(v.toFixed(1))}%`} referenceLine={cpuCapPct ? { value: cpuCapPct, label: txFn("Limit"), level: cpuLevel } : null} activeIndex={activeIndex} - onHoverIndex={setHoverIndex} + onHoverIndex={handleHoverIndex} /> 0 ? { value: effectiveMemLimit, label: txFn("Limit"), level: memLevel } : null } activeIndex={activeIndex} - onHoverIndex={setHoverIndex} + onHoverIndex={handleHoverIndex} />
diff --git a/src/features/services/composeStats.test.ts b/src/features/services/composeStats.test.ts new file mode 100644 index 0000000000..e37a6d450e --- /dev/null +++ b/src/features/services/composeStats.test.ts @@ -0,0 +1,127 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import type { DockerContainerStats } from "@/platform/ipc"; +import { deriveStatsSeries } from "./containerStats"; +import { + aggregateComposeTick, + clearComposeStatsHistory, + composeStatsScope, + MAX_COMPOSE_STATS_TICKS, + MAX_TRACKED_COMPOSE_PROJECTS, + pushComposeStatsTick, + resetComposeStatsStore, + useComposeStatsStore, +} from "./composeStats"; + +function makeStats(overrides: Partial = {}): DockerContainerStats { + return { + cpuPerc: "10.00%", + memUsage: "100MiB / 114.3GiB", + memPerc: "0.09%", + netIo: "1MB / 500kB", + blockIo: "2MB / 4MB", + pids: "10", + ...overrides, + }; +} + +beforeEach(() => { + resetComposeStatsStore(); +}); + +describe("aggregateComposeTick", () => { + it("sums CPU, memory, I/O, and PIDs while keeping shared Docker VM limit instead of multiplying it", () => { + const t0 = 1_700_000_000_000; + const tick = aggregateComposeTick( + { + "r-1": makeStats({ + cpuPerc: "25.50%", + memUsage: "100MiB / 114.3GiB", + netIo: "1MB / 200kB", + blockIo: "5MB / 10MB", + pids: "17", + }), + "r-2": makeStats({ + cpuPerc: "90.50%", + memUsage: "200MiB / 114.3GiB", + netIo: "2MB / 300kB", + blockIo: "3MB / 6MB", + pids: "16", + }), + }, + null, + t0, + ); + + expect(tick.aggregate.cpuPercent).toBeCloseTo(116.0, 5); + expect(tick.aggregate.memUsedBytes).toBe(300 * 1024 ** 2); + // Shared VM memory limit is not multiplied by 2. + expect(tick.aggregate.memLimitBytes).toBeCloseTo(114.3 * 1024 ** 3, -5); + expect(tick.aggregate.netRxBytes).toBe(3_000_000); + expect(tick.aggregate.netTxBytes).toBe(500_000); + expect(tick.aggregate.diskReadBytes).toBe(8_000_000); + expect(tick.aggregate.diskWriteBytes).toBe(16_000_000); + expect(tick.aggregate.pids).toBe(33); + }); + + it("sums distinct per-container cgroup memory limits", () => { + const tick = aggregateComposeTick( + { + db: makeStats({ memUsage: "1GiB / 2GiB" }), + api: makeStats({ memUsage: "512MiB / 4GiB" }), + }, + null, + 1000, + ); + expect(tick.aggregate.memLimitBytes).toBe(6 * 1024 ** 3); + }); + + it("computes summed I/O rates per container so a container stopping or restarting does not zero healthy containers", () => { + const t0 = 1_700_000_000_000; + const tick1 = aggregateComposeTick( + { + c1: makeStats({ blockIo: "10MB / 20MB", netIo: "5MB / 1MB" }), + c2: makeStats({ blockIo: "50MB / 100MB", netIo: "40MB / 10MB" }), + }, + null, + t0, + ); + // At t0 + 2s: c1 writes +4MB and receives +2MB; c2 restarted with counters reset near zero. + const tick2 = aggregateComposeTick( + { + c1: makeStats({ blockIo: "12MB / 24MB", netIo: "7MB / 2MB" }), + c2: makeStats({ blockIo: "0B / 0B", netIo: "0B / 0B" }), + }, + tick1, + t0 + 2000, + ); + + const { points } = deriveStatsSeries([tick1.aggregate, tick2.aggregate], 60_000); + expect(points).toHaveLength(2); + // Only c1's valid forward delta contributes: read 1 MB/s, write 2 MB/s, rx 1 MB/s, tx 500 kB/s. + expect(points[1]!.diskReadRate).toBe(1_000_000); + expect(points[1]!.diskWriteRate).toBe(2_000_000); + expect(points[1]!.netRxRate).toBe(1_000_000); + expect(points[1]!.netTxRate).toBe(500_000); + }); +}); + +describe("compose stats ring buffer store", () => { + it("caps per-project ticks and LRU-evicts oldest projects", () => { + const scope = composeStatsScope("default", "stack-0"); + for (let i = 0; i < MAX_COMPOSE_STATS_TICKS + 15; i++) { + pushComposeStatsTick(scope, { c1: makeStats() }, 1_700_000_000_000 + i * 3000); + } + const ticks = useComposeStatsStore.getState().byScope[scope]!; + expect(ticks).toHaveLength(MAX_COMPOSE_STATS_TICKS); + + for (let p = 1; p <= MAX_TRACKED_COMPOSE_PROJECTS + 1; p++) { + pushComposeStatsTick(composeStatsScope("default", `stack-${p}`), { c1: makeStats() }, 1000); + } + const scopes = Object.keys(useComposeStatsStore.getState().byScope); + expect(scopes).toHaveLength(MAX_TRACKED_COMPOSE_PROJECTS); + expect(scopes).not.toContain(scope); + + clearComposeStatsHistory(composeStatsScope("default", `stack-${MAX_TRACKED_COMPOSE_PROJECTS + 1}`)); + expect(Object.keys(useComposeStatsStore.getState().byScope)).toHaveLength(MAX_TRACKED_COMPOSE_PROJECTS - 1); + }); +}); diff --git a/src/features/services/composeStats.ts b/src/features/services/composeStats.ts new file mode 100644 index 0000000000..944dd56e25 --- /dev/null +++ b/src/features/services/composeStats.ts @@ -0,0 +1,196 @@ +/** + * Bounded per-Compose-project resource history store and aggregation helpers. + * + * Each 3s `ComposeProjectDashboard` poll pushes one `ComposeStatsTick` holding both + * the raw per-container snapshot (so crosshair scrubbing updates the Services table + * with exact per-service attribution) and the summed stack-level `StatsSample` + * (computing I/O rates per container first so a single container stopping or + * restarting does not introduce false drops into the stack rate). + */ +import { create } from "zustand"; +import type { DockerContainerStats } from "@/platform/ipc"; +import { + MAX_CONTINUOUS_GAP_MS, + sampleFromLegacyStats, + type PrecomputedIoRates, + type StatsSample, +} from "./containerStats"; + +/** 15 minutes at the default 3s poll cadence. */ +export const MAX_COMPOSE_STATS_TICKS = 300; +/** Cap retained histories across Compose projects so memory stays bounded. */ +export const MAX_TRACKED_COMPOSE_PROJECTS = 8; + +export interface ComposeStatsTick { + timestampMs: number; + byId: Record; + aggregate: StatsSample; +} + +interface ComposeStatsStore { + byScope: Record; + order: string[]; +} + +const INITIAL_STORE: ComposeStatsStore = { + byScope: {}, + order: [], +}; + +export const useComposeStatsStore = create(() => ({ ...INITIAL_STORE })); + +export function composeStatsScope(conn: string, project: string): string { + return `${conn}\0${project}`; +} + +/** + * Aggregates one tick of per-container `docker stats` snapshots into a stack-level + * `StatsSample`, computing I/O rates per container against `prevTick` when continuous. + */ +export function aggregateComposeTick( + byId: Record, + prevTick: ComposeStatsTick | null, + timestampMs: number, +): ComposeStatsTick { + const entries = Object.entries(byId); + const parsed = new Map(); + let cpuPercent = 0; + let memUsedBytes = 0; + let netRxBytes = 0; + let netTxBytes = 0; + let diskReadBytes = 0; + let diskWriteBytes = 0; + let pids = 0; + const limits: number[] = []; + + for (const [id, stats] of entries) { + const sample = sampleFromLegacyStats(stats, timestampMs); + parsed.set(id, sample); + cpuPercent += sample.cpuPercent; + memUsedBytes += sample.memUsedBytes; + netRxBytes += sample.netRxBytes; + netTxBytes += sample.netTxBytes; + diskReadBytes += sample.diskReadBytes; + diskWriteBytes += sample.diskWriteBytes; + pids += sample.pids; + if (sample.memLimitBytes > 0) limits.push(sample.memLimitBytes); + } + + let memLimitBytes = 0; + if (limits.length === 1) { + memLimitBytes = limits[0]!; + } else if (limits.length > 1) { + const firstLimit = limits[0]!; + const allEqual = limits.every((l) => l === firstLimit); + // All replicas reporting the exact same limit usually reflects the shared Docker VM RAM; + // only sum when containers carry distinct cgroup caps or combined usage exceeds one limit. + memLimitBytes = allEqual && memUsedBytes <= firstLimit ? firstLimit : limits.reduce((acc, l) => acc + l, 0); + } + const memPercent = memLimitBytes > 0 ? Math.min(100, (memUsedBytes / memLimitBytes) * 100) : 0; + + let rates: PrecomputedIoRates = { diskRead: null, diskWrite: null, netRx: null, netTx: null }; + const dtMs = prevTick ? timestampMs - prevTick.timestampMs : 0; + if (prevTick && dtMs > 0 && dtMs <= MAX_CONTINUOUS_GAP_MS) { + let diskReadSum = 0; + let diskReadCount = 0; + let diskWriteSum = 0; + let diskWriteCount = 0; + let netRxSum = 0; + let netRxCount = 0; + let netTxSum = 0; + let netTxCount = 0; + + for (const [id, curr] of parsed) { + const prevRaw = prevTick.byId[id]; + if (!prevRaw) continue; + const prev = sampleFromLegacyStats(prevRaw, prevTick.timestampMs); + if (curr.diskReadBytes >= prev.diskReadBytes) { + diskReadSum += ((curr.diskReadBytes - prev.diskReadBytes) * 1000) / dtMs; + diskReadCount += 1; + } + if (curr.diskWriteBytes >= prev.diskWriteBytes) { + diskWriteSum += ((curr.diskWriteBytes - prev.diskWriteBytes) * 1000) / dtMs; + diskWriteCount += 1; + } + if (curr.netRxBytes >= prev.netRxBytes) { + netRxSum += ((curr.netRxBytes - prev.netRxBytes) * 1000) / dtMs; + netRxCount += 1; + } + if (curr.netTxBytes >= prev.netTxBytes) { + netTxSum += ((curr.netTxBytes - prev.netTxBytes) * 1000) / dtMs; + netTxCount += 1; + } + } + + rates = { + diskRead: diskReadCount > 0 ? diskReadSum : null, + diskWrite: diskWriteCount > 0 ? diskWriteSum : null, + netRx: netRxCount > 0 ? netRxSum : null, + netTx: netTxCount > 0 ? netTxSum : null, + }; + } + + return { + timestampMs, + byId: { ...byId }, + aggregate: { + timestampMs, + cpuPercent, + onlineCpus: null, + memUsedBytes, + memLimitBytes, + memPercent, + netRxBytes, + netTxBytes, + diskReadBytes, + diskWriteBytes, + pids, + approximateIo: true, + rates, + }, + }; +} + +export function pushComposeStatsTick( + scope: string, + byId: Record, + timestampMs = Date.now(), +): void { + if (Object.keys(byId).length === 0) return; + useComposeStatsStore.setState((state) => { + const existing = state.byScope[scope] ?? []; + const prev = existing.at(-1) ?? null; + const effectiveTs = prev && timestampMs <= prev.timestampMs ? prev.timestampMs + 1 : timestampMs; + const tick = aggregateComposeTick(byId, prev, effectiveTs); + const nextTicks = + existing.length >= MAX_COMPOSE_STATS_TICKS + ? [...existing.slice(existing.length - MAX_COMPOSE_STATS_TICKS + 1), tick] + : [...existing, tick]; + const nextOrder = [...state.order.filter((k) => k !== scope), scope]; + const nextByScope: Record = { ...state.byScope, [scope]: nextTicks }; + while (nextOrder.length > MAX_TRACKED_COMPOSE_PROJECTS) { + const evicted = nextOrder.shift(); + if (evicted && evicted !== scope) { + delete nextByScope[evicted]; + } + } + return { byScope: nextByScope, order: nextOrder }; + }); +} + +export function clearComposeStatsHistory(scope: string): void { + useComposeStatsStore.setState((state) => { + if (!(scope in state.byScope)) return state; + const nextByScope = { ...state.byScope }; + delete nextByScope[scope]; + return { + byScope: nextByScope, + order: state.order.filter((k) => k !== scope), + }; + }); +} + +/** Resets Compose stats history (intended for tests). */ +export function resetComposeStatsStore(): void { + useComposeStatsStore.setState({ ...INITIAL_STORE }); +} diff --git a/src/features/services/containerStats.ts b/src/features/services/containerStats.ts index 14af803ca3..24387d50c8 100644 --- a/src/features/services/containerStats.ts +++ b/src/features/services/containerStats.ts @@ -38,6 +38,13 @@ export const MAX_CONTINUOUS_GAP_MS = 15_000; /** Default polling fallback delay (`top` interval) when streaming is unavailable. */ export const STATS_FALLBACK_POLL_MS = 3000; +export interface PrecomputedIoRates { + diskRead: number | null; + diskWrite: number | null; + netRx: number | null; + netTx: number | null; +} + export interface StatsSample { timestampMs: number; cpuPercent: number; @@ -53,6 +60,8 @@ export interface StatsSample { approximateIo: boolean; /** Original CLI strings when sampled via legacy one-shot `docker stats` fallback. */ raw?: DockerContainerStats; + /** Optional pre-aggregated I/O rates (used by Compose stacks to sum per-container rates cleanly). */ + rates?: PrecomputedIoRates; } export interface DerivedStatsPoint { @@ -332,12 +341,13 @@ export function deriveStatsSeries( return ((b - a) * 1000) / dtMs; }; if (i >= firstVisible) { + const pre = !gapBefore ? curr.rates : undefined; points.push({ sample: curr, - diskReadRate: rate(prev?.diskReadBytes ?? 0, curr.diskReadBytes), - diskWriteRate: rate(prev?.diskWriteBytes ?? 0, curr.diskWriteBytes), - netRxRate: rate(prev?.netRxBytes ?? 0, curr.netRxBytes), - netTxRate: rate(prev?.netTxBytes ?? 0, curr.netTxBytes), + diskReadRate: pre ? pre.diskRead : rate(prev?.diskReadBytes ?? 0, curr.diskReadBytes), + diskWriteRate: pre ? pre.diskWrite : rate(prev?.diskWriteBytes ?? 0, curr.diskWriteBytes), + netRxRate: pre ? pre.netRx : rate(prev?.netRxBytes ?? 0, curr.netRxBytes), + netTxRate: pre ? pre.netTx : rate(prev?.netTxBytes ?? 0, curr.netTxBytes), gapBefore: i > firstVisible && gapBefore, }); } diff --git a/src/features/services/dashboard.tsx b/src/features/services/dashboard.tsx index 6624df7965..02d0e00f36 100644 --- a/src/features/services/dashboard.tsx +++ b/src/features/services/dashboard.tsx @@ -59,7 +59,20 @@ import { isContainerOomKilled, useDevContainerResourceStatus, } from "./containerResources"; -import { clearContainerStatsHistory, containerStatsScope, useLiveContainerStatsHistory } from "./containerStats"; +import { ContainerStatsCharts } from "./ContainerStatsCharts"; +import { + clearComposeStatsHistory, + composeStatsScope, + pushComposeStatsTick, + useComposeStatsStore, + type ComposeStatsTick, +} from "./composeStats"; +import { + clearContainerStatsHistory, + containerStatsScope, + formatLocalClock, + useLiveContainerStatsHistory, +} from "./containerStats"; import { containerOp, endpointOf, errorMessage, useServices } from "./store"; import { useServicesTree } from "./tree"; import styles from "./Services.module.css"; @@ -781,13 +794,20 @@ function PropRow({ label, children, hidden }: { label: ReactNode; children: Reac ); } -function LineProgress({ percent }: { percent: number }) { +function LineProgress({ percent, tone = "auto" }: { percent: number; tone?: "auto" | "normal" }) { const clamped = Math.min(100, Math.max(0, percent)); - const tone = clamped >= 90 ? styles.progressDanger : clamped >= 75 ? styles.progressWarning : styles.progressNormal; + const toneClass = + tone === "normal" + ? styles.progressNormal + : clamped >= 90 + ? styles.progressDanger + : clamped >= 75 + ? styles.progressWarning + : styles.progressNormal; return (
0 ? Math.max(2, clamped) : 0}%` }} />
@@ -909,6 +929,8 @@ async function fetchContainerStatsMap( function useLiveContainerStats( conn: string, runningIdsKey: string, + paused = false, + onSample?: (byId: Record, timestampMs: number) => void, ): { byId: Record; loading: boolean; @@ -920,10 +942,14 @@ function useLiveContainerStats( byId: Record; settledScope: string; }>({ conn: "", byId: {}, settledScope: "" }); + const onSampleRef = useRef(onSample); + useEffect(() => { + onSampleRef.current = onSample; + }, [onSample]); useEffect(() => { const ids = runningIdsKey ? runningIdsKey.split("\0") : []; - if (!ids.length || !shown || !isTauri()) return; + if (!ids.length || paused || !shown || !isTauri()) return; let alive = true; let timer: ReturnType | undefined; let inFlight = false; @@ -945,6 +971,9 @@ function useLiveContainerStats( const byId = await fetchContainerStatsMap(conn, ids); if (alive) { setStatsState({ conn, byId, settledScope: statsScope }); + if (Object.keys(byId).length > 0) { + onSampleRef.current?.(byId, Date.now()); + } } } finally { inFlight = false; @@ -967,9 +996,9 @@ function useLiveContainerStats( clearTimer(); document.removeEventListener("visibilitychange", onVisibility); }; - }, [conn, runningIdsKey, shown, statsScope]); + }, [conn, runningIdsKey, paused, shown, statsScope]); - const active = Boolean(runningIdsKey) && shown && isTauri(); + const active = Boolean(runningIdsKey) && !paused && shown && isTauri(); return { byId: statsState.conn === conn ? statsState.byId : {}, loading: active && statsState.settledScope !== statsScope, @@ -1984,6 +2013,8 @@ export function NetworkDashboard({ ); } +const EMPTY_COMPOSE_TICKS: readonly ComposeStatsTick[] = []; + export function ComposeProjectDashboard({ conn, project, @@ -1995,6 +2026,7 @@ export function ComposeProjectDashboard({ containers: DockerContainer[]; snapshot: DockerSnapshot; }) { + const tx = useTx(); const txTemplate = useTxTemplate(); const target: DockerTarget = { conn, @@ -2029,7 +2061,34 @@ export function ComposeProjectDashboard({ .join("\0"), [containers], ); - const { byId: activeStats, loading: statsLoading } = useLiveContainerStats(conn, runningIdsKey); + const [statsPaused, setStatsPaused] = useState(false); + const [scrubbedTs, setScrubbedTs] = useState(null); + const composeScope = composeStatsScope(conn, project); + const composeTicks = useComposeStatsStore((s) => s.byScope[composeScope] ?? EMPTY_COMPOSE_TICKS); + const { byId: activeStats, loading: statsLoading } = useLiveContainerStats( + conn, + runningIdsKey, + statsPaused, + (byId, ts) => pushComposeStatsTick(composeScope, byId, ts), + ); + + const aggregateSamples = useMemo(() => composeTicks.map((tick) => tick.aggregate), [composeTicks]); + const scrubbedTick = useMemo( + () => (scrubbedTs !== null ? (composeTicks.find((tick) => tick.timestampMs === scrubbedTs) ?? null) : null), + [composeTicks, scrubbedTs], + ); + const tableStats = scrubbedTick ? scrubbedTick.byId : activeStats; + const totalTableMemBytes = useMemo(() => { + let sum = 0; + for (const c of containers) { + const s = tableStats[c.id]; + if (s) sum += parseUsagePair(s.memUsage).usedBytes; + } + return sum; + }, [containers, tableStats]); + const count = runningCount; + const clock = scrubbedTick ? formatLocalClock(scrubbedTick.timestampMs) : null; + const showProjectCharts = runningCount > 0 || aggregateSamples.length > 0; return (
@@ -2078,7 +2137,15 @@ export function ComposeProjectDashboard({
- + + {tx`Snapshot ${clock}`} + + ) : undefined + } + > Services
@@ -2111,10 +2178,15 @@ export function ComposeProjectDashboard({ {containers.map((c) => { const running = isRunning(c); - const stats = running ? activeStats[c.id] : undefined; + const stats = scrubbedTick ? tableStats[c.id] : running ? tableStats[c.id] : undefined; const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0; const memPair = stats ? parseUsagePair(stats.memUsage) : null; const memPct = memPair ? memPair.percent : stats ? parsePercent(stats.memPerc) : 0; + // When multiple uncapped replicas share a large VM (memPct < 10%), scale the + // table bar by each service's share of total stack memory so hotspots stand out. + const useStackShare = + runningCount > 1 && memPct < 10 && totalTableMemBytes > 0 && (memPair?.usedBytes ?? 0) > 0; + const memBarPct = useStackShare ? ((memPair?.usedBytes ?? 0) / totalTableMemBytes) * 100 : memPct; return ( @@ -2147,7 +2219,7 @@ export function ComposeProjectDashboard({ {stats.memUsage} ({stats.memPerc}) - +
) : running && statsLoading ? ( @@ -2173,6 +2245,31 @@ export function ComposeProjectDashboard({
+ {showProjectCharts && ( + Project Resource Usage} + statusMeta={count > 0 ? tx`${count} running` : null} + multiContainer={containers.length > 1} + samples={aggregateSamples} + running={runningCount > 0} + paused={statsPaused} + statsLoading={statsLoading} + onTogglePause={() => setStatsPaused((p) => !p)} + onClear={() => { + setScrubbedTs(null); + clearComposeStatsHistory(composeScope); + }} + onActiveTimestampChange={setScrubbedTs} + cpuLimit={null} + cpuLimitText={null} + vmCpuText={null} + memoryLimitBytes={null} + memLimitText={null} + vmMemText={null} + sourceLabel={null} + /> + )} + (data: T) => ({ status: "ok" as const, data }); @@ -85,6 +86,7 @@ const snapshot: DockerSnapshot = { beforeEach(() => { vi.useFakeTimers(); resetContainerStatsStore(); + resetComposeStatsStore(); backend.stats.mockReset(); backend.volumeSizes.mockReset(); backend.volumeSizes.mockResolvedValue(ok({})); @@ -585,3 +587,117 @@ describe("dev container resource limits and OOM reporting in Services", () => { expect(screen.getAllByRole("button", { name: "Open Configuration" }).length).toBeGreaterThanOrEqual(1); }); }); + +describe("Compose Project Resource Usage 2x2 charts and synchronized table scrubbing", () => { + it("sums running service metrics, scrubs the Services table on keyboard navigation, pauses polling, and preserves Last session", async () => { + const apiRunning: DockerContainer = { + ...stoppedContainer, + state: "running", + status: "Up 15 minutes", + }; + const bothRunning = [runningContainer, apiRunning]; + const perIdRound: Record = {}; + backend.stats.mockImplementation(async (_ep, id: string) => { + const n = (perIdRound[id] ?? 0) + 1; + perIdRound[id] = n; + if (n === 1) { + return ok( + id === "db-1" + ? { + cpuPerc: "80.00%", + memUsage: "200MiB / 114.3GiB", + memPerc: "0.17%", + netIo: "2MB / 1MB", + blockIo: "10MB / 20MB", + pids: "10", + } + : { + cpuPerc: "20.00%", + memUsage: "100MiB / 114.3GiB", + memPerc: "0.09%", + netIo: "1MB / 500kB", + blockIo: "5MB / 10MB", + pids: "8", + }, + ); + } + return ok( + id === "db-1" + ? { + cpuPerc: "5.00%", + memUsage: "210MiB / 114.3GiB", + memPerc: "0.18%", + netIo: "5MB / 2MB", + blockIo: "16MB / 26MB", + pids: "11", + } + : { + cpuPerc: "15.00%", + memUsage: "110MiB / 114.3GiB", + memPerc: "0.09%", + netIo: "4MB / 1.5MB", + blockIo: "8MB / 13MB", + pids: "9", + }, + ); + }); + + const { rerender } = render( + + + , + ); + + await act(async () => { + await Promise.resolve(); + }); + expect(screen.getByText("Project Resource Usage")).toBeInTheDocument(); + expect(screen.getByText("2 running")).toBeInTheDocument(); + expect(screen.getByText("PIDs 18")).toBeInTheDocument(); + const cpuCard = screen.getByRole("group", { name: "CPU" }); + expect(within(cpuCard).getByRole("img", { name: "CPU: 100%" })).toBeInTheDocument(); + + // Second tick (3s later): CPU drops to 20.0% summed (5% + 15%), PIDs rises to 20. + await act(async () => { + await vi.advanceTimersByTimeAsync(CONTAINER_STATS_POLL_MS); + }); + expect(within(cpuCard).getByRole("img", { name: "CPU: 20.0%" })).toBeInTheDocument(); + expect(screen.getByText("PIDs 20")).toBeInTheDocument(); + expect(screen.getByText("5.00%")).toBeInTheDocument(); + + // Scrubbing back to tick 0 (`Home`) shows the Snapshot badge and attributes 80.00% to db-1 in the Services table. + const region = screen.getByRole("region", { name: "Container resource metrics" }); + fireEvent.keyDown(region, { key: "Home" }); + expect(screen.getByText(/^Snapshot /)).toBeInTheDocument(); + expect(screen.getByText("80.00%")).toBeInTheDocument(); + expect(within(cpuCard).getByRole("img", { name: "CPU: 100%" })).toBeInTheDocument(); + + // Escape returns Services table to live stats. + fireEvent.keyDown(region, { key: "Escape" }); + expect(screen.queryByText(/^Snapshot /)).not.toBeInTheDocument(); + expect(screen.getByText("5.00%")).toBeInTheDocument(); + + // Pausing metrics stops further 3s polling. + const callsBeforePause = backend.stats.mock.calls.length; + fireEvent.click(screen.getByRole("button", { name: "Pause metrics" })); + expect(screen.getByText("Paused")).toBeInTheDocument(); + await act(async () => { + await vi.advanceTimersByTimeAsync(CONTAINER_STATS_POLL_MS * 3); + }); + expect(backend.stats).toHaveBeenCalledTimes(callsBeforePause); + + // Stopping all services preserves recorded charts with Last session badge. + rerender( + + + , + ); + expect(screen.getByText("Last session")).toBeInTheDocument(); + expect(screen.getByRole("group", { name: "CPU" })).toBeInTheDocument(); + }); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e4d6159c15..dca8307135 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -5393,6 +5393,8 @@ "Peak {peak}": "Peak {peak}", "Total {total}": "Total {total}", "PIDs {pids}": "PIDs {pids}", + "Project Resource Usage": "Project Resource Usage", + "Snapshot {clock}": "Snapshot {clock}", "{memoryBytes} RAM": "{memoryBytes} RAM", "{storageBytes} storage": "{storageBytes} storage", "OOM killed": "OOM killed", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 591f5715e9..6f8c5b89ac 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -12291,6 +12291,8 @@ "Peak {peak}": "峰值 {peak}", "Total {total}": "累计 {total}", "PIDs {pids}": "进程数 {pids}", + "Project Resource Usage": "项目资源使用情况", + "Snapshot {clock}": "快照 {clock}", "{memoryBytes} RAM": "{memoryBytes} 内存", "{storageBytes} storage": "{storageBytes} 存储", "OOM killed": "OOM 终止",