diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 3e45386b5..2dca31b14 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -217,7 +217,8 @@ milliseconds up to one day. `cpu`, `memory` and `disk` are each left out when they could not be read; `cpu` is also left out for the first 15 seconds, since it is busy time between two reads. `pressure` (`normal`, `warn` or `critical`) is present only where the operating system reports one. `disk` is the folder -Simlock keeps its data in. `limited` is `false` for the whole machine's figures. +Simlock keeps its data in. `limited` is `false` for the whole machine's figures, and `true` when a Linux +cgroup CPU or memory limit applies and the figures are measured against it. Under the `resource` capacity strategy, **`capacity.ramBudget`** reports the RAM budget; under `fixed` the field is absent: diff --git a/docs/internal/COMPONENTS.md b/docs/internal/COMPONENTS.md index 48dbedf94..67202be77 100644 --- a/docs/internal/COMPONENTS.md +++ b/docs/internal/COMPONENTS.md @@ -140,7 +140,7 @@ modules with. | Component | Where | Owns | Does not | |---|---|---|---| | `HostLoadSampler` | `src/host-load/sampler.ts` | The machine's CPU, memory and disk load: one read at start and every 15 s, one read at a time and each bounded at 10 s, busy % from two successive CPU counters, the age of the reading, and one warn when a part that was read fails. Served from memory through `current()`. | Read the machine: the `HostLoadProbe` port does. Shape the wire block: the contract's `fitHostLoad` does. | -| `HostLoadProbe` adapters | `src/ports/host-load.ts` | `DarwinHostLoadProbe` (`sysctl`, `os.cpus()`), `LinuxHostLoadProbe` (`/proc/stat`, `/proc/meminfo`), `FakeHostLoadProbe`, and `productionHostLoadProbe`. Each part is read on its own and left out when it fails. | Compute a percentage. | +| `HostLoadProbe` adapters | `src/ports/host-load.ts` | `DarwinHostLoadProbe` (`sysctl`, `os.cpus()`), `LinuxHostLoadProbe` (`/proc/stat`, `/proc/meminfo`, `/proc/self/cgroup` and the cgroup v2 files under `/sys/fs/cgroup`), `FakeHostLoadProbe`, and `productionHostLoadProbe`. Each part is read on its own and left out when it fails. | Compute a percentage. | ## Event bus diff --git a/src/host-load/sampler.test.ts b/src/host-load/sampler.test.ts index baeb7a49e..f6361caf1 100644 --- a/src/host-load/sampler.test.ts +++ b/src/host-load/sampler.test.ts @@ -5,6 +5,8 @@ import { FakeHostLoadProbe, type HostLoadCounters, JsonLinesLogger, + LinuxHostLoadProbe, + MemoryFilesystem, MemoryLogSink, } from "../ports/index.js"; import { HostLoadSampler } from "./index.js"; @@ -316,3 +318,42 @@ describe("HostLoadSampler", () => { expect(clock.pendingTimerCount).toBe(0); }); }); + +describe("HostLoadSampler under a cgroup CPU limit", () => { + it("reports busy % as the cgroup's usage over elapsed time times the limit's cores, from two reads", async () => { + const filesystem = new MemoryFilesystem(); + const write = async (path: string, contents: string): Promise => { + await filesystem.mkdirp(path.slice(0, path.lastIndexOf("/"))); + await filesystem.writeFileAtomic(path, contents); + }; + await write("/proc/stat", "cpu 100 10 50 300 20 5 7 3 99 98\n"); + await write( + "/proc/meminfo", + "MemTotal: 16000000 kB\nMemAvailable: 4000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", + ); + await write("/proc/self/cgroup", "0::/x\n"); + await write("/sys/fs/cgroup/x/cpu.max", "200000 100000\n"); + await write("/sys/fs/cgroup/x/cpu.stat", "usage_usec 1000000\n"); + let now = 10_000_000; + const clock = new FakeClock(1_000); + const sampler = new HostLoadSampler({ + clock, + probe: new LinuxHostLoadProbe({ + cores: () => 64, + dataDirectory: "/data", + filesystem, + nowMicros: () => now, + }), + }); + sampler.start(); + await flush(); + + now = 20_000_000; + await write("/sys/fs/cgroup/x/cpu.stat", "usage_usec 7100000\n"); + clock.advance(15_000); + await flush(); + + expect(sampler.current()?.cpu).toStrictEqual({ busyPercent: 30.5, cores: 2, limited: true }); + sampler.dispose(); + }); +}); diff --git a/src/ports/host-load.test.ts b/src/ports/host-load.test.ts index 623f9a112..c73a1f94e 100644 --- a/src/ports/host-load.test.ts +++ b/src/ports/host-load.test.ts @@ -13,6 +13,7 @@ import { productionHostLoadProbe, ScriptedProcessRunner, type CpuTimes, + type HostLoadCounters, } from "./index.js"; vi.mock("node:os", async (importOriginal) => { @@ -99,7 +100,12 @@ const PROC_MEMINFO = "MemTotal: 16000000 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\nSwapTotal: 2000000 kB\nSwapFree: 1500000 kB\n"; function linuxProbe(filesystem: MemoryFilesystem): LinuxHostLoadProbe { - return new LinuxHostLoadProbe({ cores: () => 4, dataDirectory: "/data", filesystem }); + return new LinuxHostLoadProbe({ + cores: () => 4, + dataDirectory: "/data", + filesystem, + nowMicros: () => 10_000_000, + }); } describe("DarwinHostLoadProbe", () => { @@ -267,6 +273,436 @@ describe("LinuxHostLoadProbe", () => { }); }); +const GIB = 1024 ** 3; +const CGROUP_ROOT = "/sys/fs/cgroup"; +const BIG_MEMINFO = + "MemTotal: 67108864 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\nSwapTotal: 2000000 kB\nSwapFree: 1500000 kB\n"; +const MACHINE_MEMORY = { + availableBytes: 4_000_000 * 1024, + limited: false, + swapUsedBytes: 500_000 * 1024, + totalBytes: 67_108_864 * 1024, +}; + +interface CgroupFolder { + readonly cpuMax?: string; + readonly memoryMax?: string; + readonly cpuStat?: string; + readonly current?: string; + readonly stat?: string; + readonly swap?: string; +} + +function folderFiles(folder: string, values: CgroupFolder): Record { + const base = folder === "" ? CGROUP_ROOT : `${CGROUP_ROOT}/${folder}`; + const entries: [string, string | undefined][] = [ + ["cpu.max", values.cpuMax], + ["memory.max", values.memoryMax], + ["cpu.stat", values.cpuStat], + ["memory.current", values.current], + ["memory.stat", values.stat], + ["memory.swap.current", values.swap], + ]; + const files: Record = {}; + for (const [name, value] of entries) { + if (value !== undefined) files[`${base}/${name}`] = value; + } + return files; +} + +const USAGE = { + cpuStat: "usage_usec 5000000\nuser_usec 3000000\nsystem_usec 2000000\n", + current: "5368709120\n", + stat: "anon 1\ninactive_file 2147483648\nactive_file 5\n", +}; + +async function cgroupFilesystem( + cgroupLine: string | undefined, + files: Record, +): Promise { + const filesystem = new SpaceFilesystem({ freeBytes: 120, totalBytes: 500 }); + const all: Record = { + "/proc/meminfo": BIG_MEMINFO, + "/proc/stat": PROC_STAT, + ...(cgroupLine === undefined ? {} : { "/proc/self/cgroup": cgroupLine }), + ...files, + }; + for (const [path, contents] of Object.entries(all)) { + await filesystem.mkdirp(path.slice(0, path.lastIndexOf("/")) || "/"); + await filesystem.writeFileAtomic(path, contents); + } + return filesystem; +} + +function cgroupProbe( + filesystem: MemoryFilesystem, + options: { cores?: number; now?: () => number } = {}, +): LinuxHostLoadProbe { + return new LinuxHostLoadProbe({ + cores: () => options.cores ?? 64, + dataDirectory: "/data", + filesystem, + nowMicros: options.now ?? (() => 10_000_000), + }); +} + +async function readCgroup( + path: string, + folders: Record, + options: { cores?: number; now?: () => number } = {}, +): Promise { + const files: Record = {}; + for (const [folder, values] of Object.entries(folders)) { + Object.assign(files, folderFiles(folder, values)); + } + const filesystem = await cgroupFilesystem(`0::${path}\n`, files); + return cgroupProbe(filesystem, options).read(); +} + +const LIMITED_TWO_CORES = { cores: 2, limited: true, busyTime: 5_000_000, totalTime: 20_000_000 }; +const LIMITED_EIGHT_GIB = { + availableBytes: 5 * GIB, + limited: true, + swapUsedBytes: 0, + totalBytes: 8 * GIB, +}; + +describe("LinuxHostLoadProbe under cgroup v2 limits", () => { + it("reports cores as the cpu.max quota over its period, and CPU time from cpu.stat against elapsed time, as limited", async () => { + const counters = await readCgroup("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/docker/abc", { + "docker/abc": { cpuMax: "200000 100000\n", ...USAGE }, + }); + + expect(counters.cpu).toStrictEqual(LIMITED_TWO_CORES); + }); + + it("reports a fractional quota as fractional cores", async () => { + const counters = await readCgroup("/x", { x: { cpuMax: "1000 100000\n", ...USAGE } }); + + expect(counters.cpu).toMatchObject({ cores: 0.01, limited: true, totalTime: 100_000 }); + }); + + it("reports a quota of 1000 over a period of 1000000 as 0.001 cores, limited", async () => { + const counters = await readCgroup("/x", { x: { cpuMax: "1000 1000000\n", ...USAGE } }); + + expect(counters.cpu).toMatchObject({ cores: 0.001, limited: true }); + }); + + it("uses /sys/fs/cgroup itself for a 0::/ line", async () => { + const counters = await readCgroup("/", { + "": { cpuMax: "150000 100000\n", memoryMax: "max\n", ...USAGE }, + x: { cpuMax: "100000 100000\n", ...USAGE }, + }); + + expect(counters.cpu).toMatchObject({ cores: 1.5, limited: true }); + expect(counters.memory).toStrictEqual(MACHINE_MEMORY); + }); + + it("takes the lowest CPU and the lowest memory limit across Simlock's folder and its parents, comparing CPU limits as cores", async () => { + const memory = await readCgroup("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/system.slice/simlock.service", { + "": { cpuMax: "max 100000\n" }, + "system.slice": { memoryMax: "8589934592\n", ...USAGE }, + "system.slice/simlock.service": { + memoryMax: "17179869184\n", + current: "1\n", + stat: "inactive_file 0\n", + }, + }); + expect(memory.memory).toStrictEqual(LIMITED_EIGHT_GIB); + expect(memory.cpu).toStrictEqual({ + busyTime: 175, + cores: 64, + limited: false, + totalTime: 495, + }); + + const cpu = await readCgroup("/x", { + x: { cpuMax: "200000 100000\n", ...USAGE }, + "": { cpuMax: "150000 50000\n" }, + }); + expect(cpu.cpu).toMatchObject({ cores: 2, limited: true }); + + const folderLower = await readCgroup("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/system.slice/simlock.service", { + "system.slice": { memoryMax: "8589934592\n", current: "1\n", stat: "inactive_file 0\n" }, + "system.slice/simlock.service": { + memoryMax: "4294967296\n", + current: "1073741824\n", + stat: "inactive_file 0\n", + }, + }); + expect(folderLower.memory).toMatchObject({ + availableBytes: 3 * GIB, + limited: true, + totalBytes: 4 * GIB, + }); + }); + + it("reports the folder's memory.max of 16 GiB as limited when cpu.max is max everywhere, and keeps the machine's CPU", async () => { + const counters = await readCgroup("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/system.slice/simlock.service", { + "": { cpuMax: "max 100000\n" }, + "system.slice/simlock.service": { + cpuMax: "max 100000\n", + memoryMax: "17179869184\n", + ...USAGE, + }, + }); + + expect(counters.memory).toStrictEqual({ + availableBytes: 13 * GIB, + limited: true, + swapUsedBytes: 0, + totalBytes: 16 * GIB, + }); + expect(counters.cpu).toMatchObject({ cores: 64, limited: false }); + }); + + it("reads usage from the folder that holds the winning limit, not from Simlock's own folder, and from the topmost of two folders tied on the lowest limit", async () => { + const winner = await readCgroup("/a/b/c", { + a: { cpuMax: "200000 100000\n", memoryMax: "8589934592\n", ...USAGE }, + "a/b": { cpuMax: "400000 100000\n" }, + "a/b/c": { + cpuMax: "400000 100000\n", + cpuStat: "usage_usec 1\n", + current: "1\n", + stat: "inactive_file 0\n", + }, + }); + expect(winner.cpu).toStrictEqual(LIMITED_TWO_CORES); + expect(winner.memory).toStrictEqual(LIMITED_EIGHT_GIB); + + const tied = await readCgroup("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/a/b", { + a: { cpuMax: "200000 100000\n", memoryMax: "8589934592\n", ...USAGE }, + "a/b": { + cpuMax: "200000 100000\n", + memoryMax: "8589934592\n", + cpuStat: "usage_usec 1\n", + current: "1\n", + stat: "inactive_file 0\n", + }, + }); + expect(tied.cpu).toStrictEqual(LIMITED_TWO_CORES); + expect(tied.memory).toStrictEqual(LIMITED_EIGHT_GIB); + }); + + it("reads only /sys/fs/cgroup for a cgroup path with a .. segment", async () => { + const counters = await readCgroup("/../../system.slice/x", { + "": { cpuMax: "200000 100000\n", ...USAGE }, + "system.slice/x": { cpuMax: "100000 100000\n", ...USAGE }, + "../../system.slice/x": { cpuMax: "100000 100000\n", ...USAGE }, + }); + + expect(counters.cpu).toStrictEqual(LIMITED_TWO_CORES); + }); + + it("accepts cpu.max and memory.max with the kernel's trailing newline, and nothing else after the value", async () => { + const folders = { + x: { cpuMax: "200000 100000\n", memoryMax: "8589934592\n", ...USAGE, swap: "1048576\n" }, + }; + const accepted = await readCgroup("/x", folders); + expect(accepted.cpu).toStrictEqual(LIMITED_TWO_CORES); + expect(accepted.memory).toMatchObject({ limited: true, swapUsedBytes: 1_048_576 }); + + const extra = await readCgroup("/x", { + x: { ...folders.x, cpuMax: "200000 100000\n\n", memoryMax: "8589934592\n\n" }, + }); + expect(extra.cpu).toMatchObject({ limited: false }); + expect(extra.memory).toStrictEqual(MACHINE_MEMORY); + }); + + it.each([ + "garbage\n", + "200000\n", + "200000 0\n", + "-1 100000\n", + "max 100000\n", + "200000 100000\n", + ])("treats cpu.max %j as no limit at that level", async (value) => { + const accepted = await readCgroup("/x", { + "": { cpuMax: "300000 100000\n", ...USAGE }, + x: { cpuMax: "200000 100000\n", ...USAGE }, + }); + expect(accepted.cpu).toMatchObject({ cores: 2, limited: true }); + + const counters = await readCgroup("/x", { + "": { cpuMax: "300000 100000\n", ...USAGE }, + x: { cpuMax: value }, + }); + + expect(counters.cpu).toMatchObject({ cores: 3, limited: true }); + }); + + it("reports the machine's CPU, not limited, for a quota at or above the machine's cores", async () => { + const folders = { x: { cpuMax: "300000 100000\n", ...USAGE } }; + const below = await readCgroup("/x", folders, { cores: 4 }); + expect(below.cpu).toMatchObject({ cores: 3, limited: true }); + + const counters = await readCgroup( + "/x", + { x: { cpuMax: "800000 100000\n", ...USAGE } }, + { cores: 4 }, + ); + + expect(counters.cpu).toMatchObject({ cores: 4, limited: false }); + + const equal = await readCgroup( + "/x", + { x: { cpuMax: "400000 100000\n", ...USAGE } }, + { cores: 4 }, + ); + expect(equal.cpu).toMatchObject({ cores: 4, limited: false }); + expect(counters.cpu?.totalTime).toBe(100 + 10 + 50 + 5 + 7 + 3 + 300 + 20); + }); + + it.each([ + ["cpu.stat is missing", { cpuMax: "200000 100000\n" }], + ["cpu.stat has no usage_usec", { cpuMax: "200000 100000\n", cpuStat: "user_usec 1\n" }], + ])("leaves CPU out under a CPU limit when %s", async (_why, folder) => { + const accepted = await readCgroup("/x", { x: { cpuMax: "200000 100000\n", ...USAGE } }); + expect(accepted.cpu).toBeDefined(); + + const counters = await readCgroup("/x", { x: folder }); + + expect(counters.cpu).toBeUndefined(); + expect(counters.memory).toBeDefined(); + }); + + it("reports memory total as the limit, and available as the limit minus memory.current plus inactive_file, floored at 0, as limited", async () => { + const counters = await readCgroup("/x", { x: { memoryMax: "8589934592\n", ...USAGE } }); + expect(counters.memory).toStrictEqual(LIMITED_EIGHT_GIB); + + const over = await readCgroup("/x", { + x: { memoryMax: "8589934592\n", current: "10737418240\n", stat: "inactive_file 0\n" }, + }); + expect(over.memory).toStrictEqual({ ...LIMITED_EIGHT_GIB, availableBytes: 0 }); + }); + + it("reports swap used as memory.swap.current under a memory limit, and 0 when that file is missing", async () => { + const withSwap = await readCgroup("/x", { + x: { memoryMax: "8589934592\n", ...USAGE, swap: "123456\n" }, + }); + expect(withSwap.memory).toMatchObject({ limited: true, swapUsedBytes: 123_456 }); + + const without = await readCgroup("/x", { x: { memoryMax: "8589934592\n", ...USAGE } }); + expect(without.memory).toMatchObject({ limited: true, swapUsedBytes: 0 }); + }); + + it.each([ + ["max", "max\n"], + ["a value above MemTotal", "1099511627776\n"], + ["a value equal to MemTotal", "68719476736\n"], + ["an unparsable file", "garbage\n"], + ])("reports the machine's memory, not limited, for memory.max %s", async (_why, value) => { + const accepted = await readCgroup("/x", { x: { memoryMax: "8589934592\n", ...USAGE } }); + expect(accepted.memory?.limited).toBe(true); + + const counters = await readCgroup("/x", { x: { memoryMax: value, ...USAGE } }); + + expect(counters.memory).toStrictEqual(MACHINE_MEMORY); + }); + + it("leaves memory out under a memory limit when memory.current or inactive_file cannot be read, and keeps the limit when /proc/meminfo cannot be read", async () => { + const limit = { memoryMax: "8589934592\n" }; + const noCurrent = await readCgroup("/x", { x: { ...limit, stat: USAGE.stat } }); + expect(noCurrent.memory).toBeUndefined(); + const noInactive = await readCgroup("/x", { + x: { ...limit, current: USAGE.current, stat: "anon 1\n" }, + }); + expect(noInactive.memory).toBeUndefined(); + const noStat = await readCgroup("/x", { x: { ...limit, current: USAGE.current } }); + expect(noStat.memory).toBeUndefined(); + + const filesystem = await cgroupFilesystem("0::/x\n", folderFiles("x", { ...limit, ...USAGE })); + await filesystem.rm("/proc/meminfo"); + const counters = await cgroupProbe(filesystem).read(); + expect(counters.memory).toStrictEqual(LIMITED_EIGHT_GIB); + }); + + it("decides the CPU and memory limits independently", async () => { + const counters = await readCgroup("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/a/b", { + a: { cpuMax: "200000 100000\n", ...USAGE }, + "a/b": { memoryMax: "8589934592\n", ...USAGE }, + }); + + expect(counters.cpu).toStrictEqual(LIMITED_TWO_CORES); + expect(counters.memory).toStrictEqual(LIMITED_EIGHT_GIB); + }); + + it.each([ + ["a cgroup path with files missing", "0::/user.slice/x\n"], + ["v1 lines only", "12:cpu,cpuacct:/docker/abc\n1:name=systemd:/docker/abc\n"], + ])("reports the machine's figures when /proc/self/cgroup is %s", async (_why, line) => { + const files = folderFiles("docker/abc", { + cpuMax: "200000 100000\n", + memoryMax: "8589934592\n", + ...USAGE, + }); + const accepted = await cgroupFilesystem("0::/docker/abc\n", files); + expect((await cgroupProbe(accepted).read()).cpu?.limited).toBe(true); + + const counters = await cgroupProbe(await cgroupFilesystem(line, files)).read(); + + expect(counters.cpu).toMatchObject({ cores: 64, limited: false }); + expect(counters.memory).toStrictEqual(MACHINE_MEMORY); + }); + + it("reports the machine's figures when /proc/self/cgroup cannot be read", async () => { + const files = folderFiles("docker/abc", { cpuMax: "200000 100000\n", ...USAGE }); + const accepted = await cgroupFilesystem("0::/docker/abc\n", files); + expect((await cgroupProbe(accepted).read()).cpu?.limited).toBe(true); + + const counters = await cgroupProbe(await cgroupFilesystem(undefined, files)).read(); + + expect(counters.cpu).toMatchObject({ cores: 64, limited: false }); + expect(counters.memory).toStrictEqual(MACHINE_MEMORY); + }); + + it("reports the machine's figures when /proc/self/cgroup has only cgroup v1 lines and no 0:: line", async () => { + const files = folderFiles("docker/abc", { + cpuMax: "200000 100000\n", + memoryMax: "8589934592\n", + ...USAGE, + }); + const accepted = await cgroupFilesystem("12:memory:/docker/abc\n0::/docker/abc\n", files); + expect((await cgroupProbe(accepted).read()).cpu?.limited).toBe(true); + + const counters = await cgroupProbe( + await cgroupFilesystem( + "12:memory:/docker/abc\n10::/docker/abc\n1:name=systemd:/docker/abc\n", + files, + ), + ).read(); + + expect(counters.cpu).toMatchObject({ cores: 64, limited: false }); + expect(counters.memory).toStrictEqual(MACHINE_MEMORY); + }); + + it("shows a limit seeded between two reads on the second read, drops one removed between reads, and follows /proc/self/cgroup to a new folder between reads", async () => { + const filesystem = await cgroupFilesystem("0::/a\n", {}); + const probe = cgroupProbe(filesystem); + expect((await probe.read()).cpu?.limited).toBe(false); + + for (const [path, contents] of Object.entries( + folderFiles("a", { cpuMax: "200000 100000\n", ...USAGE }), + )) { + await filesystem.mkdirp(path.slice(0, path.lastIndexOf("/"))); + await filesystem.writeFileAtomic(path, contents); + } + expect((await probe.read()).cpu).toStrictEqual(LIMITED_TWO_CORES); + + for (const [path, contents] of Object.entries( + folderFiles("b", { cpuMax: "100000 100000\n", ...USAGE }), + )) { + await filesystem.mkdirp(path.slice(0, path.lastIndexOf("/"))); + await filesystem.writeFileAtomic(path, contents); + } + await filesystem.writeFileAtomic("/proc/self/cgroup", "0::/b\n"); + expect((await probe.read()).cpu).toMatchObject({ cores: 1, limited: true }); + + await filesystem.rm(`${CGROUP_ROOT}/b/cpu.max`); + expect((await probe.read()).cpu).toMatchObject({ cores: 64, limited: false }); + }); +}); + describe("NodeFilesystem.diskSpace", () => { const directories: string[] = []; afterEach(async () => { @@ -288,6 +724,19 @@ describe("NodeFilesystem.diskSpace", () => { }); }); +describe.skipIf(process.platform !== "linux")("production Linux probe on this machine", () => { + it("returns CPU counters, memory and disk from the real /proc and /sys", async () => { + const probe = productionHostLoadProbe({ platform: "linux", dataDirectory: tmpdir() }); + + const counters = await probe.read(); + + expect(counters.cpu?.totalTime).toBeGreaterThan(0); + expect(counters.cpu?.cores).toBeGreaterThan(0); + expect(counters.memory?.totalBytes).toBeGreaterThan(0); + expect(counters.disk?.totalBytes).toBeGreaterThan(0); + }); +}); + describe("productionHostLoadProbe", () => { afterEach(() => { vi.restoreAllMocks(); @@ -333,4 +782,47 @@ describe("productionHostLoadProbe", () => { expect(counters.cpu).toStrictEqual({ busyTime: 20, cores: 3, limited: false, totalTime: 100 }); }); + + it("advances the Linux probe's nowMicros by about one million per second of process.hrtime", async () => { + const hrtime = vi.spyOn(process.hrtime, "bigint"); + vi.mocked(cpus).mockReturnValue( + Array.from({ length: 4 }, () => ({}) as ReturnType[number]), + ); + vi.spyOn(NodeFilesystem.prototype, "readFile").mockImplementation(async (path: string) => { + if (path === "/proc/self/cgroup") return "0::/x\n"; + if (path === `${CGROUP_ROOT}/x/cpu.max`) return "200000 100000\n"; + if (path === `${CGROUP_ROOT}/x/cpu.stat`) return "usage_usec 1\n"; + if (path === "/proc/stat") return "cpu 10 0 10 80 0 0 0 0 0 0\n"; + throw new Error("ENOENT"); + }); + const probe = productionHostLoadProbe({ dataDirectory: tmpdir(), platform: "linux" }); + + hrtime.mockReturnValue(5_000_000_000n); + const first = await probe.read(); + hrtime.mockReturnValue(7_000_000_000n); + const second = await probe.read(); + + expect(first.cpu).toMatchObject({ cores: 2, limited: true, totalTime: 10_000_000 }); + expect(second.cpu).toMatchObject({ totalTime: 14_000_000 }); + }); + + it.runIf(process.platform === "linux")( + "on Linux, the production Linux probe returns CPU counters, memory and disk from the real /proc and /sys", + async () => { + vi.restoreAllMocks(); + vi.mocked(cpus).mockImplementation( + (await vi.importActual("node:os")).cpus, + ); + + const counters = await productionHostLoadProbe({ + dataDirectory: tmpdir(), + platform: "linux", + }).read(); + + expect(counters.cpu?.cores).toBeGreaterThan(0); + expect(counters.cpu?.totalTime).toBeGreaterThan(0); + expect(counters.memory?.totalBytes).toBeGreaterThan(0); + expect(counters.disk?.totalBytes).toBeGreaterThan(0); + }, + ); }); diff --git a/src/ports/host-load.ts b/src/ports/host-load.ts index 666d5743e..3c1fabdb4 100644 --- a/src/ports/host-load.ts +++ b/src/ports/host-load.ts @@ -148,21 +148,136 @@ export interface LinuxHostLoadProbeOptions { readonly filesystem: Pick; readonly dataDirectory: string; readonly cores: () => number; + readonly nowMicros: () => number; +} + +const CGROUP_ROOT = "/sys/fs/cgroup"; + +interface CgroupLimit { + readonly folder: string; + readonly value: number; +} + +interface CgroupLimits { + readonly cpu?: CgroupLimit; + readonly memory?: CgroupLimit; +} + +function parseQuota(text: string | undefined): number | undefined { + const match = /^(max|[1-9]\d*) ([1-9]\d*)\n?$/.exec(text ?? ""); + if (!match || match[1] === "max") return undefined; + return Number(match[1]) / Number(match[2]); +} + +function parseLimit(text: string | undefined): number | undefined { + const match = /^(max|\d+)\n?$/.exec(text ?? ""); + if (!match || match[1] === "max") return undefined; + return Number(match[1]); +} + +function lower( + current: CgroupLimit | undefined, + folder: string, + value: number | undefined, +): CgroupLimit | undefined { + if (value === undefined || (current !== undefined && value >= current.value)) return current; + return { folder, value }; +} + +function machineMemory( + totalBytes: number | undefined, + kib: (name: string) => number | undefined, +): MemoryCounters | undefined { + const availableBytes = kib("MemAvailable"); + const swapTotal = kib("SwapTotal"); + const swapFree = kib("SwapFree"); + if ( + totalBytes === undefined || + availableBytes === undefined || + swapTotal === undefined || + swapFree === undefined + ) { + return undefined; + } + return { + availableBytes, + limited: false, + swapUsedBytes: Math.max(0, swapTotal - swapFree), + totalBytes, + }; } export class LinuxHostLoadProbe implements HostLoadProbe { constructor(private readonly options: LinuxHostLoadProbeOptions) {} async read(): Promise { + const limits = await this.#limits(); const [cpu, memory, disk] = await Promise.all([ - this.#cpu(), - this.#memory(), + this.#cpu(limits.cpu), + this.#memory(limits.memory), readDisk(this.options.filesystem, this.options.dataDirectory), ]); return { ...(cpu && { cpu }), ...(memory && { memory }), ...(disk && { disk }) }; } - async #cpu(): Promise { + async #optional(path: string): Promise { + try { + return await this.options.filesystem.readFile(path); + } catch { + return undefined; + } + } + + async #folders(): Promise { + const line = (await this.#optional("/proc/self/cgroup")) + ?.split("\n") + .find((candidate) => candidate.startsWith("0::")); + if (line === undefined) return []; + const segments = line.slice(3).split("/").filter(Boolean); + if (segments.includes("..")) return [CGROUP_ROOT]; + const folders = [CGROUP_ROOT]; + for (const segment of segments) { + folders.push(`${folders[folders.length - 1]}/${segment}`); + } + return folders; + } + + async #limits(): Promise { + let cpu: CgroupLimit | undefined; + let memory: CgroupLimit | undefined; + for (const folder of await this.#folders()) { + const [cpuMax, memoryMax] = await Promise.all([ + this.#optional(`${folder}/cpu.max`), + this.#optional(`${folder}/memory.max`), + ]); + cpu = lower(cpu, folder, parseQuota(cpuMax)); + memory = lower(memory, folder, parseLimit(memoryMax)); + } + return { ...(cpu && { cpu }), ...(memory && { memory }) }; + } + + async #cpu(limit: CgroupLimit | undefined): Promise { + try { + const cores = this.options.cores(); + if (limit !== undefined && limit.value < cores) { + const stat = await this.#optional(`${limit.folder}/cpu.stat`); + const usage = /^usage_usec (\d+)$/m.exec(stat ?? ""); + if (!usage) return undefined; + const now = this.options.nowMicros(); + return { + busyTime: Number(usage[1]), + cores: limit.value, + limited: true, + totalTime: now * limit.value, + }; + } + return await this.#machineCpu(cores); + } catch { + return undefined; + } + } + + async #machineCpu(cores: number): Promise { try { const text = await this.options.filesystem.readFile("/proc/stat"); const line = text.split("\n").find((candidate) => /^cpu\s/.test(candidate)); @@ -184,7 +299,7 @@ export class LinuxHostLoadProbe implements HostLoadProbe { const busyTime = user + nice + system + irq + softirq + steal; return { busyTime, - cores: this.options.cores(), + cores, limited: false, totalTime: busyTime + idle + iowait, }; @@ -193,35 +308,40 @@ export class LinuxHostLoadProbe implements HostLoadProbe { } } - async #memory(): Promise { + async #memory(limit: CgroupLimit | undefined): Promise { try { - const text = await this.options.filesystem.readFile("/proc/meminfo"); + const text = await this.#optional("/proc/meminfo"); const kib = (name: string): number | undefined => { - const match = new RegExp(`^${name}:\\s+(\\d+)\\s*kB`, "m").exec(text); + const match = new RegExp(`^${name}:\\s+(\\d+)\\s*kB`, "m").exec(text ?? ""); return match ? Number(match[1]) * 1024 : undefined; }; - const totalBytes = kib("MemTotal"); - const availableBytes = kib("MemAvailable"); - const swapTotal = kib("SwapTotal"); - const swapFree = kib("SwapFree"); - if ( - totalBytes === undefined || - availableBytes === undefined || - swapTotal === undefined || - swapFree === undefined - ) { - return undefined; + const machineTotal = kib("MemTotal"); + if (limit !== undefined && (machineTotal === undefined || limit.value < machineTotal)) { + return await this.#limitedMemory(limit); } - return { - availableBytes, - limited: false, - swapUsedBytes: Math.max(0, swapTotal - swapFree), - totalBytes, - }; + return machineMemory(machineTotal, kib); } catch { return undefined; } } + + async #limitedMemory(limit: CgroupLimit): Promise { + const [current, stat, swap] = await Promise.all([ + this.#optional(`${limit.folder}/memory.current`), + this.#optional(`${limit.folder}/memory.stat`), + this.#optional(`${limit.folder}/memory.swap.current`), + ]); + const used = /^(\d+)\n?$/.exec(current ?? ""); + const inactive = /^inactive_file (\d+)$/m.exec(stat ?? ""); + if (!used || !inactive) return undefined; + const swapMatch = /^(\d+)\n?$/.exec(swap ?? ""); + return { + availableBytes: Math.max(0, limit.value - (Number(used[1]) - Number(inactive[1]))), + limited: true, + swapUsedBytes: swapMatch ? Number(swapMatch[1]) : 0, + totalBytes: limit.value, + }; + } } export class FakeHostLoadProbe implements HostLoadProbe { @@ -269,5 +389,6 @@ export function productionHostLoadProbe(options: ProductionHostLoadProbeOptions) cores: () => cpus().length, dataDirectory: options.dataDirectory, filesystem, + nowMicros: () => Number(process.hrtime.bigint() / 1000n), }); }