Файли
openidea/src/workbench/devcontainerResources.ts
T
Onur Ugur ef4458c04c feat(remote): show dev container resource limits, usage and OOM kills (#7518)
The remote status shows the dev container's CPU and memory limits and live usage, and says when the container hit its memory limit, using Docker's explicit OOM status rather than the exit code. Stale responses after a disconnect are discarded and host round-trip time is measured independently of Docker polling; MCP approval flow and tool registrations are kept.

Closes #7467

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 21:23:33 +08:00

193 рядки
7.9 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* Shared dev container resource limit formatting, read-only config links, and
* extensible limit-action helpers used by Services › Docker › Dev Containers,
* the remote window's status bar resources widget, and OOM disconnect reporting.
*/
import { tx } from "@/platform/i18n";
import { call, commands, type DevContainerResourceStatus, type ResourceLimitSource } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { editorService, notifications } from "@/workbench/contributions";
const KIB = 1024;
const MIB = KIB * 1024;
const GIB = MIB * 1024;
const TIB = GIB * 1024;
function trimNumber(value: number, maxDecimals = 2): string {
const factor = 10 ** maxDecimals;
const rounded = Math.round(value * factor) / factor;
if (Math.abs(rounded - Math.round(rounded)) < 1e-6) return String(Math.round(rounded));
return rounded.toFixed(maxDecimals).replace(/\.?0+$/, "");
}
/** Human-readable CPU limit (`1 CPU`, `2 CPUs`, `2.5 CPUs`). */
export function formatCpuLimit(cpus: number | null | undefined): string | null {
if (cpus == null || !Number.isFinite(cpus) || cpus <= 0) return null;
const text = trimNumber(cpus, 2);
return Math.abs(cpus - 1) < 1e-6 ? `${text} CPU` : `${text} CPUs`;
}
/** Compact CPU limit for the status bar pill (`2 CPU`, `2.5 CPU`). */
export function formatCompactCpuLimit(cpus: number | null | undefined): string | null {
if (cpus == null || !Number.isFinite(cpus) || cpus <= 0) return null;
return `${trimNumber(cpus, 1)} CPU`;
}
/** Plain-language memory limit matching Docker / devcontainer units (`4 GB`, `1.5 GB`, `512 MB`). */
export function formatMemoryLimit(bytes: number | null | undefined): string | null {
if (bytes == null || !Number.isFinite(bytes) || bytes <= 0) return null;
if (bytes >= TIB) return `${trimNumber(bytes / TIB, 1)} TB`;
if (bytes >= GIB) return `${trimNumber(bytes / GIB, 1)} GB`;
if (bytes >= MIB) return `${trimNumber(bytes / MIB, 1)} MB`;
if (bytes >= KIB) return `${trimNumber(bytes / KIB, 1)} KB`;
return `${Math.round(bytes)} B`;
}
/** Compact memory limit for the status bar pill (`4G`, `512M`). */
export function formatCompactMemoryLimit(bytes: number | null | undefined): string | null {
if (bytes == null || !Number.isFinite(bytes) || bytes <= 0) return null;
if (bytes >= TIB) return `${trimNumber(bytes / TIB, 1)}T`;
if (bytes >= GIB) return `${trimNumber(bytes / GIB, 1)}G`;
if (bytes >= MIB) return `${trimNumber(bytes / MIB, 0)}M`;
if (bytes >= KIB) return `${trimNumber(bytes / KIB, 0)}K`;
return `${Math.round(bytes)}B`;
}
function basename(path: string | null | undefined): string | null {
if (!path) return null;
const clean = path.replace(/\\/g, "/").replace(/\/+$/, "");
const name = clean.split("/").pop();
return name || null;
}
/** Short label naming where a container's resource limits come from. */
export function limitSourceLabel(
source: ResourceLimitSource | null | undefined,
configPath?: string | null,
): string | null {
switch (source) {
case "devcontainerRunArgs":
return basename(configPath) ?? "devcontainer.json";
case "composeDeployLimits":
return basename(configPath) ?? "Docker Compose";
case "dockerVm":
return tx("Docker VM");
default:
return null;
}
}
export interface EffectiveDevContainerLimits {
/** Container-level CPU limit (`HostConfig` or configured), `null` when uncapped. */
cpus: number | null;
/** Container-level memory limit in bytes (`HostConfig` or configured), `null` when uncapped. */
memoryBytes: number | null;
/** Docker VM CPU ceiling when known. */
dockerVmCpus: number | null;
/** Docker VM memory ceiling in bytes when known. */
dockerVmMemoryBytes: number | null;
/** Where the configured limit comes from (`devcontainer.json`, Compose, or Docker VM). */
source: ResourceLimitSource;
/** Local config file path (`devcontainer.json` or Compose file) to open when clicked. */
configPath: string | null;
}
/** Resolves effective container limits alongside configured source & Docker VM ceilings. */
export function resolveDevContainerLimits(
status: DevContainerResourceStatus | null | undefined,
): EffectiveDevContainerLimits | null {
if (!status) return null;
const configured = status.configuredLimits;
const running = status.container?.running === true;
const cpus = status.limits.cpus ?? (running ? null : configured?.cpus) ?? null;
const memoryBytes = status.limits.memoryBytes ?? (running ? null : configured?.memoryBytes) ?? null;
const dockerVmCpus = status.hostRequirements.environment.dockerCpus ?? null;
const dockerVmMemoryBytes = status.hostRequirements.environment.dockerMemoryBytes ?? null;
const source: ResourceLimitSource =
configured &&
(configured.cpus != null || configured.memoryBytes != null) &&
(!running || (configured.cpus === cpus && configured.memoryBytes === memoryBytes))
? configured.source
: dockerVmCpus != null || dockerVmMemoryBytes != null
? "dockerVm"
: "none";
const configPath = status.configuredLimits?.configPath ?? status.configPath ?? null;
return { cpus, memoryBytes, dockerVmCpus, dockerVmMemoryBytes, source, configPath };
}
/** Plain-language OOM summary for UI surfaces that inspect container state directly. */
export function formatOomSummary(memoryLimitBytes: number | null | undefined): string {
const limit = formatMemoryLimit(memoryLimitBytes);
if (limit) return tx`The dev container ran out of its ${limit} memory limit.`;
return tx("The dev container ran out of memory (killed by the OOM killer, exit 137).");
}
function normalizeSlash(p: string): string {
return p.replace(/\\/g, "/").replace(/\/+$/, "");
}
/**
* Opens a dev container's configuration file (`devcontainer.json` or Compose file) in the editor.
* Inside a connected dev container window, maps paths under the bind-mounted local folder into the
* container workspace; when disconnected or outside the open project, opens it in a local window.
*/
export async function openDevContainerConfig(configPath: string, localFolder?: string | null): Promise<void> {
const trimmed = configPath.trim();
if (!trimmed) return;
const remote = useRemote.getState();
const normConfig = normalizeSlash(trimmed);
if (remote.session?.target.kind === "devContainer") {
const folder = normalizeSlash(localFolder || remote.session.target.folder);
if (!remote.lost && folder && normConfig.startsWith(`${folder}/`)) {
const rel = normConfig.slice(folder.length + 1);
const containerPath = `${normalizeSlash(remote.session.root)}/${rel}`;
try {
await editorService().openFile(containerPath, { focus: true });
return;
} catch {
// Fall through to opening locally on the desktop.
}
}
try {
await call(commands.windowOpenFileInNewWindow(folder || null, trimmed));
return;
} catch (e) {
notifications().notify({
group: "remote",
level: "error",
title: tx("Could not open dev container configuration"),
body: e instanceof Error ? e.message : String(e),
});
return;
}
}
const projectRoot = useProject.getState().project?.root;
try {
if (projectRoot && normConfig.startsWith(`${normalizeSlash(projectRoot)}/`)) {
await editorService().openFile(trimmed, { focus: true });
} else {
await call(commands.windowOpenFileInNewWindow(localFolder ?? null, trimmed));
}
} catch (e) {
notifications().notify({
group: "remote",
level: "error",
title: tx("Could not open dev container configuration"),
body: e instanceof Error ? e.message : String(e),
});
}
}
/**
* Extension point for follow-up limit-editing actions (e.g. `#7468` Change Limits…)
* shared between Services › Docker › Dev Containers and the status bar resources widget.
*/
export interface DevContainerLimitAction {
id: string;
label: string;
run: () => void | Promise<void>;
}