47 lines
2.3 KiB
Python
47 lines
2.3 KiB
Python
"""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 command_lines.docker_command import capped
|
|
from command_lines.shell_command import tool_name
|
|
|
|
# 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)
|
|
|
|
|
|
def finds_this_docker(word: str, before: list[str]) -> bool:
|
|
"""Whether a command's docker is this one, given the word that names docker and the words before it, assuming run-heavy put this docker first on PATH, as it does on Linux. It is where docker is named bare, since a path names a different docker, and no word before it may reset PATH."""
|
|
return word == "docker" and not any(resets_path(earlier) for earlier in before)
|
|
|
|
|
|
def resets_path(word: str) -> bool:
|
|
"""Whether a word before docker may drop the PATH run-heavy set. It errs towards yes, so that a command it matches must set its own memory limits: it matches a PATH= assignment, -i, --ignore-environment, -u or --unset whichever variable and launcher they belong to, and sudo or doas, which reset PATH."""
|
|
return word.startswith(("PATH=", "--unset")) or word in ("-i", "--ignore-environment", "-u") or tool_name(word) in ("doas", "sudo")
|