Answer principles round 1: 0 🔴, 4 🟡 (0 misread); exempt only a bare docker under run-heavy with no PATH of its own, drop the stale item citation, unit-test the slot share in MiB, place the limits by the subcommand's index; also a named Option, exit 126, clearer names and the launcher's import order
This commit is contained in:
+68
-36
@@ -1,32 +1,62 @@
|
||||
"""What a docker command asks of docker: its subcommand, whether a container it makes has a memory limit and a swap limit, and those arguments with the limits a container lacks."""
|
||||
"""What a docker command asks of docker: its subcommand, and whether a container it makes has a memory limit and a swap limit. capped adds the limits such a container lacks."""
|
||||
import re
|
||||
import typing
|
||||
|
||||
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
|
||||
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
|
||||
# The subcommands that make a container, whose memory limits docker reads from the same options.
|
||||
STARTS_CONTAINER = (["container", "create"], ["container", "run"], ["create"], ["run"])
|
||||
# A size as docker reads one, such as 4g, 512M or 1.5GiB: the pattern go-units' RAMInBytes parses.
|
||||
SIZE = r"\d+(?:\.\d+)*[kKmMgGtTpP]?[iI]?[bB]?"
|
||||
# A size as docker reads one, such as 4g, 512M or 1.5GiB: the pattern go-units' RAMInBytes parses, each unit a power of 1024.
|
||||
SIZE = r"(\d+(?:\.\d+)*)([kKmMgGtTpP]?)[iI]?[bB]?"
|
||||
# Docker's documented floor for --memory, 6m: a smaller value, such as grep -m 1's, belongs to the container's own command.
|
||||
MEMORY_FLOOR = 6 * 1024**2
|
||||
MEMORY_OPTIONS = ("-m", "--memory")
|
||||
SWAP_OPTIONS = ("--memory-swap",)
|
||||
# The values with which docker leaves swap without a limit: -1 for unlimited swap, and 0, in any unit, for unset.
|
||||
UNSET_SWAP = r"-1|0+(?:\.0+)*[kKmMgGtTpP]?[iI]?[bB]?"
|
||||
# A swap limit is any other size.
|
||||
SWAP = rf"(?!(?:{UNSET_SWAP})$){SIZE}"
|
||||
|
||||
|
||||
class Option(typing.NamedTuple):
|
||||
"""An option the arguments give: where it stands, how many words it takes, and its value."""
|
||||
at: int
|
||||
length: int
|
||||
value: str
|
||||
|
||||
|
||||
def size(value: str) -> float | None:
|
||||
"""The bytes a docker size spells; None for a value that is no size."""
|
||||
spelled = re.fullmatch(SIZE, value)
|
||||
return float(spelled.group(1)) * 1024 ** " kmgtp".index(spelled.group(2).lower() or " ") if spelled else None
|
||||
|
||||
|
||||
def memory_limit(value: str) -> bool:
|
||||
return (size(value) or 0) >= MEMORY_FLOOR
|
||||
|
||||
|
||||
def swap_limit(value: str) -> bool:
|
||||
"""Whether a --memory-swap value limits swap: -1 leaves it unlimited, and 0 leaves it unset, which docker reads as twice the memory limit."""
|
||||
return bool(size(value))
|
||||
|
||||
|
||||
def unset_swap(value: str) -> bool:
|
||||
return value == "-1" or size(value) == 0
|
||||
|
||||
|
||||
def docker_subcommand(arguments: list[str]) -> list[str]:
|
||||
"""The subcommand docker's arguments name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"]."""
|
||||
positional: list[str] = []
|
||||
return [arguments[at] for at in subcommand_at(arguments)]
|
||||
|
||||
|
||||
def subcommand_at(arguments: list[str]) -> list[int]:
|
||||
"""Where in docker's arguments each word of its subcommand stands, so a global option's value that spells it, as in --context run, is not taken for it."""
|
||||
positional: list[int] = []
|
||||
skip = False
|
||||
for word in arguments:
|
||||
for at, word in enumerate(arguments):
|
||||
if skip:
|
||||
skip = False
|
||||
elif word.startswith("-"):
|
||||
skip = word in DOCKER_VALUED
|
||||
else:
|
||||
positional.append(word)
|
||||
if positional[0] not in ("buildx", "compose", "container") or len(positional) == 2:
|
||||
positional.append(at)
|
||||
if arguments[positional[0]] not in ("buildx", "compose", "container") or len(positional) == 2:
|
||||
break
|
||||
return positional
|
||||
|
||||
@@ -34,52 +64,54 @@ def docker_subcommand(arguments: list[str]) -> list[str]:
|
||||
def unlimited(arguments: list[str]) -> bool:
|
||||
"""Whether docker's arguments make a container, with docker run or docker create, and leave its memory or its swap without a limit.
|
||||
|
||||
The container's own arguments, past its image, are read too: telling them apart needs every value-taking option of docker run. So a -m 4g there reads as a limit, while python -m pytest does not, since pytest is no size.
|
||||
The container's own arguments, past its image, are read too: telling them apart needs every value-taking option of docker run. So a -m 4g there reads as a limit, while python -m pytest and grep -m 1 do not, since neither is a size docker takes.
|
||||
"""
|
||||
subcommand = docker_subcommand(arguments)
|
||||
limited = option_value(arguments, MEMORY_OPTIONS, SIZE) and option_value(arguments, SWAP_OPTIONS, SWAP)
|
||||
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments, subcommand)
|
||||
limited = option_value(arguments, MEMORY_OPTIONS, memory_limit) and option_value(arguments, SWAP_OPTIONS, swap_limit)
|
||||
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments)
|
||||
|
||||
|
||||
def capped(arguments: list[str], share: str) -> list[str]:
|
||||
"""docker's arguments with the limit a container they make lacks put right after the subcommand: the container's other limit, or share where it sets neither, as docker refuses less swap than memory. An unset or unlimited swap value gives way; every other word stays."""
|
||||
"""docker's arguments, with each limit a container they make lacks added right after the subcommand.
|
||||
|
||||
A container that sets neither limit gets share for both. One that sets one limit gets the other at the same size, since docker refuses less swap than memory. A --memory-swap of -1 or 0 is dropped; every other word stays.
|
||||
"""
|
||||
if not unlimited(arguments):
|
||||
return arguments
|
||||
memory = option_value(arguments, MEMORY_OPTIONS, SIZE)
|
||||
swap = option_value(arguments, SWAP_OPTIONS, SWAP)
|
||||
rest = without(arguments, SWAP_OPTIONS, UNSET_SWAP)
|
||||
memory = option_value(arguments, MEMORY_OPTIONS, memory_limit)
|
||||
swap = option_value(arguments, SWAP_OPTIONS, swap_limit)
|
||||
rest = without(arguments, SWAP_OPTIONS, unset_swap)
|
||||
limits = ([] if memory else ["--memory", swap or share]) + ([] if swap else ["--memory-swap", memory or share])
|
||||
after = rest.index(docker_subcommand(rest)[-1]) + 1
|
||||
after = subcommand_at(rest)[-1] + 1
|
||||
return [*rest[:after], *limits, *rest[after:]]
|
||||
|
||||
|
||||
def option_value(arguments: list[str], options: tuple[str, ...], pattern: str) -> str | None:
|
||||
"""The value the arguments give one of the options, where pattern matches it, as its next word or attached, as in -m4g or --memory=4g; None where they give none."""
|
||||
found = option_at(arguments, options, pattern)
|
||||
return found[2] if found else None
|
||||
def option_value(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> str | None:
|
||||
"""The value the arguments give one of the options, where it fits, as its next word or attached, as in -m4g or --memory=4g; None where they give none."""
|
||||
found = option_at(arguments, options, fits)
|
||||
return found.value if found else None
|
||||
|
||||
|
||||
def without(arguments: list[str], options: tuple[str, ...], pattern: str) -> list[str]:
|
||||
"""The arguments with each of the options removed, with its value, where pattern matches the value."""
|
||||
while found := option_at(arguments, options, pattern):
|
||||
start, length, _ = found
|
||||
arguments = [*arguments[:start], *arguments[start + length:]]
|
||||
def without(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> list[str]:
|
||||
"""The arguments with each of the options removed, with its value, where the value fits."""
|
||||
while found := option_at(arguments, options, fits):
|
||||
arguments = [*arguments[:found.at], *arguments[found.at + found.length:]]
|
||||
return arguments
|
||||
|
||||
|
||||
def option_at(arguments: list[str], options: tuple[str, ...], pattern: str) -> tuple[int, int, str] | None:
|
||||
"""Where the arguments first give one of the options a value pattern matches: its index, its length in words and the value."""
|
||||
def option_at(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> Option | None:
|
||||
"""Where the arguments first give one of the options, with a value that fits."""
|
||||
for at, (word, following) in enumerate(zip(arguments, [*arguments[1:], ""])):
|
||||
for option in options:
|
||||
attached = word.removeprefix(option if len(option) == 2 else option + "=")
|
||||
if attached != word and re.fullmatch(pattern, attached):
|
||||
return at, 1, attached
|
||||
if word == option and re.fullmatch(pattern, following):
|
||||
return at, 2, following
|
||||
if attached != word and fits(attached):
|
||||
return Option(at, 1, attached)
|
||||
if word == option and fits(following):
|
||||
return Option(at, 2, following)
|
||||
return None
|
||||
|
||||
|
||||
def helped(arguments: list[str], subcommand: list[str]) -> bool:
|
||||
def helped(arguments: list[str]) -> bool:
|
||||
"""Whether docker only prints its help: a --help before the subcommand or as the first word after it, not one the container's own command takes."""
|
||||
after = arguments.index(subcommand[-1]) + 1
|
||||
after = subcommand_at(arguments)[-1] + 1
|
||||
return "--help" in arguments[:after + 1]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it, whether at least ROOM_SHARE of it is available, which leaves room for a worker, and each heavy slot's share of the rest."""
|
||||
"""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
|
||||
@@ -17,9 +17,9 @@ class Memory:
|
||||
def has_room(self) -> bool:
|
||||
return self.available >= ROOM_SHARE * self.total
|
||||
|
||||
def slot_share(self, slots: int) -> str:
|
||||
"""The memory each heavy slot's containers may take, as docker writes a size: what ROOM_SHARE leaves, split evenly across the slots."""
|
||||
return f"{int(self.total * (1 - ROOM_SHARE)) // slots // 1024}m"
|
||||
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:
|
||||
|
||||
@@ -39,6 +39,12 @@ class MemoryShare(unittest.TestCase):
|
||||
self.assertIsNone(memory.read_memory(pathlib.Path(temp, "gone")))
|
||||
|
||||
|
||||
class SlotShare(unittest.TestCase):
|
||||
def test_splits_the_three_quarters_a_worker_leaves_evenly_across_the_slots_in_mib(self):
|
||||
self.assertEqual(memory.Memory(available=0, total=32 * 1024 * 1024).slot_share(4), 6144)
|
||||
self.assertEqual(memory.Memory(available=0, total=8000000).slot_share(2), 2929)
|
||||
|
||||
|
||||
class SlotFolder(unittest.TestCase):
|
||||
def test_every_session_shares_the_slots_under_the_users_state_folder(self):
|
||||
self.assertEqual(slots.slot_folder({}), pathlib.Path.home() / ".local" / "state" / "run-heavy")
|
||||
|
||||
@@ -32,7 +32,7 @@ RULES: dict[RuleName, Rule] = {
|
||||
),
|
||||
"docker-run-memory": Rule(
|
||||
"a container made with docker run or docker create has a memory limit and a swap limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so a runaway container fails alone instead of starving the machine; a swap limit equal to the memory limit keeps it out of swap",
|
||||
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. A container a script or docker compose starts is not checked",
|
||||
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. One under run-heavy passes, as run-heavy's docker adds the limits, unless it names docker by its path or sets its own PATH. A container a script or docker compose starts is not checked",
|
||||
),
|
||||
"ignorefile-sorted": Rule(
|
||||
"each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
|
||||
@@ -154,8 +154,11 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
|
||||
def unlimited_container(words: list[str]) -> bool:
|
||||
"""Whether the simple command, directly or through a launcher, starts a container that lacks a memory limit or a swap limit."""
|
||||
docker = launched(words, {"docker"})
|
||||
# Under run-heavy, its docker adds the limits a container lacks.
|
||||
return docker is not None and "run-heavy" not in docker.launchers and unlimited(docker.arguments)
|
||||
if docker is None or not unlimited(docker.arguments):
|
||||
return False
|
||||
# On Linux, run-heavy's docker adds the limits a container lacks, where PATH finds it: docker named bare, with no PATH of the command's own.
|
||||
capped = "run-heavy" in docker.launchers and words[len(words) - len(docker.arguments) - 1] == "docker" and not any(word.startswith("PATH=") for word in words)
|
||||
return not capped
|
||||
|
||||
|
||||
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
|
||||
|
||||
@@ -117,12 +117,12 @@ class CommandBreaches(unittest.TestCase):
|
||||
self.assertEqual(checked(command), [])
|
||||
|
||||
def test_a_docker_run_or_create_without_a_memory_limit_breaks_docker_run_memory(self):
|
||||
for command in ["docker run --rm node:24.22.1-alpine3.24 node x.js", "cd /w && docker run -v /w:/w alpine:3.22.2 true", "docker create alpine:3.22.2", "docker container run alpine:3.22.2 true", "docker container create alpine:3.22.2", "nice -n 19 docker run alpine:3.22.2 true", "docker -H unix:///d.sock run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 true", "docker run -m 4g alpine:3.22.2 true", "docker run --memory=4g alpine:3.22.2 sh -c 'x --memory-swap 4g'", "docker run -m 4g alpine:3.22.2 tool --memory-swap", "docker run -m 4g --memory-swap -1 alpine:3.22.2 true", "docker run -m 4g --memory-swap=0 alpine:3.22.2 true", "docker run --rm python:3.13.1 python -m pytest", "docker run alpine:3.22.2 git commit -m x", "timeout 60 docker run alpine:3.22.2 true", "docker run node:24.22.1-alpine3.24 node --help", "docker run alpine:3.22.2 --help", "docker run -m 4g alpine:3.22.2 sleep 60"]:
|
||||
for command in ["docker run --rm node:24.22.1-alpine3.24 node x.js", "cd /w && docker run -v /w:/w alpine:3.22.2 true", "docker create alpine:3.22.2", "docker container run alpine:3.22.2 true", "docker container create alpine:3.22.2", "nice -n 19 docker run alpine:3.22.2 true", "docker -H unix:///d.sock run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 true", "docker run -m 4g alpine:3.22.2 true", "docker run --memory=4g alpine:3.22.2 sh -c 'x --memory-swap 4g'", "docker run -m 4g alpine:3.22.2 tool --memory-swap", "docker run -m 4g --memory-swap -1 alpine:3.22.2 true", "docker run -m 4g --memory-swap=0 alpine:3.22.2 true", "docker run --rm python:3.13.1 python -m pytest", "docker run alpine:3.22.2 git commit -m x", "timeout 60 docker run alpine:3.22.2 true", "docker run node:24.22.1-alpine3.24 node --help", "docker run alpine:3.22.2 --help", "docker run -m 4g alpine:3.22.2 sleep 60", "~/.claude/bin/run-heavy /usr/bin/docker run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 grep -m 1 x", "run-heavy env PATH=/usr/bin docker run alpine:3.22.2 true"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(checked(command), ["docker-run-memory"])
|
||||
|
||||
def test_a_docker_run_with_a_memory_limit_or_another_docker_call_passes_docker_run_memory(self):
|
||||
for command in ["docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run -m4g --memory-swap=4g alpine:3.22.2 true", "docker run --memory 512M --memory-swap 1g alpine:3.22.2 true", "docker run -m 1073741824 --memory-swap 2g alpine:3.22.2 true", "timeout 60 docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run --rm --memory=1.5GiB --memory-swap=1.5GiB alpine:3.22.2 true", "docker container create -m 1g --memory-swap 1g alpine:3.22.2", "docker run --help", "docker container run --help", "docker --help", "docker ps", "docker images", "docker container ls", "docker compose run --rm app go vet", "docker exec box true", "echo docker run alpine:3.22.2", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true"]:
|
||||
for command in ["docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run -m4g --memory-swap=4g alpine:3.22.2 true", "docker run --memory 512M --memory-swap 1g alpine:3.22.2 true", "docker run -m 1073741824 --memory-swap 2g alpine:3.22.2 true", "timeout 60 docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run --rm --memory=1.5GiB --memory-swap=1.5GiB alpine:3.22.2 true", "docker container create -m 1g --memory-swap 1g alpine:3.22.2", "docker run --help", "docker container run --help", "docker --context run run --help", "docker --help", "docker ps", "docker images", "docker container ls", "docker compose run --rm app go vet", "docker exec box true", "echo docker run alpine:3.22.2", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(checked(command), [])
|
||||
|
||||
|
||||
+1
-1
@@ -5,8 +5,8 @@ import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from run_heavy import main
|
||||
from machine_load.memory import read_memory
|
||||
from machine_load.slots import usable_cpus
|
||||
from run_heavy import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, usable_cpus(), read_memory()))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The docker a heavy command finds first on its PATH: it gives a container the command makes the limits it lacks, the slot's memory share in RUN_HEAVY_MEMORY, then runs the real docker."""
|
||||
"""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
|
||||
@@ -7,17 +7,29 @@ import typing
|
||||
|
||||
from docker_command import capped
|
||||
|
||||
FOLDER = pathlib.Path(__file__).resolve().parent / "path_entry"
|
||||
SHARE = "RUN_HEAVY_MEMORY"
|
||||
# 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."""
|
||||
path = os.pathsep.join(entry for entry in env.get("PATH", "").split(os.pathsep) if pathlib.Path(entry or ".").resolve() != FOLDER)
|
||||
"""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)
|
||||
os.execve(docker, [docker, *(capped(argv, share) if share else argv)], {**env, "PATH": path})
|
||||
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 or ".").resolve() != PATH_ENTRY)
|
||||
|
||||
+17
-10
@@ -9,12 +9,17 @@ $XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot i
|
||||
says so once on stderr and waits. It then replaces itself with the command. The slot's lock stays held
|
||||
until the command, and every process that inherited the lock, exits. Its exit code is the command's.
|
||||
|
||||
Each container the command makes with docker run or docker create gets a memory limit and a swap limit,
|
||||
both the slot's share, where it sets neither: three quarters of the machine's memory, split across the
|
||||
slots. A docker first on the command's PATH adds them, and passes every other call on unchanged. A
|
||||
container that sets one of the two limits keeps it, and gets the other as large; an unlimited
|
||||
swap, --memory-swap -1, gives way. The share is in RUN_HEAVY_MEMORY. A docker compose service,
|
||||
or a docker named by its full path, gets no limit.
|
||||
On Linux, run-heavy also caps the memory of each container the command makes with docker run or
|
||||
docker create. The cap is the slot's share: three quarters of the machine's memory, split evenly
|
||||
across the slots, handed to the command in RUN_HEAVY_MEMORY, in MiB. run-heavy puts its own docker
|
||||
first on the command's PATH. That docker adds the limits a container lacks, then runs the real one:
|
||||
|
||||
- A container that sets neither limit gets a memory limit and a swap limit, both the share.
|
||||
- A container that sets one of them keeps it, and gets the other at the same size.
|
||||
- A --memory-swap of -1, unlimited swap, is dropped and replaced.
|
||||
|
||||
Every other docker call goes through unchanged. A docker compose service, and a docker named by its
|
||||
full path, get no cap: give those containers their own limits.
|
||||
|
||||
A command it runs carries the slot's number in RUN_HEAVY_SLOT, and run-heavy called with that set
|
||||
runs its command at once, so a gate that wraps its own steps cannot wait on itself.
|
||||
@@ -24,12 +29,13 @@ folder or a slot file cannot be made or locked; 126 when the command is found bu
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from run_heavy.capped_docker import FOLDER, SHARE
|
||||
from machine_load.memory import Memory
|
||||
from run_heavy.capped_docker import PATH_ENTRY, SHARE_VARIABLE, without_path_entry
|
||||
from machine_load.slots import slot_count, slot_folder, waited_slot
|
||||
|
||||
OWN_FAILURE = 125
|
||||
@@ -56,10 +62,11 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memor
|
||||
|
||||
|
||||
def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> dict[str, str]:
|
||||
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; nothing where the memory is unknown, as off Linux."""
|
||||
if memory is None:
|
||||
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; nothing where the memory is unknown, as off Linux, or where PATH finds no docker to cap."""
|
||||
path = env.get("PATH", "")
|
||||
if memory is None or shutil.which("docker", path=without_path_entry(path)) is None:
|
||||
return {}
|
||||
return {SHARE: memory.slot_share(slots), "PATH": os.pathsep.join([str(FOLDER), env.get("PATH", "")])}
|
||||
return {SHARE_VARIABLE: str(memory.slot_share(slots)), "PATH": os.pathsep.join([str(PATH_ENTRY), path])}
|
||||
|
||||
|
||||
def held_slot(folder: pathlib.Path, slots: int) -> int | Failure:
|
||||
|
||||
@@ -94,7 +94,8 @@ class RunHeavy(unittest.TestCase):
|
||||
|
||||
def test_a_docker_run_without_limits_gets_three_quarters_of_the_memory_split_across_the_slots(self):
|
||||
memory = read_memory()
|
||||
assert memory is not None
|
||||
if memory is None:
|
||||
self.skipTest("no /proc/meminfo to read the share from")
|
||||
share = f"{memory.total * 3 // 4 // slot_count(usable_cpus()) // 1024}m"
|
||||
result = self.run_tool("docker", "run", "--rm", "img", "true", env=self.fake_docker())
|
||||
self.assertEqual((result.returncode, result.stdout), (0, f"run --memory {share} --memory-swap {share} --rm img true\n"))
|
||||
@@ -106,6 +107,14 @@ class RunHeavy(unittest.TestCase):
|
||||
result = self.run_tool("docker", *args, env=env)
|
||||
self.assertEqual((result.returncode, result.stdout), (0, " ".join(args) + "\n"))
|
||||
|
||||
def test_a_command_on_a_machine_without_docker_finds_none(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
(pathlib.Path(folder.name) / "python3").symlink_to(sys.executable)
|
||||
(pathlib.Path(folder.name) / "sh").symlink_to("/bin/sh")
|
||||
result = self.run_tool("sh", "-c", "command -v docker || echo none", env={**self.env, "PATH": folder.name})
|
||||
self.assertEqual((result.returncode, result.stdout), (0, "none\n"))
|
||||
|
||||
def test_a_capped_docker_that_finds_no_docker_exits_127_saying_so(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
|
||||
@@ -9,7 +9,10 @@ class Capped(unittest.TestCase):
|
||||
(["run", "--rm", "img", "true"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "--rm", "img", "true"]),
|
||||
(["-H", "unix:///d.sock", "run", "img"], ["-H", "unix:///d.sock", "run", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
|
||||
(["container", "create", "img"], ["container", "create", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
|
||||
(["--context", "run", "run", "img"], ["--context", "run", "run", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
|
||||
(["run", "img", "python", "-m", "pytest"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "python", "-m", "pytest"]),
|
||||
(["run", "img", "grep", "-m", "1", "x"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "grep", "-m", "1", "x"]),
|
||||
(["run", "img", "stress", "--memory", "2"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "stress", "--memory", "2"]),
|
||||
]:
|
||||
with self.subTest(given):
|
||||
self.assertEqual(capped(given, "6144m"), expected)
|
||||
|
||||
Reference in New Issue
Block a user