bambuddy/Dockerfile

169 lines
7.7 KiB
Text
Raw Permalink Normal View History

2025-12-09 17:06:54 +00:00
# Build frontend
2025-12-09 17:10:31 +00:00
FROM node:22-bookworm-slim AS frontend-builder
2025-12-09 17:06:54 +00:00
WORKDIR /app/frontend
2026-01-02 12:28:32 +01:00
# Copy package files first for better caching
2025-12-12 16:48:12 +01:00
COPY frontend/package*.json ./
2026-01-02 12:28:32 +01:00
# Use cache mount for npm
RUN --mount=type=cache,target=/root/.npm \
npm ci
2025-12-09 17:09:09 +00:00
2025-12-09 17:10:31 +00:00
COPY frontend/ ./
2025-12-09 17:06:54 +00:00
RUN npm run build
# Production image
FROM python:3.13-slim-trixie
2025-12-09 17:06:54 +00:00
WORKDIR /app
# Install system dependencies
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ffmpeg \
gnupg \
fix(docker): normalise data-volume ownership at startup via gosu entrypoint Two related failure modes have been biting Docker users repeatedly, most recently in #1211: 1. Docker named volumes are created by the daemon as root:root, and the previous `chmod 777 /app/data` Dockerfile workaround only covered the named-volume root — so subdirs Bambuddy creates at runtime (virtual_printer/uploads, virtual_printer/certs, etc.) inherited wrong ownership when the container ran as 1000:1000. 2. The shipped docker-compose.yml ships `./virtual_printer:/app/data/virtual_printer` uncommented, and dockerd creates a missing bind-mount source on the host as root before the container starts — leaving the host directory unwritable by uid 1000 inside the container even though the named volume above it had the chmod-777 workaround. Symptom either way: [Errno 13] Permission denied: '/app/data/virtual_printer/uploads', no virtual printer ever starts, "VP doesn't work" support reports follow. Replace the chmod-777 hack with a proper entrypoint: - deploy/docker-entrypoint.sh runs as root, chowns /app/data and /app/logs (and /app/data/virtual_printer when bind-mounted) to PUID:PGID, then drops to that uid via gosu before exec'ing the app. The chown is gated behind a top-level ownership check so subsequent restarts skip the recursive traversal — no multi- second startup penalty on multi-GB archive directories. - A sentinel .bambuddy file in each data path prevents Docker from re-syncing image directory metadata on every mount (otherwise empty volumes have their ownership reverted from the image on each restart, defeating the idempotency). - When the container is started with an explicit `user:` directive or `--user` flag the entrypoint detects it isn't root and falls through to direct exec — preserving compatibility for users who pin a specific uid. Compose template changes: - Remove `user: "${PUID:-1000}:${PGID:-1000}"` (entrypoint owns privilege drop now). - Add PUID / PGID env vars with the same defaults. - Comment out the ./virtual_printer:/app/data/virtual_printer bind mount by default, with explicit "only needed if you also run a native install of Bambuddy on the same host and want both to share the VP CA cert" guidance. The entrypoint chowns the host-side dir through the bind mount the first time it sees wrong ownership, so existing uncomented installs continue to work and #1211 specifically gets fixed.
2026-05-05 17:22:08 +02:00
gosu \
iproute2 \
libcap2-bin \
openssh-client \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Install the Tailscale CLI only (no tailscaled — the daemon runs on the host).
# Bambuddy calls `tailscale status` / `tailscale cert` via the host's socket,
# which the user mounts in via docker-compose when they want to enable the
# Tailscale integration for virtual printers. Without the socket mount, the
# binary is harmless — the code logs a hint and falls back to self-signed.
RUN curl -fsSL https://pkgs.tailscale.com/stable/debian/trixie.noarmor.gpg \
-o /usr/share/keyrings/tailscale-archive-keyring.gpg \
&& curl -fsSL https://pkgs.tailscale.com/stable/debian/trixie.tailscale-keyring.list \
-o /etc/apt/sources.list.d/tailscale.list \
&& apt-get update && apt-get install -y --no-install-recommends tailscale \
&& rm -rf /var/lib/apt/lists/*
# Allow binding to privileged ports (e.g. 990/FTPS) as non-root user.
# File capabilities are more reliable than Docker cap_add with user: directive,
# which depends on ambient capability support in the container runtime.
RUN setcap cap_net_bind_service=+ep "$(readlink -f /usr/local/bin/python3)"
# Install Python dependencies with cache mount.
# pip is upgraded to >=26.1 first to close CVE-2026-6357 — the python:3.13-slim
# base image ships pip 26.0.1, which runs its self-update check after installing
# wheels (so a hostile wheel could hijack stdlib imports during install).
2025-12-09 17:06:54 +00:00
COPY requirements.txt ./
2026-01-02 12:28:32 +01:00
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --root-user-action=ignore --upgrade 'pip>=26.1.2' \
&& pip install --root-user-action=ignore -r requirements.txt
2025-12-09 17:06:54 +00:00
# Copy backend
COPY backend/ ./backend/
# Capture the current git branch at build time. `.git/HEAD` is the only
# .git metadata the build context lets through (see .dockerignore); it
# contains `ref: refs/heads/<branch>`, which the SpoolBuddy remote-update
# flow reads at runtime via detect_current_branch() in spoolbuddy_ssh.py.
# Without this, the production image has no git metadata at all and would
# always pull `main` on the remote device regardless of which branch
# Bambuddy itself was built from.
COPY .git/HEAD ./.git/HEAD
2025-12-09 17:06:54 +00:00
# Copy built frontend from builder stage
COPY --from=frontend-builder /app/static ./static
# Copy embedded GCode viewer static assets (PrettyGCode + Bambuddy adapter).
# Served by the explicit @app.get("/gcode-viewer/{...}") routes in main.py,
# which resolve files under (static_dir.parent / "gcode_viewer") = /app/gcode_viewer/.
# Without this COPY the routes return a bare 404 at request time and the 3D
# Preview iframe shows {"detail":"Not Found"} (see #1218). The directory is
# vendored third-party JS — the Vite build does NOT stage it into static/,
# the dev server serves it via a configureServer middleware that's dev-only.
COPY gcode_viewer/ ./gcode_viewer/
fix(docker): normalise data-volume ownership at startup via gosu entrypoint Two related failure modes have been biting Docker users repeatedly, most recently in #1211: 1. Docker named volumes are created by the daemon as root:root, and the previous `chmod 777 /app/data` Dockerfile workaround only covered the named-volume root — so subdirs Bambuddy creates at runtime (virtual_printer/uploads, virtual_printer/certs, etc.) inherited wrong ownership when the container ran as 1000:1000. 2. The shipped docker-compose.yml ships `./virtual_printer:/app/data/virtual_printer` uncommented, and dockerd creates a missing bind-mount source on the host as root before the container starts — leaving the host directory unwritable by uid 1000 inside the container even though the named volume above it had the chmod-777 workaround. Symptom either way: [Errno 13] Permission denied: '/app/data/virtual_printer/uploads', no virtual printer ever starts, "VP doesn't work" support reports follow. Replace the chmod-777 hack with a proper entrypoint: - deploy/docker-entrypoint.sh runs as root, chowns /app/data and /app/logs (and /app/data/virtual_printer when bind-mounted) to PUID:PGID, then drops to that uid via gosu before exec'ing the app. The chown is gated behind a top-level ownership check so subsequent restarts skip the recursive traversal — no multi- second startup penalty on multi-GB archive directories. - A sentinel .bambuddy file in each data path prevents Docker from re-syncing image directory metadata on every mount (otherwise empty volumes have their ownership reverted from the image on each restart, defeating the idempotency). - When the container is started with an explicit `user:` directive or `--user` flag the entrypoint detects it isn't root and falls through to direct exec — preserving compatibility for users who pin a specific uid. Compose template changes: - Remove `user: "${PUID:-1000}:${PGID:-1000}"` (entrypoint owns privilege drop now). - Add PUID / PGID env vars with the same defaults. - Comment out the ./virtual_printer:/app/data/virtual_printer bind mount by default, with explicit "only needed if you also run a native install of Bambuddy on the same host and want both to share the VP CA cert" guidance. The entrypoint chowns the host-side dir through the bind mount the first time it sees wrong ownership, so existing uncomented installs continue to work and #1211 specifically gets fixed.
2026-05-05 17:22:08 +02:00
# Create data directories. Ownership is normalised at startup by the
# entrypoint (chowns to PUID:PGID and drops privileges via gosu before
# exec'ing the app), so we don't need a chmod 777 hack here — that was
# the workaround for the previous compose `user: "1000:1000"` model and
# only worked when the volume's perms happened to survive (named volume
# first-create case; bind-mount-source case bit users in #1211 / #668).
#
# The sentinel file is needed so a freshly-created Docker named volume
# isn't "empty" from Docker's POV. On empty volumes Docker resyncs the
# directory metadata (incl. ownership) from the image on every mount,
# which would mean our entrypoint chown gets reverted on every restart
# and re-fired on every start (slow on multi-GB archive dirs). With a
# sentinel inside the volume on first mount, Docker considers the
# volume populated and stops resyncing, so the chown is genuinely
# one-shot.
RUN mkdir -p /app/data /app/logs && \
: >/app/data/.bambuddy && \
: >/app/logs/.bambuddy
# Entrypoint script: handles PUID/PGID + ownership normalisation +
# privilege drop. See deploy/docker-entrypoint.sh for the full rationale.
COPY deploy/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
2025-12-09 17:06:54 +00:00
# Environment variables
ENV PYTHONUNBUFFERED=1
ENV DATA_DIR=/app/data
ENV LOG_DIR=/app/logs
ENV PORT=8000
# Provide a local username + home for tools that call getpass.getuser() /
# os.path.expanduser() under arbitrary PUIDs. With `user: "1001:1001"` the
# stock python:3.13-slim image has no /etc/passwd entry for that UID, so
# pwd.getpwuid() raises and breaks libraries that do host-level user lookups
# (notably asyncssh, which uses the local username for ~/.ssh/config host
# matching during the SpoolBuddy remote-update flow). Setting LOGNAME/USER
# makes getpass.getuser() resolve via env vars instead of the passwd db;
# HOME=/app gives a writable home that is guaranteed to exist.
ENV HOME=/app
ENV USER=bambuddy
ENV LOGNAME=bambuddy
2025-12-09 17:06:54 +00:00
# Matplotlib (imported lazily by the STL thumbnail generator) tries to create
# its font/style cache at $HOME/.config/matplotlib on first import. /app is
# root-owned and not writable by the PUID:PGID the entrypoint drops to,
# which trips an EPERM warning in everyone's logs and forces matplotlib
# to fall back to a per-restart temp dir (paying the font-scan cost on
# every container restart). Pinning the cache dir to /tmp/matplotlib
# silences the warning and keeps the cache alive for the container's
# lifetime. /tmp is writable by any uid, so this works regardless of PUID.
ENV MPLCONFIGDIR=/tmp/matplotlib
EXPOSE 322
EXPOSE 990
EXPOSE 3000
EXPOSE 3002
EXPOSE 6000
2025-12-09 17:06:54 +00:00
EXPOSE 8000
EXPOSE 8883
EXPOSE 50000-50100
2025-12-09 17:06:54 +00:00
# Health check (uses PORT env var via shell)
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
CMD python -c "import urllib.request, os; urllib.request.urlopen(f'http://localhost:{os.environ.get(\"PORT\", \"8000\")}/health')" || exit 1
2025-12-09 17:06:54 +00:00
# Run the application
2026-01-02 12:28:32 +01:00
# Use standard asyncio loop (uvloop has permission issues in some Docker environments)
# Port is configurable via PORT (default 8000); bind address via HOST (default
# 0.0.0.0). Set HOST=127.0.0.1 to bind loopback only, e.g. when a reverse proxy
# on the same host fronts the app.
fix(shutdown): exec uvicorn as PID 1 in Docker, and bound the graceful-shutdown wait Two defects, both invisible until you ask the app to stop. Docker never shut down gracefully at all. CMD ["sh","-c","uvicorn ..."] left the shell as PID 1 with uvicorn as its child, and dash does not forward signals, so docker stop SIGTERMed the shell and uvicorn never heard about it. Measured on the shipped image: the full 10s grace period, exit 137, and no "Shutting down" line in the log. Every stop, restart and image update was a hard kill -- no WAL checkpoint, no MQTT disconnect, no virtual-printer teardown. `exec` makes uvicorn PID 1; the rebuilt image now stops in 1s with exit 0 and checkpoints the WAL. Separately, uvicorn's timeout_graceful_shutdown defaults to None -- wait forever for in-flight requests. An MJPEG camera stream is a response that never completes (httptools' connection shutdown() only flips keep_alive on an in-flight cycle, it never closes the transport), so one open camera tile pinned the process until systemd SIGKILLed at 90s. The ordering makes it unfixable from inside the app: uvicorn fires the lifespan shutdown -- the code that tears the streams down -- only after connections drain. All six launchers now pass --timeout-graceful-shutdown 5: Dockerfile, deploy/bambuddy.service, the systemd unit and launchd plist from install/install.sh, the SpoolBuddy installer's unit, and the Windows NSSM registration. On timeout uvicorn cancels the request tasks; the camera generators already unwind cleanly on CancelledError. TimeoutStopSec raised to 30s on the units and stop_grace_period: 30s added to compose, as backstops rather than the mechanism. On Windows NSSM's default 1500ms AppStopMethodConsole was force-killing uvicorn mid-teardown; raised to 15s, with the WM_CLOSE and thread-message stages skipped (uvicorn is a console app with neither a window nor a message loop).
2026-07-11 14:44:45 +02:00
#
# `exec` is load-bearing, not style. Without it the shell stays as PID 1 and
# uvicorn runs as its child; dash does not forward signals, so `docker stop`
# SIGTERMs the shell and uvicorn never hears about it. Every stop then ran to
# the end of the grace period and died on SIGKILL (exit 137) — no WAL
# checkpoint, no MQTT disconnect, no virtual-printer teardown, on every restart
# and every image update. With `exec`, uvicorn *is* PID 1 and gets the signal.
#
# --timeout-graceful-shutdown caps the wait on in-flight requests. Uvicorn's
# default is to wait forever, and an MJPEG camera stream is a response that
# never completes, so a single open camera tile would otherwise pin the process
# past Docker's 10s grace and back into SIGKILL. On timeout uvicorn cancels the
# request tasks; the camera generators already unwind cleanly on CancelledError.
ENV UVICORN_TIMEOUT_GRACEFUL_SHUTDOWN=5
fix(docker): normalise data-volume ownership at startup via gosu entrypoint Two related failure modes have been biting Docker users repeatedly, most recently in #1211: 1. Docker named volumes are created by the daemon as root:root, and the previous `chmod 777 /app/data` Dockerfile workaround only covered the named-volume root — so subdirs Bambuddy creates at runtime (virtual_printer/uploads, virtual_printer/certs, etc.) inherited wrong ownership when the container ran as 1000:1000. 2. The shipped docker-compose.yml ships `./virtual_printer:/app/data/virtual_printer` uncommented, and dockerd creates a missing bind-mount source on the host as root before the container starts — leaving the host directory unwritable by uid 1000 inside the container even though the named volume above it had the chmod-777 workaround. Symptom either way: [Errno 13] Permission denied: '/app/data/virtual_printer/uploads', no virtual printer ever starts, "VP doesn't work" support reports follow. Replace the chmod-777 hack with a proper entrypoint: - deploy/docker-entrypoint.sh runs as root, chowns /app/data and /app/logs (and /app/data/virtual_printer when bind-mounted) to PUID:PGID, then drops to that uid via gosu before exec'ing the app. The chown is gated behind a top-level ownership check so subsequent restarts skip the recursive traversal — no multi- second startup penalty on multi-GB archive directories. - A sentinel .bambuddy file in each data path prevents Docker from re-syncing image directory metadata on every mount (otherwise empty volumes have their ownership reverted from the image on each restart, defeating the idempotency). - When the container is started with an explicit `user:` directive or `--user` flag the entrypoint detects it isn't root and falls through to direct exec — preserving compatibility for users who pin a specific uid. Compose template changes: - Remove `user: "${PUID:-1000}:${PGID:-1000}"` (entrypoint owns privilege drop now). - Add PUID / PGID env vars with the same defaults. - Comment out the ./virtual_printer:/app/data/virtual_printer bind mount by default, with explicit "only needed if you also run a native install of Bambuddy on the same host and want both to share the VP CA cert" guidance. The entrypoint chowns the host-side dir through the bind mount the first time it sees wrong ownership, so existing uncomented installs continue to work and #1211 specifically gets fixed.
2026-05-05 17:22:08 +02:00
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
fix(shutdown): exec uvicorn as PID 1 in Docker, and bound the graceful-shutdown wait Two defects, both invisible until you ask the app to stop. Docker never shut down gracefully at all. CMD ["sh","-c","uvicorn ..."] left the shell as PID 1 with uvicorn as its child, and dash does not forward signals, so docker stop SIGTERMed the shell and uvicorn never heard about it. Measured on the shipped image: the full 10s grace period, exit 137, and no "Shutting down" line in the log. Every stop, restart and image update was a hard kill -- no WAL checkpoint, no MQTT disconnect, no virtual-printer teardown. `exec` makes uvicorn PID 1; the rebuilt image now stops in 1s with exit 0 and checkpoints the WAL. Separately, uvicorn's timeout_graceful_shutdown defaults to None -- wait forever for in-flight requests. An MJPEG camera stream is a response that never completes (httptools' connection shutdown() only flips keep_alive on an in-flight cycle, it never closes the transport), so one open camera tile pinned the process until systemd SIGKILLed at 90s. The ordering makes it unfixable from inside the app: uvicorn fires the lifespan shutdown -- the code that tears the streams down -- only after connections drain. All six launchers now pass --timeout-graceful-shutdown 5: Dockerfile, deploy/bambuddy.service, the systemd unit and launchd plist from install/install.sh, the SpoolBuddy installer's unit, and the Windows NSSM registration. On timeout uvicorn cancels the request tasks; the camera generators already unwind cleanly on CancelledError. TimeoutStopSec raised to 30s on the units and stop_grace_period: 30s added to compose, as backstops rather than the mechanism. On Windows NSSM's default 1500ms AppStopMethodConsole was force-killing uvicorn mid-teardown; raised to 15s, with the WM_CLOSE and thread-message stages skipped (uvicorn is a console app with neither a window nor a message loop).
2026-07-11 14:44:45 +02:00
CMD ["sh", "-c", "exec uvicorn backend.app.main:app --host ${HOST:-0.0.0.0} --port ${PORT:-8000} --loop asyncio --timeout-graceful-shutdown ${UVICORN_TIMEOUT_GRACEFUL_SHUTDOWN}"]