Files
claude-config/bin/machine_load/memory.py
T

35 lines
1.3 KiB
Python

"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it, and whether that leaves room for a worker: a quarter of it."""
import dataclasses
import pathlib
import re
MEMINFO = pathlib.Path("/proc/meminfo")
# A worker starts only while this share of the machine's memory is available; the human chose it, as no standard sets one.
ROOM_SHARE = 0.25
@dataclasses.dataclass(frozen=True)
class Memory:
"""The machine's memory, in kB as /proc/meminfo counts it: what a new process can have without swapping, and all of it."""
available: int
total: int
def has_room(self) -> bool:
return self.available >= ROOM_SHARE * self.total
def parsed(meminfo: str) -> Memory | None:
"""The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal."""
fields = dict(re.findall(r"^(MemAvailable|MemTotal):\s+(\d+) kB$", meminfo, re.MULTILINE))
if len(fields) != 2:
return None
return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"]))
def read_memory(meminfo: pathlib.Path | None = None) -> Memory | None:
"""The machine's memory, read from meminfo or else MEMINFO; None where it cannot be read, as off Linux."""
try:
return parsed((meminfo or MEMINFO).read_text())
except OSError:
return None