Test recipes locally with Docker Compose (#1)
scripts/local-test.sh starts a recipe the way Cottage runs it (parameters filled in, owned volumes without copy-up, default limits, no-new-privileges, localhost only), waits for its health path to answer 200 and cleans up. CI runs it on every pull request, forks included, alongside Cottage's own checks, which now live under .github/. The README explains the recipe format and rules for contributors.
This commit is contained in:
1 parent
a0d992022d
commit
193936ab2e
9 files changed
+215
-64
No files matched your search
@@ -0,0 +1,71 @@
|
||||
"""Helper for local-test.sh: reads the recipe's Compose config (as JSON) and writes
|
||||
an env file, a Compose override and plan.sh. Standard library only."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import shlex
|
||||
import socket
|
||||
import sys
|
||||
|
||||
slug, work = sys.argv[1], sys.argv[2]
|
||||
with open(os.path.join(work, "config.json")) as f:
|
||||
cfg = json.load(f)
|
||||
x = cfg.get("x-harbor") or sys.exit(f"{slug}: template.yml has no x-harbor block")
|
||||
|
||||
primary = x["primary"]
|
||||
health = x.get("health_path", "/")
|
||||
res = x.get("default_resources", {})
|
||||
owned = x.get("volumes") or {}
|
||||
|
||||
with socket.socket() as s: # a free port on this machine
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
|
||||
GEN = {
|
||||
"random32": lambda: secrets.token_urlsafe(24)[:32],
|
||||
"random16": lambda: secrets.token_urlsafe(12)[:16],
|
||||
"hex32": lambda: secrets.token_hex(16),
|
||||
}
|
||||
env = {
|
||||
# what Cottage's servers provide to every app
|
||||
"HARBOR_POD_ID": "local-test",
|
||||
"HARBOR_SLUG": slug,
|
||||
"HARBOR_HOSTNAME": "localhost",
|
||||
"HARBOR_PUBLIC_URL": f"http://127.0.0.1:{port}",
|
||||
}
|
||||
for p in x.get("parameters") or []:
|
||||
if p.get("generate"):
|
||||
env[p["key"]] = GEN[p["generate"]]()
|
||||
else:
|
||||
env[p["key"]] = str(p.get("default", ""))
|
||||
with open(os.path.join(work, "env"), "w") as f:
|
||||
for k, v in env.items():
|
||||
f.write(f"{k}={json.dumps(v)}\n")
|
||||
|
||||
override = {"services": {}}
|
||||
for name, svc in cfg["services"].items():
|
||||
o = {"security_opt": ["no-new-privileges:true"]}
|
||||
if name == primary["service"]:
|
||||
o["ports"] = [f"127.0.0.1:{port}:{primary['port']}"]
|
||||
if res.get("memory_mb"):
|
||||
o["mem_limit"] = f"{res['memory_mb']}m"
|
||||
if res.get("cpu_millis"):
|
||||
o["cpus"] = res["cpu_millis"] / 1000
|
||||
mounts = []
|
||||
for m in svc.get("volumes") or []:
|
||||
if m.get("type") == "volume" and m.get("source") in owned:
|
||||
# same target, so Compose replaces the recipe's mount with this one
|
||||
mounts.append({"type": "volume", "source": m["source"], "target": m["target"],
|
||||
"read_only": m.get("read_only", False), "volume": {"nocopy": True}})
|
||||
if mounts:
|
||||
o["volumes"] = mounts
|
||||
override["services"][name] = o
|
||||
with open(os.path.join(work, "override.json"), "w") as f:
|
||||
json.dump(override, f)
|
||||
|
||||
parts = []
|
||||
for name, o in owned.items():
|
||||
parts.append(f"{name}:{o.get('uid', 0)}:{o.get('gid', 0)}:{o.get('mode', '0755')}")
|
||||
with open(os.path.join(work, "plan.sh"), "w") as f:
|
||||
f.write(f"port={port}\nhealth={shlex.quote(health)}\nowned={shlex.quote(' '.join(parts))}\n")
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/bin/sh
|
||||
# Test a recipe locally with Docker Compose, close to the way Cottage runs it:
|
||||
# - parameters are filled in (generated secrets, defaults)
|
||||
# - volumes listed under x-harbor.volumes belong to the given uid/gid, with Docker's
|
||||
# copy-up turned off, as on Cottage's servers
|
||||
# - the default memory and CPU limits apply, with no-new-privileges
|
||||
# - the app is published on 127.0.0.1 only
|
||||
# It waits for health_path to answer 200, then removes the containers and volumes.
|
||||
#
|
||||
# scripts/local-test.sh apps/vaultwarden
|
||||
# KEEP=1 scripts/local-test.sh apps/vaultwarden # leave it running to try it in a browser
|
||||
#
|
||||
# Needs Docker with Compose v2, python3 and curl.
|
||||
set -eu
|
||||
dir=$(cd "${1:?usage: scripts/local-test.sh apps/<slug>}" && pwd)
|
||||
slug=$(basename "$dir")
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
work=$(mktemp -d)
|
||||
project="cottage-test-$slug"
|
||||
compose() { docker compose -p "$project" -f "$dir/template.yml" -f "$work/override.json" --env-file "$work/env" "$@"; }
|
||||
|
||||
cleanup() {
|
||||
if [ "${KEEP:-}" = 1 ] && [ "${passed:-}" = 1 ]; then
|
||||
echo "left running: docker compose -p $project down -v # when you're done"
|
||||
else
|
||||
compose down -v --remove-orphans >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
docker compose -f "$dir/template.yml" config --format json --no-interpolate > "$work/config.json"
|
||||
python3 -I "$here/local-test-plan.py" "$slug" "$work"
|
||||
# plan.sh sets: port, health, owned (space-separated "volume:uid:gid:mode")
|
||||
. "$work/plan.sh"
|
||||
|
||||
echo "$slug: starting on http://127.0.0.1:$port"
|
||||
compose create --quiet-pull >/dev/null
|
||||
for v in $owned; do
|
||||
name=${v%%:*}; rest=${v#*:}; uid=${rest%%:*}; rest=${rest#*:}; gid=${rest%%:*}; mode=${rest#*:}
|
||||
docker run --rm -v "${project}_$name:/v" busybox:1.37 sh -c "chown $uid:$gid /v && chmod $mode /v"
|
||||
done
|
||||
compose start >/dev/null
|
||||
|
||||
url="http://127.0.0.1:$port$health"
|
||||
code=000
|
||||
for _ in $(seq 1 90); do
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$url" || true)
|
||||
[ "$code" = 200 ] && break
|
||||
if compose ps --status exited --status dead -q | grep -q .; then break; fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$code" != 200 ]; then
|
||||
echo "$slug: $url answered $code, expected 200. Recent logs:"
|
||||
compose logs --tail 40 || true
|
||||
exit 1
|
||||
fi
|
||||
passed=1
|
||||
echo "$slug: ok ($url answered 200)"
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Smoke test one recipe against a harbord: upload → deploy → wait for running →
|
||||
# HTTP check of health_path through the node's router (real runtime only) → delete.
|
||||
#
|
||||
# HARBOR_URL=http://127.0.0.1:7700 HARBOR_TOKEN=hbr_... scripts/smoke.sh apps/vaultwarden
|
||||
#
|
||||
# HEALTH_BASE (optional) is how this machine reaches pod hostnames, e.g. https://%s
|
||||
# where %s is replaced with the pod's domain. Without it the HTTP check is skipped,
|
||||
# which is what the fake runtime needs.
|
||||
set -eu
|
||||
dir=$(cd "${1:?recipe directory}" && pwd)
|
||||
: "${HARBOR_URL:?}" "${HARBOR_TOKEN:?}"
|
||||
api() { curl -fsS -H "Authorization: Bearer $HARBOR_TOKEN" "$@"; }
|
||||
json() { python3 -c "import sys,json; d=json.load(sys.stdin); print($1)"; }
|
||||
|
||||
slug=$(basename "$dir")
|
||||
api -X POST -H 'Content-Type: application/yaml' --data-binary @"$dir/template.yml" "$HARBOR_URL/v1/templates" >/dev/null
|
||||
version=$(api "$HARBOR_URL/v1/templates?slug=$slug" | json "sorted(d['data'], key=lambda t: t['created_at'])[-1]['version']")
|
||||
health=$(api "$HARBOR_URL/v1/templates/$slug?version=$version" | json "d.get('health_path','/')")
|
||||
ref="smoke-$slug-$$"
|
||||
pod=$(api -X POST -H "Idempotency-Key: $ref" -d "{\"slug\":\"smoke-$$\",\"external_ref\":\"$ref\",\"template\":\"$slug\",\"template_version\":\"$version\"}" \
|
||||
"$HARBOR_URL/v1/pods" | json "d['pod']['id']")
|
||||
trap 'api -X DELETE "$HARBOR_URL/v1/pods/$pod?purge=true" >/dev/null || true' EXIT
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
status=$(api "$HARBOR_URL/v1/pods/$pod" | json "d['status']")
|
||||
[ "$status" = running ] && break
|
||||
[ "$status" = failed ] && { echo "$slug: pod failed"; exit 1; }
|
||||
sleep 2
|
||||
done
|
||||
[ "$status" = running ] || { echo "$slug: not running after 120 s (status $status)"; exit 1; }
|
||||
|
||||
if [ -n "${HEALTH_BASE:-}" ]; then
|
||||
domain=$(api "$HARBOR_URL/v1/pods/$pod" | json "d['domain']")
|
||||
# shellcheck disable=SC2059
|
||||
url="$(printf "$HEALTH_BASE" "$domain")$health"
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 120 --retry 20 --retry-delay 3 --retry-all-errors "$url")
|
||||
[ "$code" = 200 ] || { echo "$slug: $url returned $code"; exit 1; }
|
||||
fi
|
||||
echo "$slug@$version: ok"
|
||||
Reference in new issue
Block a user