"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it. A worker starts while at least ROOM_SHARE of it is available. The rest is split across the heavy slots, as the memory limit run-heavy gives each container.""" import dataclasses import pathlib import re MEMINFO = pathlib.Path("/proc/meminfo") # A worker starts only while at least this share of the machine's memory is available; the human chose it, as no standard sets one. The rest is the heavy slots' share, so changing it also changes the memory limit run-heavy gives a container. 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 slot_share(self, slots: int) -> int: """The memory limit, in MiB, that run-heavy gives each container a slot's command makes: what ROOM_SHARE leaves, split evenly across the slots.""" return int(self.total * (1 - ROOM_SHARE)) // slots // 1024 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