Add web-frontend, web-project-audit and web-project-scaffold-containerized-python skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
59fc08fa5f
commit
5201aa9bd5
63 changed files with 3042 additions and 0 deletions
|
|
@ -0,0 +1,35 @@
|
|||
# The image is the runtime only: Python, git and the scripts in this folder. The app's
|
||||
# source is cloned into the /srv volume on first start and updated in place by `update`,
|
||||
# so a rebuild is needed only when this folder or the Python version changes.
|
||||
ARG PYTHON_VERSION=__PYTHON__
|
||||
FROM python:${PYTHON_VERSION}-slim
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git openssh-client tini \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG UID=1000
|
||||
ARG GID=1000
|
||||
RUN groupadd --gid "$GID" app \
|
||||
&& useradd --uid "$UID" --gid app --create-home --shell /usr/sbin/nologin app \
|
||||
&& mkdir -p /srv/src /srv/venv /srv/state /data \
|
||||
&& chown -R app:app /srv /data \
|
||||
&& git config --system --add safe.directory '*'
|
||||
|
||||
COPY container/lib.sh /usr/local/lib/app/lib.sh
|
||||
COPY --chmod=755 container/entrypoint.sh /usr/local/bin/entrypoint
|
||||
COPY --chmod=755 container/update.sh /usr/local/bin/update
|
||||
|
||||
ENV PATH=/srv/venv/bin:$PATH \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
DATA_DIR=/data \
|
||||
PORT=8000
|
||||
|
||||
USER app
|
||||
WORKDIR /srv/src
|
||||
EXPOSE 8000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD python3 -c "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ[\"PORT\"]}/healthz', timeout=3)"
|
||||
ENTRYPOINT ["tini", "--", "entrypoint"]
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
#!/usr/bin/env bash
|
||||
# Container entrypoint (runs under tini). Gets the source and venv ready, then supervises
|
||||
# uvicorn: SIGHUP restarts the app on the current checkout (that's how `update` swaps code
|
||||
# in without restarting the container); SIGTERM stops it. If the app dies on its own, the
|
||||
# container exits and Docker's restart policy takes over.
|
||||
#
|
||||
# With arguments, it runs them in the source dir after setup instead, e.g.
|
||||
# docker compose run --rm app pytest
|
||||
set -uo pipefail
|
||||
. /usr/local/lib/app/lib.sh
|
||||
|
||||
load_env
|
||||
ensure_source || exit 1
|
||||
sync_deps || die "installing requirements failed"
|
||||
cd "$SRC"
|
||||
|
||||
if [ $# -gt 0 ]; then
|
||||
export PATH="$VENV/bin:$PATH"
|
||||
exec "$@"
|
||||
fi
|
||||
|
||||
child=
|
||||
stopping=0
|
||||
restart=0
|
||||
trap 'stopping=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' TERM INT
|
||||
trap 'restart=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' HUP
|
||||
echo $$ > "$PIDFILE"
|
||||
|
||||
start_app() {
|
||||
local args=(app.main:app --host 0.0.0.0 --port "$PORT"
|
||||
--proxy-headers --forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}"
|
||||
--no-server-header --timeout-graceful-shutdown 10)
|
||||
[ "${DEV:-}" = 1 ] && args+=(--reload)
|
||||
export APP_VERSION
|
||||
APP_VERSION=$(current_version)
|
||||
log "starting app at $APP_VERSION"
|
||||
env "${APP_ENV_UNSET[@]}" "$VENV/bin/uvicorn" "${args[@]}" &
|
||||
child=$!
|
||||
}
|
||||
|
||||
while :; do
|
||||
start_app
|
||||
wait "$child"; rc=$?
|
||||
# A trapped signal interrupts `wait` while the child is still shutting down.
|
||||
while kill -0 "$child" 2>/dev/null; do wait "$child"; rc=$?; done
|
||||
[ "$stopping" = 1 ] && exit 0
|
||||
if [ "$restart" = 1 ]; then restart=0; continue; fi
|
||||
log "app exited with status $rc"
|
||||
# New code that crashes at startup must not take the container down mid-update, or
|
||||
# `update` dies with it and can't roll back. Wait for its restart signal instead.
|
||||
if ! flock -n /tmp/app-update.lock true; then
|
||||
log "an update is running; waiting for it to restart the app"
|
||||
while [ "$restart" = 0 ] && [ "$stopping" = 0 ]; do sleep 1 & wait $!; done
|
||||
[ "$stopping" = 1 ] && exit 0
|
||||
restart=0; continue
|
||||
fi
|
||||
exit "$rc"
|
||||
done
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
# Shared by entrypoint and update. Installed at /usr/local/lib/app/lib.sh.
|
||||
# Config: the project .env, mounted at /run/config/app.env, read by load_env.
|
||||
# Layout inside the container:
|
||||
# /srv/src git checkout of the app (cloned from REPO_URL on first start, or bind-mounted in dev)
|
||||
# /srv/venv virtualenv built from requirements.txt (rebuilt when requirements or Python change)
|
||||
# /srv/state update bookkeeping (previous commit, ssh known_hosts)
|
||||
# /data the app's own persistent data
|
||||
# /srv is one named volume, so source, venv and state survive container recreation.
|
||||
|
||||
SRC=${SRC:-/srv/src}
|
||||
VENV=${VENV:-/srv/venv}
|
||||
STATE=${STATE:-/srv/state}
|
||||
PORT=${PORT:-8000}
|
||||
PIDFILE=/tmp/app-supervisor.pid
|
||||
ENV_FILE=${ENV_FILE:-/run/config/app.env}
|
||||
|
||||
log() { echo "[$(basename "$0")] $*" >&2; }
|
||||
die() { log "error: $*"; exit 1; }
|
||||
|
||||
# Read the project's .env (bind-mounted read-only at $ENV_FILE). It runs on every start
|
||||
# and every update, so a new URL or rotated token takes effect without a rebuild.
|
||||
# Plain KEY=value lines only; it is parsed, not executed. Values never get printed.
|
||||
load_env() {
|
||||
[ -e "$ENV_FILE" ] || return 0
|
||||
[ -f "$ENV_FILE" ] || die "$ENV_FILE is not a file (create .env before 'docker compose up'; Docker made a directory in its place)"
|
||||
[ -r "$ENV_FILE" ] || die "$ENV_FILE is not readable by uid $(id -u): chown $(id -u) .env && chmod 600 .env on the host"
|
||||
local line key val
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
line=${line%$'\r'}
|
||||
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
||||
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
|
||||
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
||||
export "$key=$val"
|
||||
done < "$ENV_FILE"
|
||||
setup_git_auth
|
||||
}
|
||||
|
||||
# Credentials for REPO_URL, from the environment only. Nothing is written into the checkout:
|
||||
# https: GIT_TOKEN (+ GIT_USERNAME, default x-access-token) answered by a credential helper
|
||||
# ssh: GIT_SSH_KEY, the private key base64-encoded (base64 -w0 deploy_key)
|
||||
setup_git_auth() {
|
||||
if [ -n "${GIT_TOKEN:-}" ]; then
|
||||
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
||||
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
||||
fi
|
||||
local ssh="ssh -o UserKnownHostsFile=$STATE/known_hosts -o StrictHostKeyChecking=accept-new"
|
||||
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
||||
local key=/tmp/git-deploy-key
|
||||
(umask 077; printf '%s' "$GIT_SSH_KEY" | base64 -d > "$key") || die "GIT_SSH_KEY is not valid base64"
|
||||
ssh="$ssh -i $key -o IdentitiesOnly=yes"
|
||||
fi
|
||||
export GIT_SSH_COMMAND="$ssh" GIT_TERMINAL_PROMPT=0
|
||||
}
|
||||
|
||||
# Hide user:password@ if someone put credentials in the URL anyway.
|
||||
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
||||
|
||||
# The app gets the .env settings but not the repo credentials.
|
||||
APP_ENV_UNSET=(-u GIT_TOKEN -u GIT_USERNAME -u GIT_SSH_KEY -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0)
|
||||
|
||||
# Clone the source on first start. A bind-mounted checkout (dev) already has .git.
|
||||
ensure_source() {
|
||||
mkdir -p "$STATE"
|
||||
[ -d "$SRC/.git" ] && return 0
|
||||
[ -n "${REPO_URL:-}" ] || die "no source at $SRC and REPO_URL is not set in .env"
|
||||
log "cloning $(redact "$REPO_URL") (${REPO_REF:-main}) into $SRC"
|
||||
# $SRC may exist as an empty dir; clone into it.
|
||||
git clone --quiet --branch "${REPO_REF:-main}" "$REPO_URL" "$SRC"
|
||||
}
|
||||
|
||||
# Follow REPO_URL if .env changed it. Credentials are never part of the stored URL.
|
||||
sync_remote() {
|
||||
[ -n "${REPO_URL:-}" ] || return 0
|
||||
[ "$(git -C "$SRC" remote get-url origin 2>/dev/null)" = "$REPO_URL" ] || git -C "$SRC" remote set-url origin "$REPO_URL"
|
||||
}
|
||||
|
||||
requirement_files() {
|
||||
echo "$SRC/requirements.txt"
|
||||
if [ "${DEV:-}" = 1 ] && [ -f "$SRC/requirements-dev.txt" ]; then echo "$SRC/requirements-dev.txt"; fi
|
||||
}
|
||||
|
||||
# Bring the venv in line with the checkout. A no-op when nothing changed.
|
||||
sync_deps() {
|
||||
local py want files
|
||||
py=$(python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])')
|
||||
mapfile -t files < <(requirement_files)
|
||||
want="$py $(cat "${files[@]}" | sha256sum | cut -d' ' -f1)"
|
||||
if [ "$(cat "$VENV/.python" 2>/dev/null)" != "$py" ]; then
|
||||
log "creating venv for Python $py"
|
||||
rm -rf "$VENV"
|
||||
python3 -m venv "$VENV"
|
||||
echo "$py" > "$VENV/.python"
|
||||
fi
|
||||
[ "$(cat "$VENV/.synced" 2>/dev/null)" = "$want" ] && return 0
|
||||
log "installing requirements"
|
||||
local args=()
|
||||
for f in "${files[@]}"; do args+=(-r "$f"); done
|
||||
"$VENV/bin/pip" install --quiet --disable-pip-version-check --no-cache-dir "${args[@]}" || return 1
|
||||
echo "$want" > "$VENV/.synced"
|
||||
}
|
||||
|
||||
# The new code must at least import before it replaces the running app.
|
||||
check_import() {
|
||||
(cd "$SRC" && "$VENV/bin/python" -c 'import app.main') || return 1
|
||||
}
|
||||
|
||||
current_version() { git -C "$SRC" rev-parse --short HEAD 2>/dev/null || echo dev; }
|
||||
|
||||
# Wait until /healthz answers with the expected version (or any version if none given).
|
||||
wait_healthy() {
|
||||
local want=${1:-} timeout=${HEALTH_TIMEOUT:-30} got
|
||||
for _ in $(seq 1 "$timeout"); do
|
||||
got=$(python3 - "$PORT" <<'PY' 2>/dev/null
|
||||
import json, sys, urllib.request
|
||||
r = urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/healthz", timeout=2)
|
||||
print(json.load(r).get("version", ""))
|
||||
PY
|
||||
) && { [ -z "$want" ] || [ "$got" = "$want" ]; } && return 0
|
||||
sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
#!/usr/bin/env bash
|
||||
# Pull the latest source from the remote repo in .env (REPO_URL, REPO_REF and credentials)
|
||||
# into the running container and restart the app on it. No rebuild.
|
||||
# docker exec <container> update # to the tip of REPO_REF
|
||||
# docker exec <container> update <ref> # to a tag, branch or commit
|
||||
# docker exec <container> update --check # show what an update would bring in
|
||||
# docker exec <container> update --rollback # back to the commit before the last update
|
||||
# Steps: fetch, check out, sync requirements, import check, restart, wait for /healthz to
|
||||
# report the new commit. If any step fails, it puts the previous commit back and exits 1.
|
||||
set -euo pipefail
|
||||
. /usr/local/lib/app/lib.sh
|
||||
|
||||
usage() { sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
|
||||
|
||||
mode=update force=0 ref=
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--check) mode=check ;;
|
||||
--rollback) mode=rollback ;;
|
||||
--force) force=1 ;;
|
||||
-h|--help) usage ;;
|
||||
-*) usage 1 ;;
|
||||
*) ref=$1 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
load_env
|
||||
[ "${DEV:-}" = 1 ] && die "dev mode: the source is bind-mounted from the host; update it with git there"
|
||||
[ -d "$SRC/.git" ] || die "no checkout at $SRC"
|
||||
exec 9>/tmp/app-update.lock
|
||||
flock -n 9 || die "another update is running"
|
||||
cd "$SRC"
|
||||
|
||||
old=$(git rev-parse HEAD)
|
||||
if [ "$mode" = rollback ]; then
|
||||
new=$(cat "$STATE/previous" 2>/dev/null) || die "no previous commit recorded"
|
||||
else
|
||||
sync_remote
|
||||
git fetch --quiet --prune --tags origin
|
||||
target=${ref:-${REPO_REF:-main}}
|
||||
# A branch resolves on the remote; a tag or commit as given.
|
||||
new=$(git rev-parse --verify --quiet "origin/$target^{commit}" || git rev-parse --verify --quiet "$target^{commit}") \
|
||||
|| die "unknown ref: $target"
|
||||
fi
|
||||
short() { git rev-parse --short "$1"; }
|
||||
|
||||
if [ "$mode" = check ]; then
|
||||
if [ "$old" = "$new" ]; then echo "up to date at $(short "$old")"; else
|
||||
echo "$(short "$old") -> $(short "$new")"
|
||||
git log --oneline "$old..$new" 2>/dev/null || true
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
[ "$old" = "$new" ] && { echo "already at $(short "$new")"; exit 0; }
|
||||
|
||||
if [ "$force" = 0 ] && [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
||||
die "the checkout has local changes (inspect with: docker exec ${CONTAINER_NAME:-<container>} git -C $SRC status); --force discards them"
|
||||
fi
|
||||
|
||||
restart_app() { kill -HUP "$(cat "$PIDFILE")" || return 1; sleep 1; }
|
||||
apply() { git reset --quiet --hard "$1" && sync_deps && check_import; }
|
||||
|
||||
restarted=0
|
||||
log "updating $(short "$old") -> $(short "$new")"
|
||||
if apply "$new" && restarted=1 && restart_app && wait_healthy "$(short "$new")"; then
|
||||
echo "$old" > "$STATE/previous"
|
||||
git log --oneline "$old..$new" 2>/dev/null | head -20 || true
|
||||
if [ -n "$(git diff --name-only "$old" "$new" -- container/)" ]; then
|
||||
log "note: container/ changed; rebuild the image to pick that up (docker compose up -d --build)"
|
||||
fi
|
||||
echo "updated to $(short "$new")"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "update failed; going back to $(short "$old")"
|
||||
apply "$old" || die "could not restore $(short "$old"): the app may be down, check: docker logs ${CONTAINER_NAME:-<container>}"
|
||||
[ "$restarted" = 1 ] || { log "the running app was never touched"; exit 1; }
|
||||
restart_app && wait_healthy "$(short "$old")" || die "restored $(short "$old") but it is not healthy; check: docker logs ${CONTAINER_NAME:-<container>}"
|
||||
log "running $(short "$old") again"
|
||||
exit 1
|
||||
Loading…
Add table
Add a link
Reference in a new issue