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,3 @@
|
|||
# The image is built from container/ only; the source reaches the container through git.
|
||||
*
|
||||
!container/
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
# install.sh writes .env from this file on the server (see README).
|
||||
# Gitignored. The container reads it at startup and on every `update`, so edits apply on the
|
||||
# next update or restart; no rebuild. Plain KEY=value lines; quotes optional; not executed.
|
||||
|
||||
# The remote the container pulls the source from, and the branch/tag it follows.
|
||||
REPO_URL=__REPO_URL__
|
||||
REPO_REF=__BRANCH__
|
||||
|
||||
# Private repo over https: a read-only access token (GitHub fine-grained token with
|
||||
# Contents: read, GitLab deploy token, ...). Leave empty for a public repo.
|
||||
GIT_USERNAME=
|
||||
GIT_TOKEN=
|
||||
|
||||
# Or private repo over SSH: an ssh REPO_URL (git@host:owner/repo.git) and a read-only deploy
|
||||
# key, base64-encoded on one line: base64 -w0 deploy_key
|
||||
GIT_SSH_KEY=
|
||||
|
||||
# Host port on 127.0.0.1 (used by compose, not the app).
|
||||
HOST_PORT=__PORT__
|
||||
|
||||
# App settings go below; the app sees them as environment variables.
|
||||
6
skills/web-project-scaffold-containerized-python/templates/project/.gitignore
vendored
Normal file
6
skills/web-project-scaffold-containerized-python/templates/project/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
.env
|
||||
deploy_key*
|
||||
__pycache__/
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
data/
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
# __TITLE__
|
||||
|
||||
A FastAPI backend serving a plain HTML/CSS/JS frontend, in one container. Nothing is compiled: no bundler, no TypeScript, no Sass. The image holds only the runtime. The source lives in a git checkout inside a volume, so a deploy is one command and needs no image rebuild.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
app/main.py FastAPI app: /healthz, /api, static files, index page
|
||||
app/api.py JSON API routes (under /api)
|
||||
app/static/ the frontend, served as is (vendor libraries into static/vendor/)
|
||||
tests/ pytest
|
||||
container/ Dockerfile, entrypoint (setup + supervisor), update script
|
||||
compose.yml production
|
||||
compose.dev.yml development overlay (bind-mounted source, auto reload)
|
||||
requirements.txt runtime dependencies (pinned); requirements-dev.txt for tests
|
||||
```
|
||||
|
||||
## Develop
|
||||
|
||||
The host needs only Docker and git.
|
||||
|
||||
```bash
|
||||
docker compose -f compose.yml -f compose.dev.yml up --build # http://127.0.0.1:__PORT__
|
||||
docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
|
||||
```
|
||||
|
||||
Python changes reload on save; frontend changes show on the next page load.
|
||||
|
||||
## Install on a server
|
||||
|
||||
On a fresh Linux server (Debian, Ubuntu, Fedora, RHEL and others), paste one line:
|
||||
|
||||
```bash
|
||||
# public repo
|
||||
curl -fsSL __INSTALL_URL__ | bash
|
||||
|
||||
# private repo: asks for a read-only token without echoing it
|
||||
read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash
|
||||
```
|
||||
|
||||
`install.sh` does the whole setup:
|
||||
- installs git and Docker (Engine and Compose) if they're missing
|
||||
- checks it can read `__REPO_URL__`
|
||||
- clones it into `/opt/__NAME__`
|
||||
- writes `/opt/__NAME__/.env` (the repo URL, branch, credentials and port that `update` uses)
|
||||
- builds the image, starts the container and waits until it is healthy
|
||||
|
||||
Settings such as `INSTALL_DIR`, `REPO_REF`, `HOST_PORT`, `GIT_TOKEN` and `GIT_SSH_KEY` can be passed as environment variables; the top of `install.sh` lists them. For an SSH-only private repo, copy `install.sh` to the server and run `GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh`.
|
||||
|
||||
Re-running the installer is safe. It keeps `.env`, replacing only the keys you pass, then updates the checkout, rebuilds and restarts. Re-run it whenever `container/` changes, or to rotate a credential.
|
||||
|
||||
After that, every deploy is:
|
||||
|
||||
```bash
|
||||
git push # from your machine
|
||||
docker exec __NAME__ update # on the server
|
||||
```
|
||||
|
||||
`update` fetches, checks out the new commit, installs the requirements if they changed, checks that `app.main` imports, restarts the app process and waits until `/healthz` reports the new commit. If any step fails it goes back to the previous commit and exits non-zero. Other forms:
|
||||
|
||||
```bash
|
||||
docker exec __NAME__ update --check # what an update would bring in
|
||||
docker exec __NAME__ update v1.4.0 # a tag, branch or commit
|
||||
docker exec __NAME__ update --rollback # back to the commit before the last update
|
||||
```
|
||||
|
||||
The app restarts in place, so there is a second or two of downtime while it restarts. The container itself keeps running.
|
||||
|
||||
A rebuild is needed only when `container/` or the Python version changes. For that, re-run the install command, or run `docker compose up -d --build` in `/opt/__NAME__`. `update` prints a reminder when an update touches `container/`.
|
||||
|
||||
## The `.env` file
|
||||
|
||||
`.env` is gitignored and stays on the machine. It is mounted read-only into the container, which reads it at startup and again on every `update`. So a changed URL, branch or rotated token takes effect on the next update, with no rebuild or recreate.
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `REPO_URL` | The remote the container pulls from (https or SSH). Keep credentials out of the URL. |
|
||||
| `REPO_REF` | The branch (or tag) that `update` follows. |
|
||||
| `GIT_TOKEN`, `GIT_USERNAME` | Private repo over https: a read-only token. A git credential helper supplies it, so it is never written into the checkout. |
|
||||
| `GIT_SSH_KEY` | Private repo over SSH: a read-only deploy key, base64-encoded on one line (`base64 -w0 deploy_key`). |
|
||||
| anything else | App settings. The app sees them as environment variables; it never sees the git credentials. |
|
||||
|
||||
`install.sh` writes `.env` owned by uid 1000 (the container's user) with mode 640. If you set up by hand, do the same, and create `.env` before the first `docker compose up`: if it is missing, Docker creates an empty directory in its place, and the container stops with an error saying so.
|
||||
|
||||
## Data and config
|
||||
|
||||
- Persistent app data goes under `$DATA_DIR` (`/data`, the `data` volume). Back up that volume.
|
||||
- Configuration and secrets live in `.env`, never in the repo.
|
||||
- Do startup work (creating tables, migrations) in `lifespan` in `app/main.py`, and make it idempotent. Don't do it at import time: `update` imports the app as a check before it restarts it.
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
"""JSON API, mounted under /api. Split into a package (app/api/<area>.py) as it grows."""
|
||||
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/info")
|
||||
def info() -> dict:
|
||||
return {"name": "__TITLE__", "version": os.environ.get("APP_VERSION", "dev")}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
"""__TITLE__: FastAPI backend serving a no-build static frontend from app/static."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app import api
|
||||
|
||||
VERSION = os.environ.get("APP_VERSION", "dev")
|
||||
STATIC = Path(__file__).parent / "static"
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
# Startup work goes here, not at import time: `update` imports this module as a check
|
||||
# before restarting. Create tables or run migrations idempotently here.
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="__TITLE__", version=VERSION, lifespan=lifespan, docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json")
|
||||
app.include_router(api.router, prefix="/api")
|
||||
|
||||
|
||||
@app.get("/healthz", include_in_schema=False)
|
||||
def healthz() -> dict:
|
||||
# `update` waits for this to report the new commit before it calls the update done.
|
||||
return {"status": "ok", "version": VERSION}
|
||||
|
||||
|
||||
class Assets(StaticFiles):
|
||||
"""Browsers revalidate on every load (cheap 304s), so an update shows up at once."""
|
||||
|
||||
async def get_response(self, path, scope):
|
||||
response = await super().get_response(path, scope)
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
app.mount("/static", Assets(directory=STATIC), name="static")
|
||||
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
def index() -> FileResponse:
|
||||
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
/* App styles on top of tokens.css. Plain CSS, no preprocessor. */
|
||||
.wrap { max-width: var(--content-max); margin-inline: auto; padding-inline: var(--gutter); }
|
||||
|
||||
.topbar { border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.topbar-inner { display: flex; align-items: center; justify-content: space-between; gap: var(--space-4); height: 3.5rem; }
|
||||
.brand { font-weight: var(--weight-semibold); color: var(--fg); text-decoration: none; }
|
||||
|
||||
main.wrap { display: grid; gap: var(--space-6); padding-block: var(--space-12); }
|
||||
.lead { font-size: var(--text-lg); color: var(--fg-muted); max-width: var(--measure); margin: 0; }
|
||||
h1 { margin: 0; text-wrap: balance; }
|
||||
|
||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-md); padding: var(--space-5); max-width: 32rem; }
|
||||
.card h2 { margin: 0 0 var(--space-2); }
|
||||
.card p { margin: 0; }
|
||||
|
||||
.badge { display: inline-flex; align-items: center; height: 1.375rem; padding-inline: var(--space-2);
|
||||
font: var(--weight-medium) var(--text-xs) / 1 var(--font-mono); border-radius: var(--radius-full);
|
||||
background: var(--surface-2); color: var(--fg-muted); }
|
||||
.ok { color: var(--ok); }
|
||||
.error { color: var(--danger); }
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>__TITLE__</title>
|
||||
<link rel="stylesheet" href="/static/css/tokens.css">
|
||||
<link rel="stylesheet" href="/static/css/app.css">
|
||||
<script type="module" src="/static/js/main.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="wrap topbar-inner">
|
||||
<a class="brand" href="/">__TITLE__</a>
|
||||
<span class="badge" id="version" title="Running commit">…</span>
|
||||
</div>
|
||||
</header>
|
||||
<main class="wrap">
|
||||
<h1>__TITLE__</h1>
|
||||
<p class="lead">FastAPI serves this page and the JSON API under <code>/api</code>. Edit <code>app/static</code> and reload; there is no build step.</p>
|
||||
<section class="card" aria-labelledby="status-heading">
|
||||
<h2 id="status-heading" class="label">Server</h2>
|
||||
<p id="status" aria-live="polite">Checking…</p>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
// Small fetch wrapper: JSON in, JSON out, errors carry the server's message.
|
||||
export async function getJSON(path, options = {}) {
|
||||
const response = await fetch(path, { headers: { Accept: "application/json" }, ...options });
|
||||
if (!response.ok) {
|
||||
let detail = response.statusText;
|
||||
try { detail = (await response.json()).detail ?? detail; } catch {}
|
||||
throw new Error(`${response.status} ${detail}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function postJSON(path, body) {
|
||||
return getJSON(path, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body) });
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
// Plain ES modules, no bundler. Vendor any library into /static/vendor and import it by path.
|
||||
import { getJSON } from "./api.js";
|
||||
|
||||
const status = document.getElementById("status");
|
||||
const version = document.getElementById("version");
|
||||
|
||||
try {
|
||||
const info = await getJSON("/api/info");
|
||||
version.textContent = info.version;
|
||||
status.textContent = `Running ${info.name} at commit ${info.version}.`;
|
||||
status.className = "ok";
|
||||
} catch (err) {
|
||||
status.textContent = `Could not reach the API: ${err.message}`;
|
||||
status.className = "error";
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
# Local development: the source is this folder, bind-mounted, and uvicorn reloads on save.
|
||||
# docker compose -f compose.yml -f compose.dev.yml up --build
|
||||
# docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
|
||||
# `update` is disabled in dev; use git on the host. Separate project name = separate volumes.
|
||||
name: __NAME__-dev
|
||||
services:
|
||||
app:
|
||||
container_name: __NAME__-dev
|
||||
environment:
|
||||
DEV: "1"
|
||||
CONTAINER_NAME: __NAME__-dev
|
||||
volumes:
|
||||
- .:/srv/src
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
# Production. install.sh sets this up on a server (see README); by hand it is:
|
||||
# clone into /opt/__NAME__, write .env from .env.example, docker compose up -d --build
|
||||
# Deploys after that: docker exec __NAME__ update
|
||||
name: __NAME__
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: container/Dockerfile
|
||||
image: __NAME__:latest
|
||||
container_name: __NAME__
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CONTAINER_NAME: __NAME__
|
||||
# Only a reverse proxy at these addresses may set X-Forwarded-For.
|
||||
FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-127.0.0.1}
|
||||
# Loopback only: put a reverse proxy or tunnel in front of it.
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-__PORT__}:8000"
|
||||
volumes:
|
||||
- runtime:/srv # source checkout, venv, update state
|
||||
- data:/data # the app's persistent data
|
||||
# Repo URL, credentials and app settings, read on every start and every update.
|
||||
# Not env_file: a mounted file can change without recreating the container.
|
||||
- ./.env:/run/config/app.env:ro
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
cap_drop: [ALL]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 256m
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
volumes:
|
||||
runtime:
|
||||
data:
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
#!/usr/bin/env bash
|
||||
# Install (or upgrade) __TITLE__ on a Linux server. Paste one line into a fresh server:
|
||||
#
|
||||
# Public repo:
|
||||
# curl -fsSL __INSTALL_URL__ | bash
|
||||
#
|
||||
# Private repo over https (the token is asked for, not typed into history):
|
||||
# read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash
|
||||
#
|
||||
# Private repo over SSH: copy this file to the server, then
|
||||
# GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh
|
||||
#
|
||||
# What it does: installs git and Docker (Engine + Compose) if missing, clones the repo into
|
||||
# $INSTALL_DIR, writes $INSTALL_DIR/.env (repo URL, branch, credentials, port) for the
|
||||
# container's `update`, builds the image, starts the container and waits until it is
|
||||
# healthy. Re-running it is safe: it keeps .env (values you pass replace those keys),
|
||||
# pulls the checkout, rebuilds the image and restarts. Run it again whenever container/
|
||||
# changes; for ordinary deploys use `docker exec __NAME__ update`.
|
||||
#
|
||||
# Settings (environment variables, all optional):
|
||||
# INSTALL_DIR default /opt/__NAME__
|
||||
# REPO_URL default __REPO_URL__
|
||||
# REPO_REF default __BRANCH__
|
||||
# GIT_TOKEN, GIT_USERNAME private repo over https
|
||||
# GIT_SSH_KEY private repo over SSH (base64-encoded deploy key)
|
||||
# HOST_PORT default __PORT__ (bound to 127.0.0.1)
|
||||
#
|
||||
# Everything is inside main(), so a partial download runs nothing.
|
||||
|
||||
main() {
|
||||
set -euo pipefail
|
||||
local NAME=__NAME__
|
||||
INSTALL_DIR=${INSTALL_DIR:-/opt/$NAME}
|
||||
local DEFAULT_REPO_URL="__REPO_URL__" DEFAULT_REF="__BRANCH__" DEFAULT_PORT="__PORT__"
|
||||
# Which keys the caller passed explicitly (these replace values in an existing .env).
|
||||
local passed=()
|
||||
for k in REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT; do
|
||||
[ -n "${!k:-}" ] && passed+=("$k")
|
||||
done
|
||||
|
||||
[ "$(uname -s)" = Linux ] || die "this installer is for Linux servers"
|
||||
SUDO=
|
||||
if [ "$(id -u)" != 0 ]; then
|
||||
command -v sudo >/dev/null || die "run as root, or install sudo"
|
||||
SUDO=sudo
|
||||
fi
|
||||
|
||||
step "prerequisites"
|
||||
install_packages
|
||||
install_docker
|
||||
|
||||
step "source"
|
||||
load_existing_env
|
||||
REPO_URL=${REPO_URL:-$DEFAULT_REPO_URL}
|
||||
REPO_REF=${REPO_REF:-$DEFAULT_REF}
|
||||
HOST_PORT=${HOST_PORT:-$DEFAULT_PORT}
|
||||
git_auth
|
||||
check_access
|
||||
checkout
|
||||
|
||||
step "configuration"
|
||||
write_env
|
||||
|
||||
step "container"
|
||||
(cd "$INSTALL_DIR" && $DOCKER compose up -d --build --remove-orphans)
|
||||
wait_healthy
|
||||
|
||||
step "done"
|
||||
cat <<EOF
|
||||
$NAME is running at $(health_version) on http://127.0.0.1:$HOST_PORT (loopback; put a reverse proxy or tunnel in front).
|
||||
deploy a new commit: docker exec $NAME update
|
||||
see what's new: docker exec $NAME update --check
|
||||
undo the last update: docker exec $NAME update --rollback
|
||||
logs: docker logs -f $NAME
|
||||
settings: $INSTALL_DIR/.env (re-read on every update)
|
||||
rebuild/upgrade: run this installer again
|
||||
EOF
|
||||
[ "$DOCKER" = docker ] || echo " (prefix docker with sudo, or add yourself to the docker group)"
|
||||
}
|
||||
|
||||
# Run a command directly, and only with sudo if that fails (no password prompt when not needed).
|
||||
priv() { "$@" 2>/dev/null || { [ -n "$SUDO" ] && $SUDO "$@"; }; }
|
||||
read_file() { if [ -r "$1" ]; then cat "$1"; else $SUDO cat "$1"; fi; }
|
||||
|
||||
step() { printf '\n==> %s\n' "$*"; }
|
||||
log() { printf ' %s\n' "$*"; }
|
||||
die() { printf '\nerror: %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
install_packages() {
|
||||
local need=()
|
||||
command -v git >/dev/null || need+=(git)
|
||||
command -v curl >/dev/null || need+=(curl)
|
||||
command -v ssh >/dev/null || need+=(ssh)
|
||||
[ ${#need[@]} -eq 0 ] && { log "git, curl, ssh: present"; return; }
|
||||
log "installing ${need[*]}"
|
||||
if command -v apt-get >/dev/null; then
|
||||
local pkgs=("${need[@]/ssh/openssh-client}")
|
||||
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq
|
||||
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ca-certificates "${pkgs[@]}" >/dev/null
|
||||
elif command -v dnf >/dev/null; then
|
||||
$SUDO dnf install -y -q ca-certificates "${need[@]/ssh/openssh-clients}"
|
||||
elif command -v apk >/dev/null; then
|
||||
$SUDO apk add -q ca-certificates "${need[@]/ssh/openssh-client}"
|
||||
else
|
||||
die "no apt-get, dnf or apk: install ${need[*]} yourself and re-run"
|
||||
fi
|
||||
}
|
||||
|
||||
install_docker() {
|
||||
if ! command -v docker >/dev/null; then
|
||||
log "installing Docker Engine + Compose (get.docker.com)"
|
||||
local dlog; dlog=$(mktemp)
|
||||
curl -fsSL https://get.docker.com | $SUDO sh >"$dlog" 2>&1 || { tail -20 "$dlog" >&2; die "Docker install failed (full log: $dlog)"; }
|
||||
rm -f "$dlog"
|
||||
fi
|
||||
if ! docker info >/dev/null 2>&1 && ! $SUDO docker info >/dev/null 2>&1 \
|
||||
&& command -v systemctl >/dev/null && [ -d /run/systemd/system ]; then
|
||||
$SUDO systemctl enable --now docker >/dev/null 2>&1 || true
|
||||
fi
|
||||
if docker info >/dev/null 2>&1; then DOCKER=docker; else DOCKER="$SUDO docker"; fi
|
||||
$DOCKER info >/dev/null 2>&1 || die "Docker is installed but the daemon is not running"
|
||||
$DOCKER compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (apt-get install docker-compose-plugin)"
|
||||
log "docker $($DOCKER version --format '{{.Server.Version}}'), compose $($DOCKER compose version --short)"
|
||||
}
|
||||
|
||||
# Values already in .env fill in whatever the caller did not pass.
|
||||
load_existing_env() {
|
||||
local f="$INSTALL_DIR/.env" line key val
|
||||
[ -f "$f" ] || return 0
|
||||
log "keeping existing $f"
|
||||
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
|
||||
case $key in REPO_URL|REPO_REF|GIT_TOKEN|GIT_USERNAME|GIT_SSH_KEY|HOST_PORT)
|
||||
[ -n "${!key:-}" ] || printf -v "$key" '%s' "$val" ;;
|
||||
esac
|
||||
done < <(read_file "$f")
|
||||
}
|
||||
|
||||
# Credentials reach git through the environment only; nothing is stored in the checkout.
|
||||
git_auth() {
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
if [ -n "${GIT_TOKEN:-}" ]; then
|
||||
export GIT_TOKEN GIT_USERNAME="${GIT_USERNAME:-}"
|
||||
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 StrictHostKeyChecking=accept-new"
|
||||
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
||||
KEYFILE=$(mktemp); trap 'rm -f "$KEYFILE"' EXIT
|
||||
printf '%s' "$GIT_SSH_KEY" | base64 -d > "$KEYFILE" 2>/dev/null || die "GIT_SSH_KEY is not valid base64 (use: base64 -w0 deploy_key)"
|
||||
ssh="$ssh -i $KEYFILE -o IdentitiesOnly=yes"
|
||||
fi
|
||||
export GIT_SSH_COMMAND="$ssh"
|
||||
}
|
||||
|
||||
check_access() {
|
||||
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable: $(redact "$REPO_URL") ($REPO_REF)"; return; }
|
||||
# Private https repo and no token yet: ask on the terminal (stdin is this script).
|
||||
if [ -z "${GIT_TOKEN:-}" ] && [[ $REPO_URL == https://* ]] && [ -r /dev/tty ]; then
|
||||
printf ' %s needs a token. Git token (read-only): ' "$(redact "$REPO_URL")" > /dev/tty
|
||||
IFS= read -rs GIT_TOKEN < /dev/tty; echo > /dev/tty
|
||||
passed+=(GIT_TOKEN)
|
||||
git_auth
|
||||
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable with token"; return; }
|
||||
fi
|
||||
die "cannot read $REPO_REF from $(redact "$REPO_URL"). Check REPO_URL/REPO_REF, and pass GIT_TOKEN (https) or GIT_SSH_KEY (ssh) for a private repo"
|
||||
}
|
||||
|
||||
# The host checkout holds compose.yml and container/ (what the image is built from).
|
||||
# The app itself runs from the container's own checkout, which `update` manages.
|
||||
checkout() {
|
||||
if [ ! -d "$INSTALL_DIR/.git" ]; then
|
||||
priv mkdir -p "$INSTALL_DIR"
|
||||
[ -w "$INSTALL_DIR" ] || $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR"
|
||||
[ -z "$(ls -A "$INSTALL_DIR" | grep -vx .env || true)" ] || die "$INSTALL_DIR exists and is not a checkout of $NAME"
|
||||
log "new checkout in $INSTALL_DIR"
|
||||
git -C "$INSTALL_DIR" init --quiet
|
||||
git -C "$INSTALL_DIR" remote add origin "$REPO_URL"
|
||||
fi
|
||||
# First install and re-runs alike: fetch and check out REPO_REF.
|
||||
git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL"
|
||||
git -C "$INSTALL_DIR" fetch --quiet --prune --tags origin
|
||||
local target
|
||||
target=$(git -C "$INSTALL_DIR" rev-parse --verify --quiet "origin/$REPO_REF^{commit}" || git -C "$INSTALL_DIR" rev-parse --verify "$REPO_REF^{commit}")
|
||||
git -C "$INSTALL_DIR" reset --quiet --hard "$target"
|
||||
log "at $(git -C "$INSTALL_DIR" log -1 --format='%h %s')"
|
||||
}
|
||||
|
||||
# .env: created from .env.example on first install; on re-runs only the keys the caller
|
||||
# passed are replaced. Owned by uid 1000 (the container's user), group = installer, mode 640.
|
||||
write_env() {
|
||||
local f="$INSTALL_DIR/.env" tmp line key out=() seen=" "
|
||||
if [ -f "$f" ]; then mapfile -t lines < <(read_file "$f"); else
|
||||
mapfile -t lines < "$INSTALL_DIR/.env.example"
|
||||
passed=(REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT)
|
||||
log "writing $f"
|
||||
fi
|
||||
for line in "${lines[@]}"; do
|
||||
key=${line%%=*}
|
||||
if [[ $line =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && [[ " ${passed[*]} " == *" $key "* ]]; then
|
||||
out+=("$key=${!key:-}"); seen+="$key "
|
||||
else out+=("$line"); fi
|
||||
done
|
||||
for key in "${passed[@]}"; do [[ $seen == *" $key "* ]] || out+=("$key=${!key:-}"); done
|
||||
tmp=$(mktemp)
|
||||
printf '%s\n' "${out[@]}" > "$tmp"
|
||||
priv install -m 640 -o 1000 -g "$(id -g)" "$tmp" "$f" || die "could not write $f"
|
||||
rm -f "$tmp"
|
||||
[ ${#passed[@]} -eq 0 ] || log "set in .env: ${passed[*]}"
|
||||
}
|
||||
|
||||
health_version() {
|
||||
$DOCKER exec "$NAME" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen(f"http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null
|
||||
}
|
||||
|
||||
wait_healthy() {
|
||||
log "waiting for the app (first start clones the repo and installs requirements)"
|
||||
for _ in $(seq 1 180); do
|
||||
[ -n "$(health_version)" ] && { log "healthy at $(health_version)"; return; }
|
||||
[ "$($DOCKER inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = false ] && break
|
||||
sleep 1
|
||||
done
|
||||
$DOCKER logs --tail 40 "$NAME" >&2 || true
|
||||
die "$NAME did not become healthy (logs above)"
|
||||
}
|
||||
|
||||
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
||||
|
||||
main "$@"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
[pytest]
|
||||
testpaths = tests
|
||||
pythonpath = .
|
||||
# The source may be a read-only or foreign-owned bind mount; don't write a cache into it.
|
||||
addopts = -p no:cacheprovider
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
pytest==__PYTEST__
|
||||
httpx2==__HTTPX__
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
fastapi==__FASTAPI__
|
||||
uvicorn[standard]==__UVICORN__
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
|
||||
def test_healthz():
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/healthz")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
|
||||
|
||||
def test_index_and_assets():
|
||||
with TestClient(app) as client:
|
||||
page = client.get("/")
|
||||
css = client.get("/static/css/app.css")
|
||||
assert page.status_code == 200 and "__TITLE__" in page.text
|
||||
assert css.status_code == 200 and css.headers["cache-control"] == "no-cache"
|
||||
|
||||
|
||||
def test_info():
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/api/info").json()["name"] == "__TITLE__"
|
||||
Loading…
Add table
Add a link
Reference in a new issue