118 lines
5.7 KiB
Python
118 lines
5.7 KiB
Python
"""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, 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",)
|
|
|
|
|
|
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"]."""
|
|
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 at, word in enumerate(arguments):
|
|
if skip:
|
|
skip = False
|
|
elif word.startswith("-"):
|
|
skip = word in DOCKER_VALUED
|
|
else:
|
|
positional.append(at)
|
|
if arguments[positional[0]] not in ("buildx", "compose", "container") or len(positional) == 2:
|
|
break
|
|
return positional
|
|
|
|
|
|
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 and grep -m 1 do not, since neither is a size docker takes.
|
|
"""
|
|
subcommand = docker_subcommand(arguments)
|
|
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 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, 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 = subcommand_at(rest)[-1] + 1
|
|
return [*rest[:after], *limits, *rest[after:]]
|
|
|
|
|
|
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, ...], 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, ...], 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 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]) -> 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 = subcommand_at(arguments)[-1] + 1
|
|
return "--help" in arguments[:after + 1]
|