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

41 lines
1.5 KiB
Python

"""How much of the machine's memory is available, so loop-claude starts a worker only while a quarter is.
loop-claude reads MemAvailable and MemTotal from /proc/meminfo before each worker starts. While less
than a quarter is available, it says so once on stderr and reads again each minute, so loops running
at once do not push the machine into swap. Where the file cannot be read, as off Linux, the worker
starts at once.
"""
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 = MEMINFO) -> Memory | None:
"""The machine's memory; None where meminfo cannot be read, as off Linux."""
try:
return parsed(meminfo.read_text())
except OSError:
return None