diff --git a/PLAN.md b/PLAN.md index 675eed8..03066c6 100644 --- a/PLAN.md +++ b/PLAN.md @@ -155,8 +155,20 @@ What we learned: Federated's monitoring. `coreapp deploy` drops `MONITOR` from the copy of `service` on the Core - [ ] Document the app format fully in the README (done in each app's README) -- [ ] Later: a database (`DEPENDS=postgresql`), SSO through Authelia, apps - published for other Cores (registry, submitting to Federated) +Databases (2026-12-03): `coreapp new --postgres ` adds +`DEPENDS="postgresql"`, DB_* settings in `env.in` (random password), an +`install` that creates the user and database on the Core's PostgreSQL +(`docker exec postgresql psql -U postgres`, as Federated's own installers +do) and an `uninstall` that drops them, and a Python example (psycopg) +that counts visits. Tested with `guest-book`: deploy, the count goes up, +a redeploy and a reboot of the Core keep the data, remove drops the database +and user. `postgresql.` resolves to the PostgreSQL container on the +`core` network (Docker's DNS); outside it, it's the public IP. + +- [ ] Next: sign-in through the Core's Authelia (OIDC), as Federated's apps + do with `configsso_` +- [ ] Later: apps published for other Cores (registry, submitting to + Federated) ## SDK packaging diff --git a/README.md b/README.md index 0f7dd8f..9ed8bde 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ the app's own `Dockerfile`. The README in each new app explains the files. | Command | Does | |---|---| | `coreapp new ` | Make an app in `./`; it gets an address in 192.168.200.x on the Core | +| `coreapp new --postgres ` | The same, with its own database on the Core's PostgreSQL (a Python example app that uses it) | | `coreapp deploy` | Build its image, copy it to the Core over SSH, install it, or update it keeping its `.env` | | `coreapp check` | It answers at its `MONITOR` URL with a valid certificate | | `coreapp status` / `logs [-f]` / `shell` | Its container, its log, a shell in it | @@ -108,5 +109,6 @@ stay installed. | `bin/coreapp-vm` | Creates and manages CoreServer VMs (`coreapp-vm help`) | | `bin/coreapp` | Makes, deploys and tests apps (`coreapp help`) | | `templates/app/` | What `coreapp new` starts from | +| `templates/postgres/` | Laid over it by `--postgres` (`*.append` files are added to the base file; `.remove` lists base files to drop) | | `uninstall.sh` | Removes what coreapp-dev set up | | [PLAN.md](PLAN.md), [TEST.md](TEST.md) | What's next, and how to test it | diff --git a/TEST.md b/TEST.md index b9f8986..2436314 100644 --- a/TEST.md +++ b/TEST.md @@ -169,3 +169,18 @@ no `blackboxregistrar` request. `~/.local/share/coreapp-dev/logs/hello-remove.log` (mode 600). 7. Collisions: an app named like one of Federated's (`coreapp new nextcloud`, deploy) is refused; so is an `INTERNAL_IP` another container uses. + +### With a database + +1. `coreapp new --postgres guest-book`: has `app.py`, no `www/`; + `service` has `DEPENDS="postgresql"`; `env.in` has `DB_NAME=guest_book` + and a random `DB_PASSWORD`; the README has a Database section. +2. `coreapp deploy`, `coreapp check`. Loading the page several times + (`curl -s https://guest-book./ | grep visits`) counts up. On the + Core, `docker exec postgresql psql -U postgres -l` lists `guest_book`, + owned by `guest_book`. +3. Change `app.py`, `coreapp deploy`: the change shows, the count continues. +4. `virsh -c qemu:///system reboot coreserver`: once the Core is up, the + app answers and the count continues (its log may show "Waiting for the + database" first). +5. `coreapp remove`: the `guest_book` database and user are gone too. diff --git a/bin/coreapp b/bin/coreapp index 0cb891c..0143ad3 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -3,7 +3,8 @@ # Purpose : Make, deploy and test apps for Federated Core, against the Core # in coreapp-dev's VM (coreapp-vm). # -# coreapp new make a new app in ./ +# coreapp new [--postgres] +# make a new app in ./ (with its own database) # coreapp deploy build, copy to the Core, install or update # coreapp check the app answers at https://./ # coreapp status its container, address and URL @@ -17,7 +18,8 @@ set -euo pipefail SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" -TEMPLATE="$(dirname "$SELF_DIR")/templates/app" +TEMPLATES="$(dirname "$SELF_DIR")/templates" +TEMPLATE="$TEMPLATES/app" DATA="$HOME/.local/share/coreapp-dev" # The INTERNAL_IP given to each app made on this machine: "name ip" lines ADDRESSES="$DATA/app-addresses" @@ -108,9 +110,17 @@ next_address() { } cmd_new() { - local name="${1:-}" title ip f + local name="" overlay="" title ip dbname f + while [[ $# -gt 0 ]]; do + case "$1" in + --postgres) overlay="$TEMPLATES/postgres" ;; + -*) die "Unknown option $1. Usage: coreapp new [--postgres] " ;; + *) name="$1" ;; + esac + shift + done [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE" - [[ -n "$name" ]] || die "Usage: coreapp new (lowercase letters, digits and -)" + [[ -n "$name" ]] || die "Usage: coreapp new [--postgres] (lowercase letters, digits and -)" [[ "$name" =~ ^[a-z][a-z0-9-]{1,30}$ ]] \ || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter. It becomes https://$name.." [[ ! -e "$name" ]] || die "./$name already exists." @@ -121,16 +131,30 @@ cmd_new() { mkdir -p "$DATA" echo "$name $ip" >> "$ADDRESSES" fi - # "my-app" -> "My App" + # "my-app" -> "My App"; database names can't have "-" title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')" + dbname="${name//-/_}" mkdir "$name" tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf - + if [[ -n "$overlay" ]]; then + # The overlay's files replace the base's; *.append ones are added to the + # end of the base file; .remove lists base files it doesn't use + tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude='*.append' -cf - . \ + | tar -C "$name" -xf - + for f in "$overlay"/*.append; do + [[ -e "$f" ]] && cat "$f" >> "$name/$(basename "$f" .append)" + done + if [[ -f "$overlay/.remove" ]]; then + while read -r f; do [[ -n "$f" ]] && rm -rf "${name:?}/$f"; done < "$overlay/.remove" + fi + fi while IFS= read -r -d '' f; do - sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{IP}}/$ip/g" "$f" + sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{IP}}/$ip/g" \ + -e "s/{{DBNAME}}/$dbname/g" "$f" done < <(find "$name" -type f ! -name '*.png' -print0) - echo "Made $title in ./$name (address on the Core: $ip)." + echo "Made $title in ./$name (address on the Core: $ip${overlay:+, database $dbname})." echo "Next: cd $name && coreapp deploy" } diff --git a/templates/postgres/.remove b/templates/postgres/.remove new file mode 100644 index 0000000..f8d728c --- /dev/null +++ b/templates/postgres/.remove @@ -0,0 +1 @@ +www diff --git a/templates/postgres/Dockerfile b/templates/postgres/Dockerfile new file mode 100644 index 0000000..26b0e69 --- /dev/null +++ b/templates/postgres/Dockerfile @@ -0,0 +1,9 @@ +# The app's image. coreapp deploy builds it as coreapp/{{NAME}}: +# and copies it to the Core. Replace this with your own app; keep it +# listening on the port in docker-compose.yml.in (8080). +FROM python:3.13-slim +RUN pip install --no-cache-dir "psycopg[binary]==3.2.*" +COPY app.py /app/app.py +USER nobody +EXPOSE 8080 +CMD ["python", "-u", "/app/app.py"] diff --git a/templates/postgres/README.md.append b/templates/postgres/README.md.append new file mode 100644 index 0000000..c8276e6 --- /dev/null +++ b/templates/postgres/README.md.append @@ -0,0 +1,13 @@ + +## Database + +The app has its own database on the Core's shared PostgreSQL +(`DEPENDS="postgresql"` in `service`): + +- `install` creates the user and database `{{DBNAME}}`, with the random + `DB_PASSWORD` from `.env`; `uninstall` drops both (`coreapp remove` + deletes the data). +- The app reads `DB_HOST` (`postgresql.`, which only resolves on the + Core's `core` network), `DB_PORT`, `DB_NAME`, `DB_USER` and `DB_PASSWORD` + from its environment. `app.py` shows how, with `psycopg`. +- Look at the data: `coreapp-vm ssh docker exec -it postgresql psql -U postgres {{DBNAME}}`. diff --git a/templates/postgres/app.py b/templates/postgres/app.py new file mode 100644 index 0000000..281f3ae --- /dev/null +++ b/templates/postgres/app.py @@ -0,0 +1,82 @@ +"""{{TITLE}}: counts its visits in its PostgreSQL database. + +Settings come from the environment (.env on the Core): DB_HOST, DB_PORT, +DB_NAME, DB_USER, DB_PASSWORD, APP_URL. +""" + +import html +import os +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import psycopg + +DB = { + "host": os.environ["DB_HOST"], + "port": os.environ.get("DB_PORT", "5432"), + "dbname": os.environ["DB_NAME"], + "user": os.environ["DB_USER"], + "password": os.environ["DB_PASSWORD"], + "connect_timeout": 5, +} + + +def connect(): + return psycopg.connect(**DB, autocommit=True) + + +def setup(): + # PostgreSQL may still be starting (after a reboot): keep trying + for attempt in range(60): + try: + with connect() as db: + db.execute( + "CREATE TABLE IF NOT EXISTS visits (" + " id bigserial PRIMARY KEY," + " at timestamptz NOT NULL DEFAULT now())" + ) + return + except psycopg.OperationalError as error: + print(f"Waiting for the database ({error})", flush=True) + time.sleep(5) + raise SystemExit("The database didn't answer for 5 minutes") + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/health": + self.reply(200, "text/plain", "ok\n") + return + try: + with connect() as db: + db.execute("INSERT INTO visits DEFAULT VALUES") + count = db.execute("SELECT count(*) FROM visits").fetchone()[0] + except psycopg.Error as error: + self.reply(503, "text/plain", f"Database error: {error}\n") + return + page = f""" + +{{TITLE}} + +

{{TITLE}}

+

Running on Federated Core, deployed with coreapp-dev.

+

Visits, counted in PostgreSQL: {count}

+

{html.escape(os.environ.get("APP_URL", ""))}

+ + +""" + self.reply(200, "text/html; charset=utf-8", page) + + def reply(self, status, content_type, body): + data = body.encode() + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + +if __name__ == "__main__": + setup() + print("Listening on port 8080", flush=True) + ThreadingHTTPServer(("", 8080), Handler).serve_forever() diff --git a/templates/postgres/env.in b/templates/postgres/env.in new file mode 100644 index 0000000..c780834 --- /dev/null +++ b/templates/postgres/env.in @@ -0,0 +1,11 @@ +# Filled in once, when the app is installed (see README.md). Redeploying +# keeps the result, so secrets don't change. +IMAGE_VERSION=@VERSION@ +APP_URL=https://{{NAME}}.@DOMAIN@ +APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ +# Its database on the Core's PostgreSQL, made by install +DB_HOST=postgresql.@DOMAIN@ +DB_PORT=5432 +DB_NAME={{DBNAME}} +DB_USER={{DBNAME}} +DB_PASSWORD=@DB_PASSWORD:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/templates/postgres/install b/templates/postgres/install new file mode 100755 index 0000000..3ec2594 --- /dev/null +++ b/templates/postgres/install @@ -0,0 +1,18 @@ +. /federated/lib/helpers.sh +installGeneric {{NAME}} +# .env holds secrets +chmod 600 /federated/apps/{{NAME}}/.env + +# Its own database and user on the Core's PostgreSQL (DEPENDS=postgresql), +# with the password from .env. Safe to run again: an existing user gets the +# password, an existing database is kept. +DB_PASSWORD="$(sed -n 's/^DB_PASSWORD=//p' /federated/apps/{{NAME}}/.env)" +if docker exec postgresql psql -U postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname = '{{DBNAME}}'" | grep -q 1; then + docker exec postgresql psql -U postgres -qc "ALTER USER {{DBNAME}} WITH PASSWORD '$DB_PASSWORD'" +else + docker exec postgresql psql -U postgres -qc "CREATE USER {{DBNAME}} WITH PASSWORD '$DB_PASSWORD'" +fi +if ! docker exec postgresql psql -U postgres -tAc "SELECT 1 FROM pg_database WHERE datname = '{{DBNAME}}'" | grep -q 1; then + docker exec postgresql psql -U postgres -qc "CREATE DATABASE {{DBNAME}} OWNER {{DBNAME}}" +fi +unset DB_PASSWORD diff --git a/templates/postgres/service b/templates/postgres/service new file mode 100644 index 0000000..942223b --- /dev/null +++ b/templates/postgres/service @@ -0,0 +1,9 @@ +NAME="{{TITLE}}" +DESCRIPTION="{{TITLE}}, made with coreapp-dev" +DOCS= +CONTAINER=coreapp/{{NAME}} +VERSION=0.1.0 +INTERNAL_IP={{IP}} +DEPENDS="postgresql" +PORTS=8080 +MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx" diff --git a/templates/postgres/uninstall b/templates/postgres/uninstall new file mode 100755 index 0000000..09e2d46 --- /dev/null +++ b/templates/postgres/uninstall @@ -0,0 +1,6 @@ +# Sourced by the Core's uninstallapp (so no `exit` here): stop the app and +# delete its settings, data and database +docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down +rm -rf /federated/apps/{{NAME}} +docker exec postgresql psql -U postgres -qc "DROP DATABASE IF EXISTS {{DBNAME}}" +docker exec postgresql psql -U postgres -qc "DROP USER IF EXISTS {{DBNAME}}"