"""The docker that run-heavy puts first on its command's PATH. It adds the memory limits a container lacks, from the slot's share, then runs the real docker.""" import os import pathlib import shutil import sys import typing from docker_command import capped # The folder run-heavy puts first on its command's PATH, holding the docker that runs main. PATH_ENTRY = pathlib.Path(__file__).resolve().parent / "path_entry" # The environment variable that hands this docker the slot's memory share, in MiB. SHARE_VARIABLE = "RUN_HEAVY_MEMORY" CANNOT_RUN = 126 NOT_FOUND = 127 def main(argv: list[str], env: typing.Mapping[str, str]) -> int: """Replaces this process with the real docker; returns only where none is found or it cannot run.""" path = without_path_entry(env.get("PATH", "")) docker = shutil.which("docker", path=path) if docker is None: print("run-heavy: docker: command not found", file=sys.stderr) return NOT_FOUND share = env.get(SHARE_VARIABLE) try: os.execve(docker, [docker, *(capped(argv, f"{share}m") if share else argv)], {**env, "PATH": path}) except OSError as failure: print(f"run-heavy: cannot run {docker}: {failure.strerror}", file=sys.stderr) return CANNOT_RUN def without_path_entry(path: str) -> str: """path less PATH_ENTRY, so the real docker is the one found.""" return os.pathsep.join(entry for entry in path.split(os.pathsep) if pathlib.Path(entry).resolve() != PATH_ENTRY)