42 lines
2.0 KiB
Python
42 lines
2.0 KiB
Python
"""What a docker command asks of docker: its subcommand, and whether a container it starts has a memory limit."""
|
|
import re
|
|
|
|
from shell_command import launched
|
|
|
|
# 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 start a container, which takes the memory limit docker run's -m sets.
|
|
STARTS_CONTAINER = (["run"], ["create"], ["container", "run"], ["container", "create"])
|
|
# -m4g is -m with its value attached; --memory-swap alone sets no limit.
|
|
MEMORY_LIMIT = re.compile(r"-m.*|--memory(=.*)?")
|
|
|
|
|
|
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] = []
|
|
skip = False
|
|
for word in 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:
|
|
break
|
|
return positional
|
|
|
|
|
|
def unlimited(arguments: list[str]) -> bool:
|
|
"""Whether docker's arguments start a container, with docker run or docker create, and set it no memory limit.
|
|
|
|
A --memory among the container's own arguments, past its image, reads as the limit too: telling it apart needs every value-taking option of docker run.
|
|
"""
|
|
return "--help" not in arguments and docker_subcommand(arguments) in STARTS_CONTAINER and not any(MEMORY_LIMIT.fullmatch(word) for word in arguments)
|
|
|
|
|
|
def unlimited_container(words: list[str]) -> bool:
|
|
"""Whether the simple command, directly or through a launcher, starts a container that has no memory limit."""
|
|
docker = launched(words, {"docker"})
|
|
return docker is not None and unlimited(docker.arguments)
|