decomposer: generate files for Create a production-suitable Dockerfile and minimal Docker Compose configuration for packaging and running the completed FastAPI endpoint monitoring service.
This commit is contained in:
82
src/containerizer/render.py
Normal file
82
src/containerizer/render.py
Normal file
@@ -0,0 +1,82 @@
|
||||
import re
|
||||
|
||||
MODULE_RE = re.compile(r"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*$")
|
||||
PIN_RE = re.compile(r"^[A-Za-z0-9_.-]+(?:\[[A-Za-z0-9_,.-]+\])?==[^\s;]+$")
|
||||
|
||||
|
||||
def validate_module(value: str) -> tuple[str, str]:
|
||||
if not MODULE_RE.fullmatch(value):
|
||||
raise ValueError("startup_module must look like package.module:attribute")
|
||||
return tuple(value.split(":", 1))
|
||||
|
||||
|
||||
def dockerfile(module: str, port: int) -> str:
|
||||
return f'''# syntax=docker/dockerfile:1.7
|
||||
FROM python:3.12.8-slim-bookworm
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \\
|
||||
PYTHONUNBUFFERED=1 \\
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
WORKDIR /app
|
||||
|
||||
RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home app
|
||||
COPY --chown=app:app requirements.lock ./requirements.lock
|
||||
RUN python -m pip install --no-cache-dir --no-deps -r requirements.lock
|
||||
COPY --chown=app:app . .
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE {port}
|
||||
CMD ["python", "-m", "uvicorn", "{module}", "--host", "0.0.0.0", "--port", "{port}", "--proxy-headers"]
|
||||
'''
|
||||
|
||||
|
||||
def compose(port: int, health_path: str | None) -> str:
|
||||
health = ""
|
||||
if health_path:
|
||||
probe = (
|
||||
"import urllib.request; "
|
||||
f"urllib.request.urlopen('http://127.0.0.1:{port}{health_path}', timeout=3)"
|
||||
)
|
||||
health = f''' healthcheck:
|
||||
test: ["CMD", "python", "-c", "{probe}"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
'''
|
||||
return f'''services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
init: true
|
||||
ports:
|
||||
- "${{PORT:-{port}}}:{port}"
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
{health}'''
|
||||
|
||||
|
||||
def dockerignore() -> str:
|
||||
return '''.git
|
||||
.github
|
||||
.venv
|
||||
venv
|
||||
__pycache__
|
||||
*.py[cod]
|
||||
.pytest_cache
|
||||
.mypy_cache
|
||||
.ruff_cache
|
||||
.coverage
|
||||
htmlcov
|
||||
.env
|
||||
.env.*
|
||||
tests
|
||||
Dockerfile*
|
||||
compose*.yaml
|
||||
README*
|
||||
'''
|
||||
Reference in New Issue
Block a user