35 lines
1.3 KiB
Python
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 at least ROOM_SHARE of it is available, which leaves room for a worker."""
|
|
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.
|
|
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
|