composeready 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 José Luis Segura Yuste
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: composeready
3
+ Version: 0.1.4
4
+ Summary: Comprueba, antes de 'docker compose up', si el host real cumple lo que el compose asume: rutas de bind-mount, puertos libres y GPU/NVIDIA runtime.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/composeready
8
+ Project-URL: Source, https://github.com/jl-segurayuste/composeready
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/composeready/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/composeready/releases
11
+ Keywords: devops,docker,docker-compose,preflight
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: Natural Language :: Spanish
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Topic :: System :: Systems Administration
25
+ Classifier: Topic :: Software Development :: Build Tools
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: pyyaml>=6.0
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.4; extra == "dev"
32
+ Requires-Dist: pytest-cov>=5; extra == "dev"
33
+ Requires-Dist: ruff==0.17.6; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # composeready
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/composeready.svg)](https://pypi.org/project/composeready/)
39
+ [![CI](https://github.com/jl-segurayuste/composeready/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/composeready/actions/workflows/ci.yml)
40
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/composeready/blob/main/pyproject.toml)
41
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/composeready/blob/main/LICENSE)
42
+
43
+ Comprueba si el host real cumple lo que un `docker-compose.yml` asume,
44
+ **antes** de lanzar `docker compose up` — no después, cuando el error ya
45
+ salió confuso y a medias.
46
+
47
+ Tres cosas que Docker solo descubre en el momento:
48
+
49
+ - **Rutas de bind-mount**: si `./data:/app/data` apunta a algo que no
50
+ existe en este host, Docker falla con un error sobre la ruta — pero solo
51
+ cuando ya intentó arrancar el contenedor.
52
+ - **Puertos publicados**: si `8080:80` ya está ocupado por otra cosa, el
53
+ error de "address already in use" no siempre deja claro *qué* servicio
54
+ del compose falló ni por qué.
55
+ - **GPU/NVIDIA**: si el servicio pide `runtime: nvidia`, `gpus: all`, un
56
+ dispositivo CDI `nvidia.com/gpu=...` o `deploy.resources.reservations.devices`
57
+ con `driver: nvidia` y el host
58
+ no tiene el runtime instalado, el contenedor puede arrancar igualmente
59
+ — solo que corriendo por CPU, en silencio, sin ningún error visible.
60
+
61
+ `composeready` lee el YAML y comprueba las tres cosas contra el host real
62
+ en el que se ejecuta, sin arrancar ningún contenedor.
63
+
64
+ ## Así se ve
65
+
66
+ ![Salida de composeready sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/composeready/main/docs/img/demo.svg)
67
+
68
+ <sub>Ejecución real sobre un `compose.yaml` cuyo puerto ya está ocupado, con carpetas que no existen y que pide una GPU que el equipo no tiene (todos los datos son ficticios).</sub>
69
+
70
+ ## Instalación
71
+
72
+ ```bash
73
+ pipx install composeready # recomendado para herramientas de línea de comandos
74
+ # o bien
75
+ pip install composeready
76
+ ```
77
+
78
+ ## Uso
79
+
80
+ ```bash
81
+ composeready # busca docker-compose.yml en el directorio actual
82
+ composeready ruta/al/compose.yml # o un fichero concreto
83
+ composeready --skip gpu . # omite un check (bind_mount, port, gpu)
84
+ ```
85
+
86
+ Sale con código 1 si encuentra algo, 0 si el host está listo.
87
+
88
+ ## Qué NO comprueba (a propósito)
89
+
90
+ - Rangos de puertos (`8080-8090:80-90`) — poco frecuentes, mucho parseo
91
+ extra para el valor que aportan.
92
+ - UDP — un simple `bind()` no dice de forma fiable si un puerto UDP está
93
+ realmente en uso.
94
+ - Que la GPU *funcione* de verdad (versión de CUDA, memoria libre...) —
95
+ solo que exista al menos un `/dev/nvidia*` y el binario `nvidia-smi`.
96
+ Es la comprobación mínima determinista de "¿hay GPU aquí siquiera?",
97
+ no un diagnóstico completo del stack NVIDIA.
98
+ - Sustitución de variables más allá de `${VAR}`, `${VAR:-def}`, `${VAR-def}`
99
+ y `$VAR` — no reimplementa el intérprete completo de Compose. Las variables
100
+ salen, como en Compose, del `.env` de la carpeta del proyecto y del entorno
101
+ (que tiene prioridad).
102
+
103
+ ## Desarrollo
104
+
105
+ ```bash
106
+ python -m venv .venv && source .venv/bin/activate
107
+ pip install -e ".[dev]"
108
+ ruff check .
109
+ pytest
110
+ ```
@@ -0,0 +1,75 @@
1
+ # composeready
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/composeready.svg)](https://pypi.org/project/composeready/)
4
+ [![CI](https://github.com/jl-segurayuste/composeready/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/composeready/actions/workflows/ci.yml)
5
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/composeready/blob/main/pyproject.toml)
6
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/composeready/blob/main/LICENSE)
7
+
8
+ Comprueba si el host real cumple lo que un `docker-compose.yml` asume,
9
+ **antes** de lanzar `docker compose up` — no después, cuando el error ya
10
+ salió confuso y a medias.
11
+
12
+ Tres cosas que Docker solo descubre en el momento:
13
+
14
+ - **Rutas de bind-mount**: si `./data:/app/data` apunta a algo que no
15
+ existe en este host, Docker falla con un error sobre la ruta — pero solo
16
+ cuando ya intentó arrancar el contenedor.
17
+ - **Puertos publicados**: si `8080:80` ya está ocupado por otra cosa, el
18
+ error de "address already in use" no siempre deja claro *qué* servicio
19
+ del compose falló ni por qué.
20
+ - **GPU/NVIDIA**: si el servicio pide `runtime: nvidia`, `gpus: all`, un
21
+ dispositivo CDI `nvidia.com/gpu=...` o `deploy.resources.reservations.devices`
22
+ con `driver: nvidia` y el host
23
+ no tiene el runtime instalado, el contenedor puede arrancar igualmente
24
+ — solo que corriendo por CPU, en silencio, sin ningún error visible.
25
+
26
+ `composeready` lee el YAML y comprueba las tres cosas contra el host real
27
+ en el que se ejecuta, sin arrancar ningún contenedor.
28
+
29
+ ## Así se ve
30
+
31
+ ![Salida de composeready sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/composeready/main/docs/img/demo.svg)
32
+
33
+ <sub>Ejecución real sobre un `compose.yaml` cuyo puerto ya está ocupado, con carpetas que no existen y que pide una GPU que el equipo no tiene (todos los datos son ficticios).</sub>
34
+
35
+ ## Instalación
36
+
37
+ ```bash
38
+ pipx install composeready # recomendado para herramientas de línea de comandos
39
+ # o bien
40
+ pip install composeready
41
+ ```
42
+
43
+ ## Uso
44
+
45
+ ```bash
46
+ composeready # busca docker-compose.yml en el directorio actual
47
+ composeready ruta/al/compose.yml # o un fichero concreto
48
+ composeready --skip gpu . # omite un check (bind_mount, port, gpu)
49
+ ```
50
+
51
+ Sale con código 1 si encuentra algo, 0 si el host está listo.
52
+
53
+ ## Qué NO comprueba (a propósito)
54
+
55
+ - Rangos de puertos (`8080-8090:80-90`) — poco frecuentes, mucho parseo
56
+ extra para el valor que aportan.
57
+ - UDP — un simple `bind()` no dice de forma fiable si un puerto UDP está
58
+ realmente en uso.
59
+ - Que la GPU *funcione* de verdad (versión de CUDA, memoria libre...) —
60
+ solo que exista al menos un `/dev/nvidia*` y el binario `nvidia-smi`.
61
+ Es la comprobación mínima determinista de "¿hay GPU aquí siquiera?",
62
+ no un diagnóstico completo del stack NVIDIA.
63
+ - Sustitución de variables más allá de `${VAR}`, `${VAR:-def}`, `${VAR-def}`
64
+ y `$VAR` — no reimplementa el intérprete completo de Compose. Las variables
65
+ salen, como en Compose, del `.env` de la carpeta del proyecto y del entorno
66
+ (que tiene prioridad).
67
+
68
+ ## Desarrollo
69
+
70
+ ```bash
71
+ python -m venv .venv && source .venv/bin/activate
72
+ pip install -e ".[dev]"
73
+ ruff check .
74
+ pytest
75
+ ```
@@ -0,0 +1,10 @@
1
+ """composeready — comprueba si el host real está listo para un compose.
2
+
3
+ Antes de `docker compose up`, lee el fichero y comprueba tres cosas que
4
+ docker solo descubre en el momento (y con errores a veces confusos): que
5
+ las rutas de bind-mount existan de verdad en este host, que los puertos
6
+ publicados no estén ya ocupados, y que el runtime NVIDIA esté disponible
7
+ si el compose pide GPU.
8
+ """
9
+
10
+ __version__ = "0.1.4"
File without changes
@@ -0,0 +1,69 @@
1
+ """Comprueba que las rutas de origen de los bind-mounts existan en el host.
2
+
3
+ Ignora los volúmenes con nombre (`mydata:/app/data`) — solo mira rutas de
4
+ host explícitas, ya sean relativas (`./data:...`), absolutas (`/srv/...`)
5
+ o con `~`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from ..compose import resolve_env
14
+ from ..finding import Finding
15
+
16
+
17
+ def _looks_like_host_path(source: str) -> bool:
18
+ return source.startswith((".", "/", "~"))
19
+
20
+
21
+ def _short_form_source(entry: str) -> str | None:
22
+ # "./host:/container[:ro]" o "/abs/host:/container[:ro]" — el primer
23
+ # ':' separa host de container, salvo que sea una letra de unidad de
24
+ # Windows (poco relevante aquí, pero evita cortar mal "C:\...").
25
+ parts = entry.split(":")
26
+ if len(parts) < 2:
27
+ return None
28
+ source = parts[0]
29
+ return source if _looks_like_host_path(source) else None
30
+
31
+
32
+ def check(
33
+ service_name: str, service: dict[str, Any], compose_dir: Path, env: dict[str, str] | None = None
34
+ ) -> list[Finding]:
35
+ findings: list[Finding] = []
36
+ volumes = service.get("volumes")
37
+ if not isinstance(volumes, list):
38
+ return findings
39
+
40
+ for entry in volumes:
41
+ source: str | None = None
42
+
43
+ if isinstance(entry, str):
44
+ source = _short_form_source(resolve_env(entry, env))
45
+ elif isinstance(entry, dict) and entry.get("type") == "bind":
46
+ raw = entry.get("source")
47
+ if isinstance(raw, str):
48
+ resolved = resolve_env(raw, env)
49
+ if _looks_like_host_path(resolved) or Path(resolved).is_absolute():
50
+ source = resolved
51
+
52
+ if source is None:
53
+ continue
54
+
55
+ resolved_path = Path(source).expanduser()
56
+ if not resolved_path.is_absolute():
57
+ resolved_path = compose_dir / resolved_path
58
+
59
+ if not resolved_path.exists():
60
+ findings.append(
61
+ Finding(
62
+ check="bind_mount",
63
+ service=service_name,
64
+ message=f"la ruta de origen '{source}' no existe en este host",
65
+ detail=f"se resolvió a: {resolved_path}",
66
+ )
67
+ )
68
+
69
+ return findings
@@ -0,0 +1,83 @@
1
+ """Comprueba que el host tenga runtime NVIDIA si el servicio pide GPU.
2
+
3
+ Formas de pedir GPU en un compose: la vieja (`runtime: nvidia`), `gpus: all`,
4
+ dispositivos CDI (`nvidia.com/gpu=...`) y `deploy.resources.reservations.devices`
5
+ con `driver: nvidia`, `capabilities: [gpu]` o `device_ids` CDI. No verifica que el modelo/CUDA concretos vayan a
6
+ funcionar — solo que exista al menos un dispositivo `/dev/nvidia*` y el
7
+ binario `nvidia-smi`, la comprobación mínima y determinista de "¿hay
8
+ GPU aquí siquiera?".
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import glob
14
+ import shutil
15
+ from typing import Any
16
+
17
+ from ..finding import Finding
18
+
19
+
20
+ def _is_cdi_gpu(value: Any) -> bool:
21
+ return isinstance(value, str) and value.startswith("nvidia.com/gpu")
22
+
23
+
24
+ def _requests_gpu(service: dict[str, Any]) -> bool:
25
+ if service.get("runtime") == "nvidia":
26
+ return True
27
+ # `gpus: all` (o una lista) es la forma corta actual de Compose.
28
+ if service.get("gpus"):
29
+ return True
30
+ # Dispositivos CDI: `devices: [nvidia.com/gpu=all]`, en forma corta o larga.
31
+ for dev in service.get("devices") or []:
32
+ if _is_cdi_gpu(dev) or (isinstance(dev, dict) and _is_cdi_gpu(dev.get("source"))):
33
+ return True
34
+
35
+ deploy = service.get("deploy")
36
+ if not isinstance(deploy, dict):
37
+ return False
38
+ resources = deploy.get("resources")
39
+ if not isinstance(resources, dict):
40
+ return False
41
+ reservations = resources.get("reservations")
42
+ if not isinstance(reservations, dict):
43
+ return False
44
+ devices = reservations.get("devices")
45
+ if not isinstance(devices, list):
46
+ return False
47
+
48
+ for device in devices:
49
+ if not isinstance(device, dict):
50
+ continue
51
+ if device.get("driver") == "nvidia":
52
+ return True
53
+ ids = device.get("device_ids")
54
+ if isinstance(ids, list) and any(_is_cdi_gpu(i) for i in ids):
55
+ return True
56
+ capabilities = device.get("capabilities")
57
+ if isinstance(capabilities, list) and "gpu" in capabilities:
58
+ return True
59
+
60
+ return False
61
+
62
+
63
+ def check(service_name: str, service: dict[str, Any]) -> list[Finding]:
64
+ if not _requests_gpu(service):
65
+ return []
66
+
67
+ problems = []
68
+ if not glob.glob("/dev/nvidia*"):
69
+ problems.append("no se encontró ningún /dev/nvidia* en este host")
70
+ if shutil.which("nvidia-smi") is None:
71
+ problems.append("nvidia-smi no está en el PATH")
72
+
73
+ if not problems:
74
+ return []
75
+
76
+ return [
77
+ Finding(
78
+ check="gpu",
79
+ service=service_name,
80
+ message="pide GPU NVIDIA pero este host no parece tenerla lista",
81
+ detail="; ".join(problems),
82
+ )
83
+ ]
@@ -0,0 +1,93 @@
1
+ """Comprueba que los puertos publicados no estén ya ocupados en el host.
2
+
3
+ Solo TCP — UDP no se puede comprobar de forma fiable con un simple bind
4
+ (muchos servicios UDP no mantienen el socket abierto entre paquetes).
5
+ Rangos de puertos (`8080-8090:80-90`) se ignoran deliberadamente: son
6
+ poco frecuentes y añaden bastante complejidad de parseo para el valor que
7
+ aportan.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import socket
13
+ from typing import Any
14
+
15
+ from ..compose import resolve_env
16
+ from ..finding import Finding
17
+
18
+
19
+ def _short_form_host_port(entry: str) -> int | None:
20
+ body = entry.split("/")[0] # descarta "/udp", "/tcp"
21
+ if "-" in body:
22
+ return None # rango, no soportado
23
+ parts = body.split(":")
24
+ if len(parts) == 1:
25
+ return None # solo puerto de contenedor, no se publica nada
26
+ host_part = parts[-2]
27
+ try:
28
+ return int(host_part)
29
+ except ValueError:
30
+ return None
31
+
32
+
33
+ def _is_port_taken(port: int) -> bool | None:
34
+ """True si está ocupado, False si está libre, None si no se pudo determinar."""
35
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
36
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 0)
37
+ try:
38
+ sock.bind(("0.0.0.0", port))
39
+ except PermissionError:
40
+ return None
41
+ except OSError:
42
+ return True
43
+ else:
44
+ return False
45
+ finally:
46
+ sock.close()
47
+
48
+
49
+ def check(service_name: str, service: dict[str, Any], env: dict[str, str] | None = None) -> list[Finding]:
50
+ findings: list[Finding] = []
51
+ ports = service.get("ports")
52
+ if not isinstance(ports, list):
53
+ return findings
54
+
55
+ for entry in ports:
56
+ host_port: int | None = None
57
+ protocol = "tcp"
58
+
59
+ if isinstance(entry, str):
60
+ # "${WEB_PORT:-8080}:80": sin resolver, el "-" del valor por defecto parecía un rango
61
+ # y el puerto no se comprobaba
62
+ entry = resolve_env(entry, env)
63
+ host_port = _short_form_host_port(entry)
64
+ if "/udp" in entry:
65
+ protocol = "udp"
66
+ elif isinstance(entry, int):
67
+ host_port = None # forma corta "80" sin publicar, nada que comprobar
68
+ elif isinstance(entry, dict):
69
+ published = entry.get("published")
70
+ if isinstance(published, str):
71
+ published = resolve_env(published, env)
72
+ protocol = entry.get("protocol", "tcp")
73
+ if published is not None:
74
+ try:
75
+ host_port = int(published)
76
+ except (TypeError, ValueError):
77
+ host_port = None
78
+
79
+ if host_port is None or protocol != "tcp":
80
+ continue
81
+
82
+ taken = _is_port_taken(host_port)
83
+ if taken:
84
+ findings.append(
85
+ Finding(
86
+ check="port",
87
+ service=service_name,
88
+ message=f"el puerto {host_port}/tcp ya está ocupado en este host",
89
+ detail="algo (otro contenedor, otro servicio) ya lo tiene enlazado",
90
+ )
91
+ )
92
+
93
+ return findings
@@ -0,0 +1,84 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+
9
+ from . import __version__
10
+ from .checks import bind_mounts, gpu, ports
11
+ from .compose import find_compose_file, iter_services, load_compose, project_env
12
+ from .finding import Finding
13
+
14
+
15
+ def run(compose_path: Path, skip: set[str]) -> list[Finding]:
16
+ data = load_compose(compose_path)
17
+ compose_dir = compose_path.parent
18
+ env = project_env(compose_dir)
19
+ findings: list[Finding] = []
20
+
21
+ for name, service in iter_services(data):
22
+ if "bind_mount" not in skip:
23
+ findings.extend(bind_mounts.check(name, service, compose_dir, env))
24
+ if "port" not in skip:
25
+ findings.extend(ports.check(name, service, env))
26
+ if "gpu" not in skip:
27
+ findings.extend(gpu.check(name, service))
28
+
29
+ return findings
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ parser = argparse.ArgumentParser(
34
+ prog="composeready",
35
+ description=(
36
+ "Comprueba si el host real cumple lo que un docker-compose asume "
37
+ "(rutas de bind-mount, puertos libres, GPU) antes de levantarlo."
38
+ ),
39
+ )
40
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
41
+ parser.add_argument(
42
+ "path",
43
+ nargs="?",
44
+ default=".",
45
+ help="Fichero compose o directorio que lo contiene (por defecto: directorio actual)",
46
+ )
47
+ parser.add_argument(
48
+ "--skip",
49
+ action="append",
50
+ choices=["bind_mount", "port", "gpu"],
51
+ default=[],
52
+ help="Check a omitir (repetible)",
53
+ )
54
+ return parser
55
+
56
+
57
+ def main(argv: list[str] | None = None) -> int:
58
+ parser = build_parser()
59
+ args = parser.parse_args(argv)
60
+
61
+ compose_path = find_compose_file(Path(args.path))
62
+ if compose_path is None:
63
+ print(f"composeready: no se encontró ningún fichero compose en '{args.path}'", file=sys.stderr)
64
+ return 2
65
+
66
+ try:
67
+ findings = run(compose_path, set(args.skip))
68
+ except (OSError, yaml.YAMLError) as exc:
69
+ # 2 y no 1: 1 significa «el host no cumple»; un compose ilegible es otra cosa.
70
+ print(f"composeready: no se pudo leer {compose_path}: {exc}", file=sys.stderr)
71
+ return 2
72
+
73
+ if not findings:
74
+ print(f"composeready: {compose_path} — listo, el host cumple lo que asume.")
75
+ return 0
76
+
77
+ for f in findings:
78
+ print(f.format())
79
+ print(f"\n{len(findings)} problema(s) encontrado(s) antes de arrancar.")
80
+ return 1
81
+
82
+
83
+ if __name__ == "__main__":
84
+ raise SystemExit(main())
@@ -0,0 +1,86 @@
1
+ """Carga de un fichero docker-compose y utilidades comunes a los checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ _VAR_RE = re.compile(
13
+ r"\$\{(?P<name>[A-Za-z_][A-Za-z0-9_]*)(?:(?P<colon>:)?-(?P<default>[^}]*))?\}|\$(?P<bare>[A-Za-z_][A-Za-z0-9_]*)"
14
+ )
15
+
16
+
17
+ def resolve_env(text: str, env: dict[str, str] | None = None) -> str:
18
+ """Sustituye ${VAR}, ${VAR:-default} y $VAR usando el entorno real.
19
+
20
+ Si una variable no está definida y no tiene default, se deja el texto
21
+ literal tal cual (mejor un falso negativo aislado que reventar aquí).
22
+ """
23
+ env = os.environ if env is None else env
24
+
25
+ def _sub(m: re.Match[str]) -> str:
26
+ name = m.group("name") or m.group("bare")
27
+ default = m.group("default")
28
+ # ${VAR:-x} usa x también si VAR está vacía; ${VAR-x}, solo si no existe
29
+ if name in env and not (m.group("colon") and default is not None and env[name] == ""):
30
+ return env[name]
31
+ return default if default is not None else m.group(0)
32
+
33
+ return _VAR_RE.sub(_sub, text)
34
+
35
+
36
+ def load_dotenv(path: Path) -> dict[str, str]:
37
+ """Variables de un `.env` (CLAVE=valor; admite comillas y `export`)."""
38
+ values: dict[str, str] = {}
39
+ try:
40
+ lines = path.read_text(errors="replace").splitlines()
41
+ except OSError:
42
+ return values
43
+ for line in lines:
44
+ line = line.strip()
45
+ if not line or line.startswith("#") or "=" not in line:
46
+ continue
47
+ key, _, value = line.removeprefix("export ").partition("=")
48
+ value = value.strip()
49
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
50
+ value = value[1:-1]
51
+ else:
52
+ value = value.split(" #", 1)[0].strip()
53
+ values[key.strip()] = value
54
+ return values
55
+
56
+
57
+ def project_env(compose_dir: Path) -> dict[str, str]:
58
+ """Variables con las que docker compose interpola el fichero: el `.env` de la carpeta del
59
+ proyecto y, por encima, el entorno. Antes solo se miraba el entorno y, con el puerto o la ruta
60
+ en el `.env`, se comprobaba el valor por defecto en vez del real."""
61
+ return {**load_dotenv(compose_dir / ".env"), **os.environ}
62
+
63
+
64
+ def load_compose(path: Path) -> dict[str, Any]:
65
+ data = yaml.safe_load(path.read_text(errors="replace"))
66
+ if not isinstance(data, dict):
67
+ return {}
68
+ return data
69
+
70
+
71
+ def iter_services(data: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]:
72
+ services = data.get("services")
73
+ if not isinstance(services, dict):
74
+ return []
75
+ return [(name, svc) for name, svc in services.items() if isinstance(svc, dict)]
76
+
77
+
78
+ def find_compose_file(path: Path) -> Path | None:
79
+ if path.is_file():
80
+ return path
81
+ # El mismo orden que `docker compose`: si hay varios, se comprueba el que va a usar.
82
+ for name in ("compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml"):
83
+ candidate = path / name
84
+ if candidate.is_file():
85
+ return candidate
86
+ return None
@@ -0,0 +1,18 @@
1
+ """Modelo de datos compartido por todos los checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Finding:
10
+ """Algo que este compose asume del host y que el host, ahora mismo, no cumple."""
11
+
12
+ check: str
13
+ service: str
14
+ message: str
15
+ detail: str
16
+
17
+ def format(self) -> str:
18
+ return f"[{self.check}] servicio '{self.service}': {self.message}\n {self.detail}"
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: composeready
3
+ Version: 0.1.4
4
+ Summary: Comprueba, antes de 'docker compose up', si el host real cumple lo que el compose asume: rutas de bind-mount, puertos libres y GPU/NVIDIA runtime.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/composeready
8
+ Project-URL: Source, https://github.com/jl-segurayuste/composeready
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/composeready/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/composeready/releases
11
+ Keywords: devops,docker,docker-compose,preflight
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: Natural Language :: Spanish
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Topic :: System :: Systems Administration
25
+ Classifier: Topic :: Software Development :: Build Tools
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: pyyaml>=6.0
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.4; extra == "dev"
32
+ Requires-Dist: pytest-cov>=5; extra == "dev"
33
+ Requires-Dist: ruff==0.17.6; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # composeready
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/composeready.svg)](https://pypi.org/project/composeready/)
39
+ [![CI](https://github.com/jl-segurayuste/composeready/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/composeready/actions/workflows/ci.yml)
40
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/composeready/blob/main/pyproject.toml)
41
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/composeready/blob/main/LICENSE)
42
+
43
+ Comprueba si el host real cumple lo que un `docker-compose.yml` asume,
44
+ **antes** de lanzar `docker compose up` — no después, cuando el error ya
45
+ salió confuso y a medias.
46
+
47
+ Tres cosas que Docker solo descubre en el momento:
48
+
49
+ - **Rutas de bind-mount**: si `./data:/app/data` apunta a algo que no
50
+ existe en este host, Docker falla con un error sobre la ruta — pero solo
51
+ cuando ya intentó arrancar el contenedor.
52
+ - **Puertos publicados**: si `8080:80` ya está ocupado por otra cosa, el
53
+ error de "address already in use" no siempre deja claro *qué* servicio
54
+ del compose falló ni por qué.
55
+ - **GPU/NVIDIA**: si el servicio pide `runtime: nvidia`, `gpus: all`, un
56
+ dispositivo CDI `nvidia.com/gpu=...` o `deploy.resources.reservations.devices`
57
+ con `driver: nvidia` y el host
58
+ no tiene el runtime instalado, el contenedor puede arrancar igualmente
59
+ — solo que corriendo por CPU, en silencio, sin ningún error visible.
60
+
61
+ `composeready` lee el YAML y comprueba las tres cosas contra el host real
62
+ en el que se ejecuta, sin arrancar ningún contenedor.
63
+
64
+ ## Así se ve
65
+
66
+ ![Salida de composeready sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/composeready/main/docs/img/demo.svg)
67
+
68
+ <sub>Ejecución real sobre un `compose.yaml` cuyo puerto ya está ocupado, con carpetas que no existen y que pide una GPU que el equipo no tiene (todos los datos son ficticios).</sub>
69
+
70
+ ## Instalación
71
+
72
+ ```bash
73
+ pipx install composeready # recomendado para herramientas de línea de comandos
74
+ # o bien
75
+ pip install composeready
76
+ ```
77
+
78
+ ## Uso
79
+
80
+ ```bash
81
+ composeready # busca docker-compose.yml en el directorio actual
82
+ composeready ruta/al/compose.yml # o un fichero concreto
83
+ composeready --skip gpu . # omite un check (bind_mount, port, gpu)
84
+ ```
85
+
86
+ Sale con código 1 si encuentra algo, 0 si el host está listo.
87
+
88
+ ## Qué NO comprueba (a propósito)
89
+
90
+ - Rangos de puertos (`8080-8090:80-90`) — poco frecuentes, mucho parseo
91
+ extra para el valor que aportan.
92
+ - UDP — un simple `bind()` no dice de forma fiable si un puerto UDP está
93
+ realmente en uso.
94
+ - Que la GPU *funcione* de verdad (versión de CUDA, memoria libre...) —
95
+ solo que exista al menos un `/dev/nvidia*` y el binario `nvidia-smi`.
96
+ Es la comprobación mínima determinista de "¿hay GPU aquí siquiera?",
97
+ no un diagnóstico completo del stack NVIDIA.
98
+ - Sustitución de variables más allá de `${VAR}`, `${VAR:-def}`, `${VAR-def}`
99
+ y `$VAR` — no reimplementa el intérprete completo de Compose. Las variables
100
+ salen, como en Compose, del `.env` de la carpeta del proyecto y del entorno
101
+ (que tiene prioridad).
102
+
103
+ ## Desarrollo
104
+
105
+ ```bash
106
+ python -m venv .venv && source .venv/bin/activate
107
+ pip install -e ".[dev]"
108
+ ruff check .
109
+ pytest
110
+ ```
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ composeready/__init__.py
5
+ composeready/cli.py
6
+ composeready/compose.py
7
+ composeready/finding.py
8
+ composeready.egg-info/PKG-INFO
9
+ composeready.egg-info/SOURCES.txt
10
+ composeready.egg-info/dependency_links.txt
11
+ composeready.egg-info/entry_points.txt
12
+ composeready.egg-info/requires.txt
13
+ composeready.egg-info/top_level.txt
14
+ composeready/checks/__init__.py
15
+ composeready/checks/bind_mounts.py
16
+ composeready/checks/gpu.py
17
+ composeready/checks/ports.py
18
+ tests/test_bind_mounts.py
19
+ tests/test_cli.py
20
+ tests/test_compose.py
21
+ tests/test_gpu.py
22
+ tests/test_ports.py
23
+ tests/test_version.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ composeready = composeready.cli:main
@@ -0,0 +1,6 @@
1
+ pyyaml>=6.0
2
+
3
+ [dev]
4
+ pytest>=7.4
5
+ pytest-cov>=5
6
+ ruff==0.17.6
@@ -0,0 +1 @@
1
+ composeready
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "composeready"
3
+ version = "0.1.4"
4
+ description = "Comprueba, antes de 'docker compose up', si el host real cumple lo que el compose asume: rutas de bind-mount, puertos libres y GPU/NVIDIA runtime."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [{ name = "José Luis Segura Yuste" }]
8
+ keywords = ["devops", "docker", "docker-compose", "preflight"]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Environment :: Console",
12
+ "Intended Audience :: Developers",
13
+ "Intended Audience :: System Administrators",
14
+ "Natural Language :: Spanish",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
22
+ "Topic :: System :: Systems Administration",
23
+ "Topic :: Software Development :: Build Tools",
24
+ ]
25
+ requires-python = ">=3.11"
26
+ dependencies = [
27
+ "pyyaml>=6.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=7.4",
33
+ "pytest-cov>=5",
34
+ "ruff==0.17.6",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/jl-segurayuste/composeready"
39
+ Source = "https://github.com/jl-segurayuste/composeready"
40
+ Issues = "https://github.com/jl-segurayuste/composeready/issues"
41
+ Changelog = "https://github.com/jl-segurayuste/composeready/releases"
42
+
43
+ [project.scripts]
44
+ composeready = "composeready.cli:main"
45
+
46
+ [build-system]
47
+ requires = ["setuptools>=77"]
48
+ build-backend = "setuptools.build_meta"
49
+
50
+ [tool.setuptools.packages.find]
51
+ include = ["composeready*"]
52
+
53
+ [tool.ruff]
54
+ line-length = 100
55
+ target-version = "py311"
56
+
57
+ [tool.coverage.run]
58
+ branch = true
59
+ source = ["composeready"]
60
+
61
+ [tool.coverage.report]
62
+ # Mínimo exigido en el CI: la cobertura medida al añadirlo (94 %) menos un margen.
63
+ fail_under = 91
64
+ show_missing = true
65
+ skip_covered = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,56 @@
1
+ from composeready.checks.bind_mounts import check
2
+
3
+
4
+ def test_flags_missing_relative_path(tmp_path):
5
+ service = {"volumes": ["./data:/app/data"]}
6
+ findings = check("web", service, tmp_path)
7
+ assert len(findings) == 1
8
+ assert "./data" in findings[0].message
9
+
10
+
11
+ def test_does_not_flag_existing_path(tmp_path):
12
+ (tmp_path / "data").mkdir()
13
+ service = {"volumes": ["./data:/app/data"]}
14
+ findings = check("web", service, tmp_path)
15
+ assert findings == []
16
+
17
+
18
+ def test_ignores_named_volumes(tmp_path):
19
+ service = {"volumes": ["mydata:/app/data"]}
20
+ findings = check("web", service, tmp_path)
21
+ assert findings == []
22
+
23
+
24
+ def test_flags_missing_absolute_path(tmp_path):
25
+ service = {"volumes": ["/does/not/exist:/app/data:ro"]}
26
+ findings = check("web", service, tmp_path)
27
+ assert len(findings) == 1
28
+
29
+
30
+ def test_long_form_bind_missing(tmp_path):
31
+ service = {
32
+ "volumes": [
33
+ {"type": "bind", "source": "/does/not/exist", "target": "/app/data"},
34
+ ]
35
+ }
36
+ findings = check("web", service, tmp_path)
37
+ assert len(findings) == 1
38
+
39
+
40
+ def test_long_form_named_volume_ignored(tmp_path):
41
+ service = {"volumes": [{"type": "volume", "source": "mydata", "target": "/app/data"}]}
42
+ findings = check("web", service, tmp_path)
43
+ assert findings == []
44
+
45
+
46
+ def test_env_var_expanded(tmp_path, monkeypatch):
47
+ real = tmp_path / "real-data"
48
+ real.mkdir()
49
+ monkeypatch.setenv("DATA_DIR", str(real))
50
+ service = {"volumes": ["${DATA_DIR}:/app/data"]}
51
+ findings = check("web", service, tmp_path)
52
+ assert findings == []
53
+
54
+
55
+ def test_no_volumes_key(tmp_path):
56
+ assert check("web", {}, tmp_path) == []
@@ -0,0 +1,41 @@
1
+ from pathlib import Path
2
+
3
+ from composeready.cli import main
4
+
5
+ FIXTURES = Path(__file__).parent / "fixtures"
6
+
7
+
8
+ def test_cli_flags_missing_bind_mount(capsys):
9
+ code = main([str(FIXTURES / "docker-compose.yml")])
10
+ out = capsys.readouterr().out
11
+ assert code == 1
12
+ assert "missing-dir" in out
13
+
14
+
15
+ def test_cli_clean_compose(tmp_path, capsys):
16
+ f = tmp_path / "docker-compose.yml"
17
+ f.write_text("services:\n web:\n image: nginx\n")
18
+ code = main([str(f)])
19
+ out = capsys.readouterr().out
20
+ assert code == 0
21
+ assert "listo" in out
22
+
23
+
24
+ def test_cli_missing_file_exits_2():
25
+ assert main(["/does/not/exist"]) == 2
26
+
27
+
28
+ def test_cli_finds_compose_in_directory(tmp_path):
29
+ (tmp_path / "compose.yaml").write_text("services:\n web:\n image: nginx\n")
30
+ assert main([str(tmp_path)]) == 0
31
+
32
+
33
+ def test_cli_skip_flag(capsys):
34
+ code = main([str(FIXTURES / "docker-compose.yml"), "--skip", "bind_mount", "--skip", "port"])
35
+ assert code == 0
36
+
37
+
38
+ def test_cli_yaml_invalido_sale_2_sin_traza(tmp_path, capsys):
39
+ (tmp_path / "compose.yml").write_text("services:\n a: [\n")
40
+ assert main([str(tmp_path)]) == 2
41
+ assert "no se pudo leer" in capsys.readouterr().err
@@ -0,0 +1,70 @@
1
+ from composeready.compose import find_compose_file, iter_services, load_compose, resolve_env
2
+
3
+
4
+ def test_resolve_env_with_default():
5
+ assert resolve_env("${FOO:-bar}", env={}) == "bar"
6
+
7
+
8
+ def test_resolve_env_from_environment():
9
+ assert resolve_env("${FOO}", env={"FOO": "baz"}) == "baz"
10
+
11
+
12
+ def test_resolve_env_bare_dollar():
13
+ assert resolve_env("$FOO/data", env={"FOO": "/srv"}) == "/srv/data"
14
+
15
+
16
+ def test_resolve_env_leaves_undefined_literal():
17
+ assert resolve_env("${UNSET_VAR}", env={}) == "${UNSET_VAR}"
18
+
19
+
20
+ def test_iter_services_skips_non_dict_entries():
21
+ data = {"services": {"web": {"image": "nginx"}, "broken": "not-a-dict"}}
22
+ assert iter_services(data) == [("web", {"image": "nginx"})]
23
+
24
+
25
+ def test_iter_services_no_services_key():
26
+ assert iter_services({}) == []
27
+
28
+
29
+ def test_find_compose_file_direct(tmp_path):
30
+ f = tmp_path / "docker-compose.yml"
31
+ f.write_text("services: {}\n")
32
+ assert find_compose_file(f) == f
33
+
34
+
35
+ def test_find_compose_file_in_directory(tmp_path):
36
+ f = tmp_path / "compose.yaml"
37
+ f.write_text("services: {}\n")
38
+ assert find_compose_file(tmp_path) == f
39
+
40
+
41
+ def test_find_compose_file_missing(tmp_path):
42
+ assert find_compose_file(tmp_path) is None
43
+
44
+
45
+ def test_load_compose_non_dict_yaml(tmp_path):
46
+ f = tmp_path / "weird.yml"
47
+ f.write_text("- just\n- a\n- list\n")
48
+ assert load_compose(f) == {}
49
+
50
+
51
+ def test_resolve_env_colon_default_with_empty_value():
52
+ assert resolve_env("${FOO:-bar}", env={"FOO": ""}) == "bar"
53
+ assert resolve_env("${FOO-bar}", env={"FOO": ""}) == ""
54
+
55
+
56
+ def test_project_env_reads_dotenv_and_environment_wins(tmp_path, monkeypatch):
57
+ from composeready.compose import project_env
58
+
59
+ (tmp_path / ".env").write_text('# c\nWEB_PORT=9000\nexport DATA="./d"\nOTRA=1 # nota\n')
60
+ monkeypatch.setenv("OTRA", "2")
61
+ env = project_env(tmp_path)
62
+ assert env["WEB_PORT"] == "9000" and env["DATA"] == "./d" and env["OTRA"] == "2"
63
+
64
+
65
+ def test_find_compose_file_mismo_orden_que_docker(tmp_path):
66
+ from composeready.compose import find_compose_file
67
+
68
+ for name in ("docker-compose.yml", "compose.yml", "compose.yaml"):
69
+ (tmp_path / name).write_text("services: {}\n")
70
+ assert find_compose_file(tmp_path).name == "compose.yaml"
@@ -0,0 +1,63 @@
1
+ from composeready.checks import gpu
2
+
3
+
4
+ def test_service_without_gpu_request_is_clean():
5
+ assert gpu.check("web", {}) == []
6
+
7
+
8
+ def test_legacy_runtime_nvidia_detected(monkeypatch):
9
+ monkeypatch.setattr(gpu.glob, "glob", lambda pattern: [])
10
+ monkeypatch.setattr(gpu.shutil, "which", lambda name: None)
11
+ findings = gpu.check("web", {"runtime": "nvidia"})
12
+ assert len(findings) == 1
13
+ assert "/dev/nvidia" in findings[0].detail
14
+
15
+
16
+ def test_modern_deploy_syntax_detected_and_host_ready(monkeypatch):
17
+ monkeypatch.setattr(gpu.glob, "glob", lambda pattern: ["/dev/nvidia0"])
18
+ monkeypatch.setattr(gpu.shutil, "which", lambda name: "/usr/bin/nvidia-smi")
19
+ service = {
20
+ "deploy": {
21
+ "resources": {
22
+ "reservations": {"devices": [{"driver": "nvidia", "count": 1}]}
23
+ }
24
+ }
25
+ }
26
+ assert gpu.check("web", service) == []
27
+
28
+
29
+ def test_modern_deploy_syntax_host_missing_gpu(monkeypatch):
30
+ monkeypatch.setattr(gpu.glob, "glob", lambda pattern: [])
31
+ monkeypatch.setattr(gpu.shutil, "which", lambda name: None)
32
+ service = {
33
+ "deploy": {
34
+ "resources": {
35
+ "reservations": {"devices": [{"capabilities": ["gpu"]}]}
36
+ }
37
+ }
38
+ }
39
+ findings = gpu.check("web", service)
40
+ assert len(findings) == 1
41
+ assert "nvidia-smi" in findings[0].detail
42
+
43
+
44
+ def test_deploy_without_gpu_capability_ignored():
45
+ service = {
46
+ "deploy": {"resources": {"reservations": {"devices": [{"driver": "something-else"}]}}}
47
+ }
48
+ assert gpu.check("web", service) == []
49
+
50
+
51
+ def test_gpus_y_cdi_detectados(monkeypatch):
52
+ monkeypatch.setattr(gpu.glob, "glob", lambda pattern: [])
53
+ monkeypatch.setattr(gpu.shutil, "which", lambda name: None)
54
+ servicios = [
55
+ {"gpus": "all"},
56
+ {"devices": ["nvidia.com/gpu=all"]},
57
+ {"devices": [{"source": "nvidia.com/gpu=0", "target": "x"}]},
58
+ {"deploy": {"resources": {"reservations": {"devices": [
59
+ {"driver": "cdi", "device_ids": ["nvidia.com/gpu=all"]}]}}}},
60
+ ]
61
+ for svc in servicios:
62
+ assert len(gpu.check("ia", svc)) == 1, svc
63
+ assert gpu.check("web", {"devices": ["/dev/ttyUSB0:/dev/ttyUSB0"]}) == []
@@ -0,0 +1,84 @@
1
+ import socket
2
+
3
+ from composeready.checks.ports import check
4
+
5
+
6
+ def _free_port() -> int:
7
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
8
+ s.bind(("0.0.0.0", 0))
9
+ port = s.getsockname()[1]
10
+ s.close()
11
+ return port
12
+
13
+
14
+ def test_flags_port_already_bound():
15
+ port = _free_port()
16
+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
17
+ holder.bind(("0.0.0.0", port))
18
+ holder.listen(1)
19
+ try:
20
+ findings = check("web", {"ports": [f"{port}:80"]})
21
+ assert len(findings) == 1
22
+ assert str(port) in findings[0].message
23
+ finally:
24
+ holder.close()
25
+
26
+
27
+ def test_does_not_flag_free_port():
28
+ port = _free_port()
29
+ findings = check("web", {"ports": [f"{port}:80"]})
30
+ assert findings == []
31
+
32
+
33
+ def test_ignores_container_only_port():
34
+ assert check("web", {"ports": [80]}) == []
35
+
36
+
37
+ def test_ignores_udp():
38
+ port = _free_port()
39
+ holder = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
40
+ holder.bind(("0.0.0.0", port))
41
+ try:
42
+ findings = check("web", {"ports": [f"{port}:80/udp"]})
43
+ assert findings == []
44
+ finally:
45
+ holder.close()
46
+
47
+
48
+ def test_ignores_port_ranges():
49
+ assert check("web", {"ports": ["8080-8090:80-90"]}) == []
50
+
51
+
52
+ def test_long_form():
53
+ port = _free_port()
54
+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
55
+ holder.bind(("0.0.0.0", port))
56
+ holder.listen(1)
57
+ try:
58
+ findings = check("web", {"ports": [{"published": port, "target": 80, "protocol": "tcp"}]})
59
+ assert len(findings) == 1
60
+ finally:
61
+ holder.close()
62
+
63
+
64
+ def test_no_ports_key():
65
+ assert check("web", {}) == []
66
+
67
+
68
+ def test_flags_port_from_variable_default_and_dotenv(tmp_path):
69
+ port = _free_port()
70
+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
71
+ holder.bind(("0.0.0.0", port))
72
+ holder.listen(1)
73
+ try:
74
+ assert len(check("web", {"ports": [f"${{WEB_PORT:-{port}}}:80"]}, env={})) == 1
75
+ assert len(check("web", {"ports": ["${WEB_PORT}:80"]}, env={"WEB_PORT": str(port)})) == 1
76
+ assert len(check("web", {"ports": [{"target": 80, "published": "${P}"}]}, env={"P": str(port)})) == 1
77
+
78
+ from composeready.cli import run
79
+
80
+ (tmp_path / ".env").write_text(f"WEB_PORT={port}\n")
81
+ (tmp_path / "compose.yml").write_text('services:\n w:\n ports: ["${WEB_PORT:-1}:80"]\n')
82
+ assert [f.check for f in run(tmp_path / "compose.yml", set())] == ["port"]
83
+ finally:
84
+ holder.close()
@@ -0,0 +1,11 @@
1
+ import pytest
2
+
3
+ from composeready import __version__
4
+ from composeready.cli import main
5
+
6
+
7
+ def test_version(capsys):
8
+ with pytest.raises(SystemExit) as exc:
9
+ main(["--version"])
10
+ assert exc.value.code == 0
11
+ assert capsys.readouterr().out.strip() == f"composeready {__version__}"