30 lines
899 B
Python
30 lines
899 B
Python
"""The machine's heavy slots: one per 4 CPUs, and at least one, each a file locked with flock that every session on the machine shares."""
|
|
import fcntl
|
|
import os
|
|
import pathlib
|
|
import typing
|
|
|
|
CPUS_PER_SLOT = 4
|
|
|
|
|
|
def slot_count(cpus: int | None) -> int:
|
|
return max(1, (cpus or 0) // CPUS_PER_SLOT)
|
|
|
|
|
|
def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path:
|
|
state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state")
|
|
return pathlib.Path(state) / "run-heavy"
|
|
|
|
|
|
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
|
|
"""The number and open file of a slot this call locked; None while every slot is held."""
|
|
for slot in range(slots):
|
|
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
|
|
try:
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
os.close(fd)
|
|
continue
|
|
return slot, fd
|
|
return None
|