feat(services): show Docker volume disk usage across dashboards (#5545)

Add a docker_volume_sizes command (docker system df -v, Engine API fallback) and show each volume's disk usage in the Volume, Compose project and Container dashboards, refreshed every 30 seconds while the Services tool window is visible.
Цей коміт міститься в:
Deng Liu authored and GitHub committed 2026-11-24 19:58:10 +08:00
1 джерело 64a168a2d1
коміт 7419eb85c8
16 files changed
+644 -31

No files matched your search

+56
Переглянути файл
@@ -557,6 +557,53 @@ fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
.collect()
}
/// Per-volume disk usage (`GET /system/df?type=volume`).
pub(crate) fn volume_sizes(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<BTreeMap<String, String>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", "/system/df?type=volume", timeout)?)?;
map_volume_sizes(&body)
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiDiskUsage {
volumes: Option<Vec<ApiVolumeUsage>>,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiVolumeUsage {
name: String,
usage_data: Option<ApiVolumeUsageData>,
}
const fn unknown_volume_size() -> i64 {
-1
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiVolumeUsageData {
#[serde(default = "unknown_volume_size")]
size: i64,
}
fn map_volume_sizes(body: &str) -> IdeResult<BTreeMap<String, String>> {
let parsed = serde_json::from_str::<ApiDiskUsage>(body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's disk usage is not JSON: {e}")))?;
Ok(parsed
.volumes
.unwrap_or_default()
.into_iter()
.filter_map(|v| {
let size = v.usage_data?.size;
(!v.name.is_empty() && size >= 0).then(|| (v.name, human_size(size)))
})
.collect())
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
@@ -1158,6 +1205,15 @@ mod tests {
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
let sizes = map_volume_sizes(
r#"{"Volumes":[{"Name":"shop_pgdata","UsageData":{"RefCount":1,"Size":145442}},{"Name":"empty","UsageData":{"RefCount":0,"Size":0}},{"Name":"remote","UsageData":{"RefCount":1,"Size":-1}},{"Name":"missing","UsageData":null}]}"#,
)
.unwrap();
assert_eq!(sizes.get("shop_pgdata").map(String::as_str), Some("145.442kB"));
assert_eq!(sizes.get("empty").map(String::as_str), Some("0B"));
assert!(!sizes.contains_key("remote"));
assert!(!sizes.contains_key("missing"));
assert!(map_volume_sizes(r#"{"Volumes":null}"#).unwrap().is_empty());
}
#[test]
+11
Переглянути файл
@@ -315,6 +315,17 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
}
/// Per-volume disk usage (`docker system df -v --format '{{json .Volumes}}'`).
pub fn volume_sizes(ep: &DockerEndpoint) -> IdeResult<std::collections::BTreeMap<String, String>> {
if docker_executable().is_none()
&& let Some(sizes) = engine::volume_sizes(ep, QUICK)
{
return sizes;
}
let out = run(ep, &["system", "df", "-v", "--format", "{{json .Volumes}}"], QUICK)?;
Ok(parse_volume_sizes(&out))
}
/// How long log lines collect before they are handed on together.
const LOG_BATCH: Duration = Duration::from_millis(30);
+27
Переглянути файл
@@ -473,6 +473,33 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
})
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawVolumeUsage {
name: String,
size: String,
}
/// `docker system df -v --format '{{json .Volumes}}'` volume name → human size.
pub fn parse_volume_sizes(text: &str) -> BTreeMap<String, String> {
let trimmed = text.trim();
let items: Vec<RawVolumeUsage> = if trimmed.is_empty() || trimmed == "null" {
Vec::new()
} else if let Ok(parsed) = serde_json::from_str::<Option<Vec<RawVolumeUsage>>>(trimmed) {
parsed.unwrap_or_default()
} else {
lines::<RawVolumeUsage>(text).collect()
};
items
.into_iter()
.filter(|v| {
let size = v.size.trim();
!v.name.is_empty() && !size.is_empty() && !size.eq_ignore_ascii_case("n/a")
})
.map(|v| (v.name, v.size.trim().to_owned()))
.collect()
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct RawVersion {
+9 -1
Переглянути файл
@@ -2,7 +2,7 @@
use ide_docker::{
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
parse_networks, parse_volumes,
parse_networks, parse_volume_sizes, parse_volumes,
};
const PS: &str = include_str!("fixtures/ps.jsonl");
@@ -113,4 +113,12 @@ fn image_history_top_and_stats() {
assert_eq!(stats.net_io, "12kB / 8kB");
assert_eq!(stats.block_io, "1.2MB / 0B");
assert_eq!(stats.pids, "14");
let df_volumes = r#"[{"Availability":"N/A","Driver":"local","Links":"4","Mountpoint":"/var/lib/docker/volumes/selfhost_runner-persist/_data","Name":"selfhost_runner-persist","Scope":"local","Size":"145.4kB"},{"Name":"unused_anon","Size":"0B"},{"Name":"remote_nfs","Size":"N/A"}]"#;
let volume_sizes = parse_volume_sizes(df_volumes);
assert_eq!(volume_sizes.get("selfhost_runner-persist").map(String::as_str), Some("145.4kB"));
assert_eq!(volume_sizes.get("unused_anon").map(String::as_str), Some("0B"));
assert!(!volume_sizes.contains_key("remote_nfs"));
assert!(parse_volume_sizes("null\n").is_empty());
assert!(parse_volume_sizes("").is_empty());
}
+3 -3
Переглянути файл
@@ -69,10 +69,10 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
Selecting an item shows tabs in the detail pane:
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project with live disk usage).
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts with live volume disk usage, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
- **Volume** and **network**: **Dashboard** and **Inspect**.
- **Volume** and **network**: **Dashboard** (including live volume disk usage) and **Inspect**.
**Open Log in Editor** opens the log in an editor tab with **Timestamps**, **Soft-wrap**, **Find in Logs** and **Clear**.
+3 -3
Переглянути файл
@@ -69,10 +69,10 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
选中某项后,详情区会显示以下标签页:
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷及其实时磁盘占用)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载及数据卷实时磁盘占用、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
- **卷** 和 **网络**:**仪表盘**(含数据卷实时磁盘占用)和 **检查**。
**在编辑器中打开日志** 会在编辑器标签页中打开日志,提供 **时间戳**、**软换行**、**在日志中查找** 和 **清除**。
+125
Переглянути файл
@@ -787,3 +787,128 @@ test("Docker Compose dashboard keeps its action row pinned when scrolling", asyn
expect(afterDown.y).toBe(beforeDown.y);
expect(afterBanner.y).toBeLessThan(beforeBanner.y - 100);
});
test("Docker volume, Compose, and container dashboards show volume disk usage", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
(window as unknown as { __volSize: string }).__volSize = "145.4kB";
const inspectJson = JSON.stringify([
{
Created: "2026-11-23T02:37:25Z",
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-23T02:37:26Z" },
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
Config: { Entrypoint: [], Cmd: ["./bin/Runner.Listener", "run"], Env: [], Labels: {} },
Mounts: [
{
Type: "volume",
Name: "selfhost_runner-persist",
Source: "/var/lib/docker/volumes/selfhost_runner-persist/_data",
Destination: "/persist",
Mode: "rw",
RW: true,
},
],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
const snapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" },
executable: "/usr/bin/docker",
containers: [
{
id: "runner-1",
name: "selfhost-github-runner-1",
image: "myoung34/github-runner:latest",
command: "./bin/Runner.Listener run",
state: "running",
status: "Up 24 hours",
ports: "",
createdAt: "2026-11-23T02:37:25Z",
composeProject: "selfhost",
composeService: "github-runner-1",
composeWorkingDir: "/work/selfhost",
composeFiles: ["/work/selfhost/docker-compose.yml"],
mounts: ["selfhost_runner-persist"],
networks: ["selfhost_default"],
},
],
images: [],
volumes: [
{
name: "selfhost_runner-persist",
driver: "local",
mountpoint: "/var/lib/docker/volumes/selfhost_runner-persist/_data",
composeProject: "selfhost",
scope: "local",
labels: {
"com.docker.compose.project": "selfhost",
"com.docker.compose.volume": "runner-persist",
},
},
],
networks: [
{ id: "net-1", name: "selfhost_default", driver: "bridge", scope: "local", composeProject: "selfhost" },
],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.docker_inspect = () => inspectJson;
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "0.02%",
memUsage: "96MiB / 114GiB",
memPerc: "0.08%",
netIo: "1.1MB / 3.8MB",
blockIo: "512kB / 201kB",
pids: "16",
});
window.__ipc.handlers.docker_volume_sizes = () => ({
"selfhost_runner-persist": (window as unknown as { __volSize: string }).__volSize,
});
const storeMod = "/src/features/services/store.ts";
const treeMod = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeMod);
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
useServices.setState({
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { default: { snapshot, loading: false, error: null } },
detailTab: "dashboard",
});
useServicesTree.setState({
expanded: new Set(["docker:default"]),
selectedKey: "docker:default:compose:selfhost",
selectedKeys: new Set(["docker:default:compose:selfhost"]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
const detail = services.locator("[data-panel][id=services-detail]");
// 1. Compose dashboard shows volume disk usage on the chip and the banner.
const volumeChip = detail.getByRole("button", { name: /selfhost_runner-persist/ });
await expect(volumeChip).toContainText("runner-persist · local · 145.4kB");
await expect(detail).toContainText("Disk usage: 145.4kB");
// 2. Opening the volume samples again; the dashboard shows the current size.
await page.evaluate(() => {
(window as unknown as { __volSize: string }).__volSize = "210.8kB";
});
await volumeChip.click();
await expect(detail.getByText("Volume Overview")).toBeVisible();
await expect(detail).toContainText("210.8kB");
// 3. The container dashboard shows the size beside the volume mount.
await page.evaluate(() => {
(window as unknown as { __volSize: string }).__volSize = "380.2kB";
});
await detail.getByRole("button", { name: /selfhost-github-runner-1/ }).click();
await expect(detail.getByText("Volume & Bind Mounts")).toBeVisible();
await expect(detail).toContainText("380.2kB");
});
+13
Переглянути файл
@@ -130,6 +130,18 @@ pub async fn docker_container_stats(
blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Disk usage per volume name (`docker system df -v`).
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn docker_volume_sizes(
state: State<'_, AppState>,
endpoint: DockerEndpoint,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
let endpoint = resolve(&state, endpoint).await?;
blocking(move || ide_docker::volume_sizes(&endpoint)).await
}
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
#[desktop_command(trust = trusted)]
#[tauri::command]
@@ -308,4 +320,5 @@ ide_command::desktop_domain!(
docker_set_registry_password,
docker_settings,
docker_snapshot,
docker_volume_sizes,
);
+1
Переглянути файл
@@ -258,6 +258,7 @@ docker_save_settings always desktop bin
docker_set_registry_password always desktop bindings async
docker_settings always desktop bindings async
docker_snapshot trusted desktop bindings async
docker_volume_sizes trusted desktop bindings async
end_process trusted desktop bindings async
env_reload always project_host bindings async
file_dialog_needs_gtk trusted desktop bindings async
+2
Переглянути файл
@@ -637,6 +637,8 @@ export const commands = {
dockerSettings: () => typedError<DockerSettings, IdeError>(__TAURI_INVOKE("docker_settings")),
/** Availability plus containers, images, volumes and networks. */
dockerSnapshot: (endpoint: DockerEndpoint) => typedError<DockerSnapshot, IdeError>(__TAURI_INVOKE("docker_snapshot", { endpoint })),
/** Disk usage per volume name (`docker system df -v`). */
dockerVolumeSizes: (endpoint: DockerEndpoint) => typedError<{ [key in string]: string }, IdeError>(__TAURI_INVOKE("docker_volume_sizes", { endpoint })),
/**
* "Clear caches": drops syntax trees and EditorConfig files of the window's
* project, shrinks the in-memory index and compacts its on-disk cache.
+5 -1
Переглянути файл
@@ -260,6 +260,10 @@
.dashboardActions + .sectionBanner {
border-top: 0;
}
.bannerMeta {
font-weight: 400;
color: var(--fg-secondary);
}
.propList {
display: flex;
flex-direction: column;
@@ -517,7 +521,7 @@ button.entityChip:not(:disabled):hover {
}
.dataRow {
display: grid;
grid-template-columns: 72px minmax(120px, 1fr) minmax(140px, 1.3fr) 56px;
grid-template-columns: 72px minmax(120px, 1fr) minmax(120px, 1.2fr) 88px 56px;
gap: var(--space-2);
align-items: center;
padding: 4px 12px;
+172 -19
Переглянути файл
@@ -113,6 +113,20 @@ export function bytesToUnits(bytes: number, precision = 1): string {
return `${val.toFixed(precision)} ${units[idx]!}`;
}
export function bytesToDecimalUnits(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) return "0B";
const units = ["B", "kB", "MB", "GB", "TB", "PB"];
let idx = 0;
let val = bytes;
while (val >= 1000 && idx < units.length - 1) {
val /= 1000;
idx++;
}
if (idx === 0) return `${Math.round(val)}B`;
const text = val.toFixed(3).replace(/\.?0+$/, "");
return `${text}${units[idx]!}`;
}
export function parsePercent(raw: string | undefined | null): number {
if (!raw) return 0;
const n = Number.parseFloat(raw.replace(/%/g, "").trim());
@@ -816,9 +830,11 @@ function ContainerLinkChip({ conn, container }: { conn: string; container: Docke
);
}
function VolumeLinkChip({ conn, volume }: { conn: string; volume: DockerVolume }) {
function VolumeLinkChip({ conn, volume, size }: { conn: string; volume: DockerVolume; size?: string }) {
const composeVol = volume.labels?.["com.docker.compose.volume"];
const meta = composeVol && composeVol !== volume.name ? `${composeVol} · ${volume.driver}` : volume.driver;
const meta = [composeVol && composeVol !== volume.name ? composeVol : null, volume.driver, size]
.filter(Boolean)
.join(" · ");
return (
<button
type="button"
@@ -841,6 +857,9 @@ const STATS_CONCURRENCY = 6;
/** Default `top` refresh delay (3s) between live `docker stats --no-stream` samples. */
export const CONTAINER_STATS_POLL_MS = 3000;
/** Between `docker system df -v` samples, which make the daemon measure every volume. */
export const VOLUME_SIZES_POLL_MS = 30_000;
async function fetchContainerStatsMap(
conn: string,
ids: readonly string[],
@@ -932,6 +951,88 @@ function useLiveContainerStats(
};
}
function useLiveVolumeSizes(
conn: string,
scopeKey: string,
enabled = true,
): {
byName: Record<string, string>;
loading: boolean;
} {
const shown = useToolWindowShown();
const fullScope = `${conn}\0${scopeKey}`;
const [sizeState, setSizeState] = useState<{
conn: string;
byName: Record<string, string>;
settledScope: string;
}>({ conn: "", byName: {}, settledScope: "" });
useEffect(() => {
if (!enabled || !scopeKey || !shown || !isTauri()) return;
let alive = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let inFlight = false;
const clearTimer = () => {
if (timer !== undefined) {
clearTimeout(timer);
timer = undefined;
}
};
const isDocumentHidden = () => document.visibilityState === "hidden";
const sample = async () => {
clearTimer();
if (!alive || inFlight || isDocumentHidden()) return;
inFlight = true;
try {
const raw = await call(commands.dockerVolumeSizes(endpointOf(conn)));
if (alive) {
const byName: Record<string, string> = {};
for (const [k, v] of Object.entries(raw)) {
if (v) byName[k] = v;
}
setSizeState({ conn, byName, settledScope: fullScope });
}
} catch {
if (alive) {
setSizeState((prev) => ({
conn,
byName: prev.conn === conn ? prev.byName : {},
settledScope: fullScope,
}));
}
} finally {
inFlight = false;
if (alive && !isDocumentHidden()) {
timer = setTimeout(() => void sample(), VOLUME_SIZES_POLL_MS);
}
}
};
const onVisibility = () => {
if (isDocumentHidden()) clearTimer();
else void sample();
};
document.addEventListener("visibilitychange", onVisibility);
if (!isDocumentHidden()) void sample();
return () => {
alive = false;
clearTimer();
document.removeEventListener("visibilitychange", onVisibility);
};
}, [conn, scopeKey, enabled, shown, fullScope]);
const active = Boolean(enabled && scopeKey) && shown && isTauri();
return {
byName: sizeState.conn === conn ? sizeState.byName : {},
loading: active && sizeState.settledScope !== fullScope,
};
}
// ---------------------------------------------------------------------------
// Container Dashboard & Processes View
@@ -979,6 +1080,18 @@ export function ContainerDashboard({
const { byId: statsById, loading: statsLoading } = useLiveContainerStats(conn, running ? container.id : "");
const stats = running ? (statsById[container.id] ?? null) : null;
const mountedVolumesKey = useMemo(() => {
const names = inspect?.mounts.length
? inspect.mounts.filter((m) => m.type === "volume" && m.name).map((m) => m.name!)
: (container.mounts ?? []).filter((m) => snapshot.volumes.some((v) => v.name === m));
return [...new Set(names)].sort().join("\0");
}, [inspect, container.mounts, snapshot.volumes]);
const { byName: volumeSizes, loading: volumeSizesLoading } = useLiveVolumeSizes(
conn,
mountedVolumesKey,
Boolean(mountedVolumesKey),
);
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
const labels = inspect?.labels.length ? inspect.labels : Object.entries(container.labels ?? {});
@@ -1221,12 +1334,17 @@ export function ContainerDashboard({
<span>
<T>Destination</T>
</span>
<span>
<T>Size</T>
</span>
<span>
<T>Mode</T>
</span>
</div>
{inspect.mounts.map((m) => {
const volumeObj = m.name ? snapshot.volumes.find((v) => v.name === m.name) : undefined;
const volumeName = m.type === "volume" ? m.name : undefined;
const volumeObj = volumeName ? snapshot.volumes.find((v) => v.name === volumeName) : undefined;
const mountSize = volumeName ? volumeSizes[volumeName] : undefined;
return (
<div key={`${m.destination}:${m.type}:${m.source}`} className={styles.dataRow}>
<span className={styles.badgeMuted}>{m.type}</span>
@@ -1251,6 +1369,14 @@ export function ContainerDashboard({
<span className={styles.mono} title={m.destination}>
{m.destination}
</span>
<span className={clsx(styles.mono, styles.nowrapCell)}>
{mountSize ??
(volumeName && volumeSizesLoading ? (
<Spinner size={12} />
) : (
<span className={styles.mutedMeta}>—</span>
))}
</span>
<span className={styles.mono}>{m.rw ? m.mode || "rw" : "ro"}</span>
</div>
);
@@ -1260,24 +1386,13 @@ export function ContainerDashboard({
<div className={styles.chipGroup}>
{container.mounts.map((m) => {
const volumeObj = snapshot.volumes.find((v) => v.name === m);
const mountSize = volumeSizes[m];
return volumeObj ? (
<button
key={m}
type="button"
className={styles.entityChip}
onClick={() => {
selectServicesTreeKey(
treeKey(conn, { kind: "volume", key: `volume:${volumeObj.name}`, volume: volumeObj }),
);
showDetail("dashboard");
}}
>
<Icon name="docker-volumes" size={14} />
<span className={styles.mono}>{m}</span>
</button>
<VolumeLinkChip key={m} conn={conn} volume={volumeObj} size={mountSize} />
) : (
<span key={m} className={styles.entityChip}>
<span className={styles.mono}>{m}</span>
{mountSize && <span className={styles.chipMeta}>{mountSize}</span>}
</span>
);
})}
@@ -1669,6 +1784,8 @@ export function VolumeDashboard({
const target: DockerTarget = { conn, node: { kind: "volume", key: `volume:${volume.name}`, volume } };
const usingContainers = useMemo(() => containersUsingVolume(snapshot, volume), [snapshot, volume]);
const labels = Object.entries(volume.labels ?? {}).sort((a, b) => a[0].localeCompare(b[0]));
const { byName: volumeSizes, loading: volumeSizesLoading } = useLiveVolumeSizes(conn, volume.name);
const diskUsage = volumeSizes[volume.name];
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
@@ -1688,6 +1805,17 @@ export function VolumeDashboard({
<PropRow label={<T>Name</T>}>
<span className={styles.mono}>{volume.name}</span>
</PropRow>
<PropRow label={<T>Disk usage</T>}>
{diskUsage ? (
<span className={styles.mono}>{diskUsage}</span>
) : volumeSizesLoading ? (
<span className={styles.mutedMeta}>
<T>Loading…</T>
</span>
) : (
<span className={styles.mutedMeta}>—</span>
)}
</PropRow>
<PropRow label={<T>Driver</T>}>
<span className={styles.mono}>{volume.driver}</span>
</PropRow>
@@ -1875,6 +2003,21 @@ export function ComposeProjectDashboard({
const first = containers[0];
const runningCount = containers.filter(isRunning).length;
const namedVolumes = useMemo(() => volumesInComposeProject(snapshot, project), [snapshot, project]);
const namedVolumesKey = useMemo(
() =>
namedVolumes
.map((v) => v.name)
.sort()
.join("\0"),
[namedVolumes],
);
const { byName: volumeSizes } = useLiveVolumeSizes(conn, namedVolumesKey, namedVolumes.length > 0);
const totalVolumeSize = useMemo(() => {
const sizes = namedVolumes.map((v) => volumeSizes[v.name]).filter((s): s is string => Boolean(s));
if (sizes.length === 0) return null;
if (sizes.length === 1) return sizes[0]!;
return bytesToDecimalUnits(sizes.reduce((sum, s) => sum + unitsToBytes(s), 0));
}, [namedVolumes, volumeSizes]);
const runningIdsKey = useMemo(
() =>
@@ -2029,13 +2172,23 @@ export function ComposeProjectDashboard({
</table>
</div>
<SectionBanner>
<SectionBanner
action={
totalVolumeSize ? (
<span className={styles.bannerMeta}>
<T>Disk usage</T>
{": "}
<span className={styles.mono}>{totalVolumeSize}</span>
</span>
) : undefined
}
>
<T>Volumes</T>
</SectionBanner>
{namedVolumes.length > 0 ? (
<div className={styles.chipGroup}>
{namedVolumes.map((v) => (
<VolumeLinkChip key={v.name} conn={conn} volume={v} />
<VolumeLinkChip key={v.name} conn={conn} volume={v} size={volumeSizes[v.name]} />
))}
</div>
) : (
+214 -4
Переглянути файл
@@ -1,10 +1,11 @@
import { act, cleanup, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DockerContainer, DockerContainerStats, DockerSnapshot } from "@/platform/ipc";
import type { DockerContainer, DockerContainerStats, DockerSnapshot, DockerVolume } from "@/platform/ipc";
import { ToolWindowShownProvider } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({
stats: vi.fn(),
volumeSizes: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => {
@@ -15,13 +16,21 @@ vi.mock("@/platform/ipc", async (original) => {
commands: {
...actual.commands,
dockerContainerStats: backend.stats,
dockerVolumeSizes: backend.volumeSizes,
},
};
});
import { ComposeProjectDashboard, CONTAINER_STATS_POLL_MS, ContainerDashboard } from "./dashboard";
import {
bytesToDecimalUnits,
ComposeProjectDashboard,
CONTAINER_STATS_POLL_MS,
ContainerDashboard,
VOLUME_SIZES_POLL_MS,
VolumeDashboard,
} from "./dashboard";
const ok = (data: DockerContainerStats) => ({ status: "ok" as const, data });
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
function makeStats(cpuPerc: string): DockerContainerStats {
return {
@@ -73,6 +82,8 @@ const snapshot: DockerSnapshot = {
beforeEach(() => {
vi.useFakeTimers();
backend.stats.mockReset();
backend.volumeSizes.mockReset();
backend.volumeSizes.mockResolvedValue(ok({}));
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
});
@@ -151,7 +162,7 @@ describe("live container stats polling", () => {
});
it("auto-refreshes ContainerDashboard without overlapping slow stats calls", async () => {
let resolvePending: ((v: ReturnType<typeof ok>) => void) | undefined;
let resolvePending: ((v: ReturnType<typeof ok<DockerContainerStats>>) => void) | undefined;
backend.stats
.mockImplementationOnce(
() =>
@@ -164,6 +175,8 @@ describe("live container stats polling", () => {
render(<ContainerDashboard conn="default" container={runningContainer} snapshot={snapshot} inspectText={null} />);
expect(backend.stats).toHaveBeenCalledTimes(1);
// Container without volume mounts does not poll dockerVolumeSizes.
expect(backend.volumeSizes).not.toHaveBeenCalled();
// Slow first sample (4.5s > 3s): no overlapping second call starts while in flight.
await act(async () => {
await vi.advanceTimersByTimeAsync(4500);
@@ -184,3 +197,200 @@ describe("live container stats polling", () => {
expect(screen.getByText("22.50%")).toBeInTheDocument();
});
});
describe("live volume disk usage polling", () => {
const pgVolume: DockerVolume = {
name: "shop_pgdata",
driver: "local",
mountpoint: "/var/lib/docker/volumes/shop_pgdata/_data",
composeProject: "shop",
scope: "local",
labels: {
"com.docker.compose.project": "shop",
"com.docker.compose.volume": "pgdata",
},
};
const cacheVolume: DockerVolume = {
name: "shop_redis",
driver: "local",
mountpoint: "/var/lib/docker/volumes/shop_redis/_data",
composeProject: "shop",
scope: "local",
labels: {
"com.docker.compose.project": "shop",
"com.docker.compose.volume": "redis",
},
};
const snapshotWithVolumes: DockerSnapshot = {
...snapshot,
volumes: [pgVolume, cacheVolume],
};
it("formats decimal byte totals like Docker CLI output", () => {
expect(bytesToDecimalUnits(0)).toBe("0B");
expect(bytesToDecimalUnits(512)).toBe("512B");
expect(bytesToDecimalUnits(145_400)).toBe("145.4kB");
expect(bytesToDecimalUnits(1_500_000_000)).toBe("1.5GB");
});
it("auto-refreshes VolumeDashboard disk usage every 30s while visible and pauses when hidden", async () => {
let sample = 0;
backend.volumeSizes.mockImplementation(async () => {
sample += 1;
return ok({ shop_pgdata: `${sample * 100}kB` });
});
const { rerender } = render(
<ToolWindowShownProvider value={true}>
<VolumeDashboard conn="default" volume={pgVolume} snapshot={snapshotWithVolumes} />
</ToolWindowShownProvider>,
);
await act(async () => {
await Promise.resolve();
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(1);
expect(backend.volumeSizes).toHaveBeenLastCalledWith({ kind: "default" });
expect(screen.getByText("100kB")).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS);
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(2);
expect(screen.getByText("200kB")).toBeInTheDocument();
// Pauses while hidden and resumes when visible again.
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
act(() => {
document.dispatchEvent(new Event("visibilitychange"));
});
await act(async () => {
await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS * 3);
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(2);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
await act(async () => {
document.dispatchEvent(new Event("visibilitychange"));
await Promise.resolve();
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(3);
expect(screen.getByText("300kB")).toBeInTheDocument();
// Stops polling when the Services tool window is closed.
rerender(
<ToolWindowShownProvider value={false}>
<VolumeDashboard conn="default" volume={pgVolume} snapshot={snapshotWithVolumes} />
</ToolWindowShownProvider>,
);
await act(async () => {
await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS * 3);
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(3);
});
it("refreshes ComposeProjectDashboard per-volume chips and summed banner disk usage every 30s", async () => {
backend.stats.mockResolvedValue(ok(makeStats("1.00%")));
backend.volumeSizes
.mockResolvedValueOnce(ok({ shop_pgdata: "1.2GB", shop_redis: "300MB" }))
.mockResolvedValueOnce(ok({ shop_pgdata: "1.5GB", shop_redis: "500MB" }));
render(
<ToolWindowShownProvider value={true}>
<ComposeProjectDashboard
conn="default"
project="shop"
containers={[runningContainer, stoppedContainer]}
snapshot={snapshotWithVolumes}
/>
</ToolWindowShownProvider>,
);
await act(async () => {
await Promise.resolve();
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(1);
expect(screen.getByText("pgdata · local · 1.2GB")).toBeInTheDocument();
expect(screen.getByText("redis · local · 300MB")).toBeInTheDocument();
expect(screen.getByText("1.5GB")).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS);
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(2);
expect(screen.getByText("pgdata · local · 1.5GB")).toBeInTheDocument();
expect(screen.getByText("redis · local · 500MB")).toBeInTheDocument();
expect(screen.getByText("2GB")).toBeInTheDocument();
});
it("refreshes ContainerDashboard mounted volume sizes every 30s without overlapping slow calls", async () => {
backend.stats.mockResolvedValue(ok(makeStats("1.00%")));
let resolveSlow: ((v: ReturnType<typeof ok<Record<string, string>>>) => void) | undefined;
backend.volumeSizes
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveSlow = resolve;
}),
)
.mockResolvedValueOnce(ok({ shop_pgdata: "256.8kB" }));
const inspectJson = JSON.stringify([
{
Created: "2026-04-20T05:00:00Z",
State: { Status: "running", Pid: 100, StartedAt: "2026-04-20T05:00:01Z" },
HostConfig: { RestartPolicy: { Name: "no", MaximumRetryCount: 0 } },
Config: { Entrypoint: [], Cmd: ["postgres"], Env: [], Labels: {} },
Mounts: [
{
Type: "volume",
Name: "shop_pgdata",
Source: "/var/lib/docker/volumes/shop_pgdata/_data",
Destination: "/var/lib/postgresql/data",
Mode: "z",
RW: true,
},
{
Type: "bind",
Source: "/work/shop/init.sql",
Destination: "/docker-entrypoint-initdb.d/init.sql",
Mode: "ro",
RW: false,
},
],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
render(
<ToolWindowShownProvider value={true}>
<ContainerDashboard
conn="default"
container={{ ...runningContainer, mounts: ["shop_pgdata"] }}
snapshot={snapshotWithVolumes}
inspectText={inspectJson}
/>
</ToolWindowShownProvider>,
);
expect(backend.volumeSizes).toHaveBeenCalledTimes(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS * 1.5);
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(1);
await act(async () => {
resolveSlow!(ok({ shop_pgdata: "145.4kB" }));
await Promise.resolve();
});
expect(screen.getByText("145.4kB")).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS);
});
expect(backend.volumeSizes).toHaveBeenCalledTimes(2);
expect(screen.getByText("256.8kB")).toBeInTheDocument();
});
});
+1
Переглянути файл
@@ -1678,6 +1678,7 @@
"No image layers": "No image layers",
"Instruction": "Instruction",
"Volume Overview": "Volume Overview",
"Disk usage": "Disk usage",
"Mountpoint": "Mountpoint",
"Containers Using Volume": "Containers Using Volume",
"No containers are using this volume": "No containers are using this volume",
+1
Переглянути файл
@@ -7588,6 +7588,7 @@
"No image layers": "無映像層",
"Instruction": "指令",
"Volume Overview": "資料磁碟區概覽",
"Disk usage": "磁碟用量",
"Mountpoint": "掛載點",
"Containers Using Volume": "使用此資料磁碟區的容器",
"No containers are using this volume": "沒有容器正在使用此資料磁碟區",
+1
Переглянути файл
@@ -8123,6 +8123,7 @@
"No image layers": "无镜像层",
"Instruction": "指令",
"Volume Overview": "数据卷概览",
"Disk usage": "磁盘占用",
"Mountpoint": "挂载点",
"Containers Using Volume": "使用此数据卷的容器",
"No containers are using this volume": "没有容器正在使用此数据卷",