diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..729c247 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,126 @@ +# Release: publish the three registry images the federated suite pulls. +# +# Trigger: semver tags WITHOUT a v prefix (the suite's VERSION_RX is +# '^[0-9][0-9\.]*$'), e.g. 1.0.0. Every release pushes: +# federatedcomputer/superbrain-app: + :latest +# federatedcomputer/superbrain-web: + :latest +# federatedcomputer/superbrain-migrate: + :latest +# all three sharing the same version tag (house tooling tracks one version +# per app), for linux/amd64 and linux/arm64. +# +# Required secrets: DOCKERHUB_USERNAME, DOCKERHUB_TOKEN (an access token +# scoped to the federatedcomputer namespace). +# +# The publish job is gated on the smoke job: the migrate image is actually +# bootstrapped against a throwaway PostgreSQL (fresh schema + full ledger + +# idempotent re-run) before anything is pushed, so a broken db/ can never +# reach a tag the upgrade flow will pull. + +name: release + +on: + push: + tags: + - '[0-9]+.[0-9]+.[0-9]+' + +permissions: + contents: read + +jobs: + smoke: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16.15-alpine + env: + POSTGRES_USER: superbrain + POSTGRES_PASSWORD: smoke-only + POSTGRES_DB: superbrain + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U superbrain" + --health-interval 3s + --health-timeout 3s + --health-retries 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Go build + vet + unit tests (DB suites skipped without TEST_DATABASE_URL) + run: | + go build ./internal/... . + go vet ./internal/... . + go test ./internal/... + + - name: Build the migrate image + run: docker build -t superbrain-migrate:smoke db/ + + - name: Bootstrap a fresh database with the image + run: | + docker run --rm --network host \ + -e DB_HOST=127.0.0.1 -e PGPASSWORD=smoke-only \ + superbrain-migrate:smoke + tables=$(docker run --rm --network host -e PGPASSWORD=smoke-only \ + postgres:16.15-alpine psql -h 127.0.0.1 -U superbrain -d superbrain \ + -t -A -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public'") + ledger=$(docker run --rm --network host -e PGPASSWORD=smoke-only \ + postgres:16.15-alpine psql -h 127.0.0.1 -U superbrain -d superbrain \ + -t -A -c "SELECT count(*) FROM _migration") + files=$(ls db/migrations/*.sql | wc -l) + echo "tables=$tables ledger=$ledger files=$files" + [ "$tables" -ge 20 ] || { echo "schema.sql did not apply"; exit 1; } + [ "$ledger" = "$files" ] || { echo "ledger incomplete"; exit 1; } + + - name: Re-run must be a no-op (idempotency) + run: | + docker run --rm --network host \ + -e DB_HOST=127.0.0.1 -e PGPASSWORD=smoke-only \ + superbrain-migrate:smoke | grep -q "up to date" + + publish: + needs: smoke + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Push superbrain-app + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: | + federatedcomputer/superbrain-app:${{ github.ref_name }} + federatedcomputer/superbrain-app:latest + + - name: Push superbrain-web + uses: docker/build-push-action@v6 + with: + context: web + file: web/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: | + federatedcomputer/superbrain-web:${{ github.ref_name }} + federatedcomputer/superbrain-web:latest + + - name: Push superbrain-migrate + uses: docker/build-push-action@v6 + with: + context: db + file: db/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: | + federatedcomputer/superbrain-migrate:${{ github.ref_name }} + federatedcomputer/superbrain-migrate:latest diff --git a/Dockerfile b/Dockerfile index d2b4583..5ff7628 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,9 @@ # Pinned patch level; keep in lockstep with the tests service in docker-compose.yml. +# NOTE: deliberately a plain FROM (no --platform=$BUILDPLATFORM cross-compile): +# the dev hosts run the legacy builder, which cannot parse BUILDPLATFORM and +# would break `docker compose build`. Release CI builds each arch natively +# under buildx/qemu — slower for arm64, but releases are rare and local dev +# must keep working. FROM golang:1.26.1-alpine3.22 AS build RUN apk add --no-cache ca-certificates tzdata WORKDIR /src diff --git a/README.md b/README.md index 0390bbe..2f47b7f 100644 --- a/README.md +++ b/README.md @@ -367,12 +367,15 @@ The installer: plus the house mail relay credential for notification emails, the `core` docker network, and fixed-IP availability (override with `SUPERBRAIN_{WEB,APP,MIGRATE}_IP` on collision). -2. **Installs the house integration** — `/federated/lib/superbrain.sh` and - `/federated/services/superbrain/service`, then runs the standard - `/federated/bin/installapp superbrain`: compose + `.env` generation - (`TIER=core`), image builds from the staged source (interim mode until - CI publishes registry images), database + user on the shared postgres, - pdns record, monitors, superpanel catalog entry. +2. **Installs the house integration** — `/federated/lib/superbrain.sh`, + `/federated/services/superbrain/service` and the `upgrade/pre` hook, + then runs the standard `/federated/bin/installapp superbrain`: compose + + `.env` generation (`TIER=core`), **image pulls from Docker Hub** + (`federatedcomputer/superbrain-{app,web,migrate}`, one shared version + tag, amd64 + arm64 — no source, no builds on the host), database + user + on the shared postgres (the migrate image bootstraps the schema and + runs the ledger itself), pdns record, monitors, superpanel catalog + entry. 3. **Registers the Authelia OIDC client** — including the `claims_policy` that puts `email` in the ID token (without it every SSO login fails with AccessDenied), validated before Authelia is restarted. @@ -386,20 +389,107 @@ Prerequisites: Authelia with the OIDC provider configured, shared sender account). Full design record, IP plan, upgrade flow and incident history: [deploy/federated/STRATEGY.md](deploy/federated/STRATEGY.md). -**Updating** an installed core (interim source-build mode) is one command -on the host: +**Updating** an installed core is the standard house flow — bump `VERSION` +in `/federated/services/superbrain/service` to the new release tag and run +`/federated/bin/upgrade superbrain` (the pre-hook backs up the database +and pulls all three images). Or one command, which also syncs the suite +files from the repo: ```bash -sudo bash /federated/apps/superbrain/deploy/federated/update.sh [git-ref] +git clone https://gitea.federated.computer/Federated_Computer/brain.git /tmp/superbrain-repo +sudo bash /tmp/superbrain-repo/deploy/federated/update.sh [git-ref] ``` -It clones the requested revision (default `main`), takes a pre-update -`pg_dump` (last 5 kept under the app dir), refreshes the suite integration -files, rebuilds the images, recreates the stack (migrations run -automatically), health-probes both containers, and **rolls back to the -previous images automatically on any failure**. When CI starts publishing -registry images, the generic house `upgrade` flow and the panel button -supersede this script (drop `IMAGE_VERSION_HOLD=1` from the app `.env`). +Releases are semver tags without a `v` prefix (`1.0.0`); CI builds and +pushes all three images under the same tag (plus `:latest`) for +linux/amd64 and linux/arm64. The migrate image is self-contained: it +detects an empty database, applies `schema.sql` as the superbrain user, +then runs the checksummed migration ledger — the host never needs the +source tree. + +## Environment variable reference + +Everything the stack reads, so a generated `.env` (or hosting environment) +stays correct as features are added. `.env.example` carries the same list +with annotations. "Required" means the app refuses to start or the feature +is off without it. + +### Core (every deployment) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `AUTH_SECRET` | **yes** | — | Signs NextAuth JWTs, Go session cookies, proxy assertions and service tokens. Keep stable: rotating it signs everyone out and (without `ENCRYPTION_KEY`) invalidates stored IMAP passwords. `openssl rand -base64 32` | +| `NEXTAUTH_SECRET` | no | `AUTH_SECRET` | Alternative name; takes precedence when both are set (both sides use the same precedence) | +| `NEXTAUTH_URL` | **yes** in production | — | Exact browser-facing origin. Drives OIDC callbacks, the proxy's origin allowlist, cookie-secure derivation and password-reset links | +| `ENCRYPTION_KEY` | no | derived from `AUTH_SECRET` | Dedicated key for stored credentials (IMAP passwords, notification channel secrets, BYO AI keys). Set it and rotating `AUTH_SECRET` no longer touches them. Back it up with the database | +| `COOKIE_SECURE` | no | derived from `NEXTAUTH_URL` scheme | Set `0` explicitly only for local HTTP | +| `DATABASE_URL` | **yes** (Go) | — | `postgres://user:pass@host:5432/db?sslmode=disable`; `DB_URL` is the Makefile fallback | + +### Compose stack (repo `docker-compose.yml`) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `POSTGRES_PASSWORD` | **yes** | — | Fail-fast `:?` interpolation — compose refuses to start without it | +| `POSTGRES_VOLUME` | no | `superbrain_pgdata` | Data volume name | +| `POSTGRES_VOLUME_EXTERNAL` | no | `false` | `true` to mount a pre-existing volume | +| `APP_HOST_PORT` / `WEB_HOST_PORT` | no | `8080` / `3000` | 127.0.0.1 host bindings; when shifting `WEB_HOST_PORT`, `NEXTAUTH_URL` must match the browser-facing origin | +| `PORT` | no | `8080` | Go listen port inside the container | + +### Access policy (tier & auth shape) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `TIER` | no | unset | `core` (Authelia-only) or `multi` (self-service signup); derives the three below. Invalid values fail startup | +| `AUTH_MODE` | no | tier-derived, else `both` | `both` / `password` / `oidc` — overrides the tier. Invalid values fail startup | +| `SIGNUP_ENABLED` | no | tier-derived, else on | `0` closes self-service registration | +| `ALLOW_BOOTSTRAP_SIGNUP` | no | tier-derived, else on | `0` stops the first signup from claiming admin (set `0` on any exposed host) | +| `ADMIN_EMAILS` | no | empty | Comma-separated operator addresses: reserved at signup, ADMIN at first SSO login, ADMIN via `--seed` | +| `TRUSTED_PROXY` | no | unset | `1` only when the proxy overwrites `X-Real-IP` (bundled nginx template does; traefik does not) — enables per-client rate-limit identity | + +### Authelia OIDC (all three required for SSO; placeholders = off) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `OIDC_ISSUER` | for SSO | — | Exact issuer from Authelia's discovery document | +| `OIDC_CLIENT_ID` | for SSO | — | Must match the Authelia client | +| `OIDC_CLIENT_SECRET` | for SSO | — | The **plain** secret, not the digest | + +### Transactional mail (password reset + notification email channel) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `SMTP_HOST` | for mail | — | Relay host; unset disables reset (503) and email delivery | +| `SMTP_PORT` | no | `587` | `465` = implicit TLS; otherwise STARTTLS when advertised | +| `SMTP_USERNAME` / `SMTP_PASSWORD` | no | — | AUTH PLAIN when the relay requires it | +| `SMTP_FROM` | **with SMTP_HOST** | — | Envelope+header sender | +| `NETGUARD_TRUSTED_HOSTS` | no | empty | Comma-separated operator-pinned hostnames allowed to resolve to private addresses (split-horizon relays). Never user-supplied names | + +### AI (assistant, automations) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `AI_API_KEY` | for the server-wide key | — | Operator fallback key; per-user BYO configs (Settings → AI) take precedence, and free/standard plans are BYO-only | +| `AI_MODEL` | no | `recursive/flint-v1.0:free` | Any model the provider serves | +| `AI_BASE_URL` | no | `https://openrouter.ai/api/v1` | Any OpenAI-compatible endpoint | +| `AI_PROVIDER` | no | `openai-compatible` | or `anthropic` / `gemini` | + +### Federated suite installs only + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `IMAGE_VERSION` | **yes** | `1.0.0` | Shared tag for the three registry images; `upgrade` rewrites it. Must be the ONLY `VERSION=`-containing line in the file (upgrade_app's sed matches every occurrence) | +| `DB_HOST` / `DB_USER` / `DB_NAME` / `PGPASSWORD` | **yes** | — | Shared suite postgres coordinates, read by the migrate image's bootstrap | +| `API_BASE_URL` | **yes** (web) | — | Server-only DNS to the Go container (`http://superbrain-app:8080`) | +| `AUTH_TRUST_HOST` | **yes** (web) | — | `true` behind the reverse proxy | + +### Tests/fixtures only — never in production + +| Variable | Default | Purpose | +|---|---|---| +| `TEST_DATABASE_URL` | unset (DB tests skip) | Integration test database | +| `INTEGRATIONS_ALLOW_PRIVATE` | unset | Allows private-range dials (loopback fakes, deliberate LAN deployments) | +| `INTEGRATIONS_ALLOW_INSECURE_IMAP` | unset | Permits plaintext IMAP for fixtures | +| `BASE_URL` / `CHROMIUM_PATH` / `E2E_KEEP_DATA` | see `.env.example` | Browser suites | ## Client test build diff --git a/db/Dockerfile b/db/Dockerfile new file mode 100644 index 0000000..698ef19 --- /dev/null +++ b/db/Dockerfile @@ -0,0 +1,15 @@ +# federatedcomputer/superbrain-migrate — self-contained database bootstrap +# and migration runner. Ships db/ inside the image so the server never needs +# the source tree. Entrypoint: bootstrap.sh (empty database => schema.sql as +# DB_USER, then always the checksummed migration ledger). +# +# Base image = the same postgres alpine the dev stack's migrate service uses; +# only the psql client is exercised. Client 16 against a newer server (the +# federated suite runs 17.x) is the supported direction. +FROM postgres:16.15-alpine + +COPY . /db +RUN chmod +x /db/bootstrap.sh /db/migrate.sh + +WORKDIR /db +CMD ["sh", "/db/bootstrap.sh"] diff --git a/db/bootstrap.sh b/db/bootstrap.sh new file mode 100644 index 0000000..344a71f --- /dev/null +++ b/db/bootstrap.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# bootstrap.sh — the federatedcomputer/superbrain-migrate entrypoint. +# +# Makes fresh-install and upgrade the SAME command, so a server never needs +# the source tree: +# 1. wait for PostgreSQL, +# 2. if the database has no tables, apply /db/schema.sql AS DB_USER +# (object ownership matters: every later migration must be able to +# ALTER these objects — applying as postgres would strand ownership), +# 3. always run /db/migrate.sh (ordered, checksummed, advisory-locked, +# one transaction per file; idempotent against a bootstrapped schema). +# +# Environment (same contract as migrate.sh): +# PGPASSWORD required +# DB_HOST default "db" +# DB_USER default "superbrain" +# DB_NAME default "superbrain" +set -eu + +DB_HOST="${DB_HOST:-db}" +DB_USER="${DB_USER:-superbrain}" +DB_NAME="${DB_NAME:-superbrain}" +[ -n "${PGPASSWORD:-}" ] || { echo "bootstrap: PGPASSWORD is required" >&2; exit 1; } + +psql() { command psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -v ON_ERROR_STOP=1 "$@"; } + +echo "bootstrap: waiting for postgres at $DB_HOST" +i=0 +until pg_isready -q -h "$DB_HOST" -U "$DB_USER" 2>/dev/null; do + i=$((i + 1)) + [ "$i" -ge 60 ] && { echo "bootstrap: postgres at $DB_HOST never became ready" >&2; exit 1; } + sleep 2 +done + +TABLES=$(psql -t -A -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'") +if [ "$TABLES" = "0" ]; then + echo "bootstrap: empty database '$DB_NAME' - applying schema.sql as $DB_USER" + psql -q -f /db/schema.sql +else + echo "bootstrap: database has $TABLES tables - skipping schema.sql" +fi + +exec sh /db/migrate.sh diff --git a/deploy/federated/STRATEGY.md b/deploy/federated/STRATEGY.md index d423b5d..07eb7b7 100644 --- a/deploy/federated/STRATEGY.md +++ b/deploy/federated/STRATEGY.md @@ -41,33 +41,55 @@ probe). Source-on-host builds fight that machinery, so: **Decision: publish versioned images from CI; the host never builds.** -**Interim mode (implemented now, 2026-10-25):** until CI publishes images, -`lib/superbrain.sh` builds from source staged at `/federated/tmp/superbrain-src` -(tar-synced from the workstation; the exact command is in the script header). -For OTHER federated cores (any operator with repo access), -`deploy/federated/install.sh` packages the whole flow: preflights the suite -(Authelia required — the core tier is SSO-only — plus the fcore SMTP -credential source), stages the source by `git clone` (or `$SUPERBRAIN_SRC`), -installs `lib/superbrain.sh` + `services/superbrain/service` (with fixed-IP -collision checks and `SUPERBRAIN_*_IP` overrides), runs -`/federated/bin/installapp superbrain`, then verifies containers, the -Authelia client + claims policy, and the HTTPS login page. -Images are tagged `superbrain-app:local` / `superbrain-web:local`, `.env` -carries `IMAGE_VERSION_HOLD=1` so the generic `upgrade` flow skips the app -cleanly, and the service file's `CONTAINER=superbrain-app` matches the -first `image:` line of the generated compose so `upgrade_app`'s rewrite-sed -can never mangle it. **Updates** in interim mode run through -`deploy/federated/update.sh` (shipped inside the app dir): clone at REF → -pre-update pg_dump (5 retained) → sync (`.env`/data untouched) → refresh -lib+service files → build → force-recreate → health probe → automatic -rollback to the previous image tags on failure. A deliberate non-goal: an -in-app "update" button — the scratch containers have no docker socket and -must never get one (read_only + cap_drop ALL is the hardening model); -host-level operator action is the trust boundary until registry mode. -Switching to registry mode later = publish images, drop the -`build:` keys + hold marker, point `CONTAINER`/`VERSION` at the registry — -at which point the house `upgrade` flow and panel button take over and -update.sh retires. +**Registry mode (implemented 2026-10-29):** CI publishes the three images — +`federatedcomputer/superbrain-{app,web,migrate}` — on semver tags without a +`v` prefix (`.github/workflows/release.yml`, tag filter `[0-9]+.[0-9]+.[0-9]+`, +linux/amd64 + linux/arm64, one shared tag per release plus `:latest`; a +smoke job bootstraps a throwaway PostgreSQL with the migrate image — fresh +schema + full ledger + idempotent re-run — before anything is pushed). The +migrate image is self-contained: `db/` is baked in and its entrypoint +`db/bootstrap.sh` waits for postgres, applies `schema.sql` **as the +superbrain user** on an empty database (object ownership: migrations must +be able to ALTER those objects), then always runs the checksummed ledger — +so a server never needs the source tree, and fresh install and upgrade are +the same command. The dev compose runs the same bootstrap.sh. + +The generated app-dir compose pulls `federatedcomputer/superbrain-*: +${IMAGE_VERSION}` (`.env`, bookstack quoting style), no `build:` keys, no +`IMAGE_VERSION_HOLD`. The service file sets `CONTAINER= +federatedcomputer/superbrain-app` (must equal the first `image:` line's +repository — `upgrade_app` greps it) and `VERSION=`; the +`.env` keeps `IMAGE_VERSION=` as its ONLY line containing `VERSION=` +because `upgrade_app`'s rewrite-sed matches every occurrence. +`services/superbrain/upgrade/pre` (house hook mechanism, listmonk +pattern) takes a pg_dump into `.update-backups/` (5 retained) and pulls +web+migrate at the target version, since `upgrade_app` itself pulls only +the app image. + +Install/update for any core: `deploy/federated/install.sh` (preflights — +Authelia required, fcore SMTP credential, fixed-IP collisions with +`SUPERBRAIN_*_IP` overrides; installs lib/service/hook; runs +`/federated/bin/installapp superbrain`; verifies containers, Authelia +client + claims markers, HTTPS login) and `deploy/federated/update.sh` +(clone at ref → sync lib/service/hook with parse-checks and backups → +re-render compose via `render_superbrain_compose` → `/federated/bin/ +upgrade superbrain` → same-version compose safety pass → health probe). +The registry-mode app dir holds ONLY compose + .env — update.sh therefore +runs from a repo clone, not from the app dir (the source-mode +self-location of the old update.sh died with interim mode). + +A deliberate non-goal remains: an in-app "update" button — the scratch +containers have no docker socket and must never get one (read_only + +cap_drop ALL is the hardening model); host-level operator action (or the +house panel, which shells out on the host) is the trust boundary. + +History: interim source-build mode (2026-10-25..29) staged a tar-synced +source tree at `/federated/tmp/superbrain-src`, built `superbrain-{app, +web}:local` on the host, pinned `IMAGE_VERSION_HOLD=1`, and updated via a +source-rebuilding update.sh with image-retag rollback. Its installer +preflights and IP-collision logic carried over unchanged. The clobber +lesson also carried over: never `cp -a` a repo tree over the app dir — the +generated compose must survive (hit in production 2026-10-29). For the registry target: diff --git a/deploy/federated/install.sh b/deploy/federated/install.sh index 15ddc93..1096cdf 100755 --- a/deploy/federated/install.sh +++ b/deploy/federated/install.sh @@ -1,41 +1,49 @@ #!/usr/bin/env bash # -# Install Superbrain into a federated "core" suite host. +# Install Superbrain into a federated "core" suite host (REGISTRY mode). # -# For operators running their own copy of the federated suite who have -# access to this repository. Run ON THE CORE HOST as root: +# For operators running their own copy of the federated suite. On the +# CORE HOST, as root: # # git clone /tmp/superbrain-repo # sudo bash /tmp/superbrain-repo/deploy/federated/install.sh # +# No source is built or stored on the host: the three release images +# (federatedcomputer/superbrain-{app,web,migrate}, one shared version tag, +# linux/amd64 + linux/arm64) are pulled from Docker Hub, and the migrate +# image owns the database lifecycle (empty database => schema.sql as the +# superbrain user, then the checksummed migration ledger). +# # What it does: -# 1. Preflights the suite (installapp, functions.sh, /etc/federated, -# docker network 'core', Authelia — required because the core tier is -# Authelia-only — and the fcore SMTP credential sources). -# 2. Stages the source at /federated/tmp/superbrain-src (git clone of -# this repo, or a copy of $SUPERBRAIN_SRC when set). -# 3. Installs the suite integration files: -# lib-superbrain.sh -> /federated/lib/superbrain.sh -# service -> /federated/services/superbrain/service -# 4. Runs /federated/bin/installapp superbrain, which performs the house -# flow: config_superbrain (compose/.env/db/images), start_superbrain -# (DNS + operator seed), configsso_superbrain (Authelia client + -# claims policy), monitors and superpanel catalog. -# 5. Verifies the result and prints the operator's next steps. +# 1. Preflights the suite (installapp, functions.sh, /etc/federated, the +# core docker network, Authelia — REQUIRED because the core tier is +# Authelia-only — and the fcore SMTP credential for notification mail). +# 2. Gets the deploy files from a repo clone (or $SUPERBRAIN_SRC). +# 3. Installs the suite integration: /federated/lib/superbrain.sh, +# /federated/services/superbrain/{service,upgrade/pre}, with fixed-IP +# collision checks and SUPERBRAIN_*_IP overrides. +# 4. Runs /federated/bin/installapp superbrain (the standard house flow: +# compose/.env generation with TIER=core, image pulls, database + +# user on shared postgres, pdns record, Authelia client + claims +# policy, monitors, superpanel catalog). +# 5. Verifies and prints first-login steps. # # Environment overrides: # SUPERBRAIN_REPO git URL to clone (default: this repo's origin) # SUPERBRAIN_REF branch/tag to clone (default: main) -# SUPERBRAIN_SRC local directory to stage INSTEAD of cloning +# SUPERBRAIN_SRC local repo checkout to take the deploy files from # SUPERBRAIN_WEB_IP / SUPERBRAIN_APP_IP / SUPERBRAIN_MIGRATE_IP # fixed core-network IPs (default .93/.94/.95 — the # installer refuses if they are already allocated) # SKIP_VERIFY=1 skip the post-install HTTPS probe # +# Updates after install: sudo bash /deploy/federated/update.sh +# (syncs the service file's VERSION, then runs the house upgrade flow). +# set -euo pipefail REPO_DEFAULT="https://gitea.federated.computer/Federated_Computer/brain.git" -STAGE=/federated/tmp/superbrain-src +CLONE=/tmp/superbrain-install-src LIB_DST=/federated/lib/superbrain.sh SVC_DST_DIR=/federated/services/superbrain @@ -71,14 +79,7 @@ if [ ! -f /federated/apps/authelia/data/secrets/NOTIFIER_SMTP_PASSWORD ] \ die "cannot find the fcore SMTP credential (authelia NOTIFIER_SMTP_PASSWORD secret or superpanel .env). The notification engine's email channel needs it; see deploy/federated/STRATEGY.md." fi -# Source staging needs git unless a local source dir was given. -if [ -z "${SUPERBRAIN_SRC:-}" ]; then - command -v git >/dev/null || die "git not found (or set SUPERBRAIN_SRC=/path/to/source)" -fi - # --- 1. Fixed-IP allocation check --------------------------------------------- -# The compose file pins static IPs on the core network. Refuse collisions -# instead of letting docker fail obscurely mid-install. ip_taken() { # $1 = ip docker network inspect core -f '{{range .Containers}}{{.IPv4Address}} {{end}}' 2>/dev/null | grep -q "$1/" && return 0 grep -rqs "^INTERNAL_IP=$1\$" /federated/services/*/service && return 0 @@ -91,37 +92,36 @@ for ip in "$WEB_IP" "$APP_IP" "$MIGRATE_IP"; do fi done -# --- 2. Stage the source ------------------------------------------------------- +# --- 2. Get the deploy files ---------------------------------------------------- if [ -n "${SUPERBRAIN_SRC:-}" ]; then - [ -f "$SUPERBRAIN_SRC/main.go" ] || die "SUPERBRAIN_SRC=$SUPERBRAIN_SRC does not look like a superbrain source tree" - say "Staging source from $SUPERBRAIN_SRC" - rm -rf "$STAGE"; mkdir -p "$STAGE" - # Same payload as the workstation tar-sync in lib-superbrain.sh's header. - (cd "$SUPERBRAIN_SRC" && tar cf - --exclude=node_modules --exclude=.next --exclude=.git \ - main.go go.mod go.sum Dockerfile internal db web deploy) | tar xf - -C "$STAGE" + SRC="$SUPERBRAIN_SRC" + [ -f "$SRC/deploy/federated/lib-superbrain.sh" ] || die "SUPERBRAIN_SRC=$SRC lacks deploy/federated files" else + command -v git >/dev/null || die "git not found (or set SUPERBRAIN_SRC=/path/to/repo)" REPO="${SUPERBRAIN_REPO:-$REPO_DEFAULT}" REF="${SUPERBRAIN_REF:-main}" - say "Cloning $REPO ($REF) into $STAGE" - rm -rf "$STAGE" - git clone --depth 1 --branch "$REF" "$REPO" "$STAGE" \ + say "Cloning $REPO ($REF) for the deploy files" + rm -rf "$CLONE" + git clone --depth 1 --branch "$REF" "$REPO" "$CLONE" \ || die "git clone failed — check repository access/credentials" + SRC="$CLONE" fi -for f in main.go Dockerfile db/schema.sql web/Dockerfile \ - deploy/federated/lib-superbrain.sh deploy/federated/service; do - [ -e "$STAGE/$f" ] || die "staged source is missing $f — wrong repo/ref?" +for f in deploy/federated/lib-superbrain.sh deploy/federated/service deploy/federated/upgrade-pre; do + [ -e "$SRC/$f" ] || die "source is missing $f — wrong repo/ref?" done -# --- 3. Install the suite integration files ------------------------------------ +# --- 3. Install the suite integration files -------------------------------------- say "Installing suite files" if [ -f "$LIB_DST" ]; then cp -a "$LIB_DST" "$LIB_DST.bak-$(date +%Y%m%d-%H%M%S)" warn "backed up an existing $LIB_DST" fi -cp "$STAGE/deploy/federated/lib-superbrain.sh" "$LIB_DST" -mkdir -p "$SVC_DST_DIR" +cp "$SRC/deploy/federated/lib-superbrain.sh" "$LIB_DST" +mkdir -p "$SVC_DST_DIR/upgrade" [ -f "$SVC_DST_DIR/service" ] && cp -a "$SVC_DST_DIR/service" "$SVC_DST_DIR/service.bak-$(date +%Y%m%d-%H%M%S)" -cp "$STAGE/deploy/federated/service" "$SVC_DST_DIR/service" +cp "$SRC/deploy/federated/service" "$SVC_DST_DIR/service" +cp "$SRC/deploy/federated/upgrade-pre" "$SVC_DST_DIR/upgrade/pre" +chmod 755 "$SVC_DST_DIR/upgrade/pre" # Apply IP overrides (defaults match the shipped files, so this is a no-op # unless the operator chose different addresses). INTERNAL_IP in the service @@ -135,11 +135,12 @@ if [ "$WEB_IP" != "192.168.0.93" ] || [ "$APP_IP" != "192.168.0.94" ] || [ "$MIG fi bash -n "$LIB_DST" || die "$LIB_DST does not parse — refusing to continue" -# --- 4. House install ------------------------------------------------------------ -say "Running /federated/bin/installapp superbrain (builds images — several minutes)" -/federated/bin/installapp superbrain || die "installapp failed; inspect the output above. The staged source and suite files remain in place; fix the cause and re-run installapp (or uninstall and re-run this script)." +# --- 4. House install ------------------------------------------------------------- +WANT_VERSION=$(sed -n 's/^VERSION=//p' "$SVC_DST_DIR/service" | tr -d '"' | head -1) +say "Running /federated/bin/installapp superbrain (pulls federatedcomputer/superbrain-*:$WANT_VERSION)" +/federated/bin/installapp superbrain || die "installapp failed; inspect the output above. The suite files remain in place; fix the cause and re-run installapp (or uninstall and re-run this script)." -# --- 5. Verify --------------------------------------------------------------------- +# --- 5. Verify ------------------------------------------------------------------------ DOMAIN_HOST=$(grep -m1 '^DOMAIN=' /etc/federated | cut -d'"' -f2) [ -n "$DOMAIN_HOST" ] || DOMAIN_HOST=$(sed -n 's/^DOMAIN=//p' /etc/federated | tr -d '"' | head -1) @@ -163,15 +164,15 @@ if [ "${SKIP_VERIFY:-0}" != 1 ] && [ -n "$DOMAIN_HOST" ]; then [ "$code" = 200 ] && { ok=1; break; } sleep 3 done - [ "$ok" = 1 ] || { warn "https://superbrain.$DOMAIN_HOST/login did not answer 200 yet (traefik may still be provisioning the certificate)"; } + [ "$ok" = 1 ] || warn "https://superbrain.$DOMAIN_HOST/login did not answer 200 yet (traefik may still be provisioning the certificate)" fi [ "$fail" = 0 ] || warn "install completed with warnings — review them before use" cat < web 192.168.0.93-style fixed IP $WEB_IP) + App: https://superbrain.$DOMAIN_HOST (traefik -> web at $WEB_IP) Data: shared suite postgres, database 'superbrain' Tier: TIER=core (Authelia-only; password login/signup/reset are disabled) @@ -189,8 +190,8 @@ $(say "Superbrain installed") Other users are provisioned upstream (Superpanel -> LDAP -> Authelia) and appear in Superbrain on their first SSO login. - Upgrades (interim source-build mode): one command on the host — - sudo bash /federated/apps/superbrain/deploy/federated/update.sh [git-ref] - (clone -> pg_dump -> rebuild -> recreate -> health probe -> auto-rollback - on failure). See deploy/federated/STRATEGY.md. + Updates: bump VERSION in $SVC_DST_DIR/service (or sync it from a repo + clone) and run /federated/bin/upgrade superbrain — or one command: + git clone /tmp/superbrain-repo + sudo bash /tmp/superbrain-repo/deploy/federated/update.sh [git-ref] EOF diff --git a/deploy/federated/lib-superbrain.sh b/deploy/federated/lib-superbrain.sh index a27bf98..79e0b1f 100644 --- a/deploy/federated/lib-superbrain.sh +++ b/deploy/federated/lib-superbrain.sh @@ -2,29 +2,32 @@ # # Superbrain Service # -# Superbrain is a Go API + Next.js web stack. Unlike most suite apps it is -# currently built FROM SOURCE on the host (interim mode, until CI publishes -# federatedcomputer/superbrain-{app,web,migrate} registry images): +# Superbrain is a Go API + Next.js web stack, installed from REGISTRY +# IMAGES (no source on the host): # -# 1. Sync the release source tree to the staging dir (from the workstation): -# tar czf - --exclude=node_modules --exclude=.next \ -# main.go go.mod go.sum Dockerfile internal db web \ -# | ssh core 'rm -rf /federated/tmp/superbrain-src \ -# && mkdir -p /federated/tmp/superbrain-src \ -# && tar xzf - -C /federated/tmp/superbrain-src' -# 2. /federated/bin/installapp superbrain +# federatedcomputer/superbrain-app (Go API, scratch) +# federatedcomputer/superbrain-web (Next.js standalone) +# federatedcomputer/superbrain-migrate (db/ baked in: bootstrap.sh applies +# schema.sql on an empty database, +# then always runs the ledger) # -# config_superbrain() copies the staged source into the app dir and builds -# superbrain-app:local / superbrain-web:local. The .env carries -# IMAGE_VERSION_HOLD=1 so the generic `upgrade` flow (which pulls registry -# images) skips superbrain until real image releases exist, and the service -# file's CONTAINER matches the first image: line of the generated compose so -# upgrade_app()'s image-rewrite sed can never mangle the file. +# All three share ONE version tag per release (IMAGE_VERSION in .env, +# VERSION in the service file — the generic `upgrade` flow compares them, +# pulls, btrfs-snapshots and rewrites .env). Images are published by the +# repo's release workflow on semver tags without a v prefix (1.0.0). +# Install is the standard house flow: /federated/bin/installapp superbrain. +# +# upgrade_app() pulls only the FIRST image: line of the compose (the app); +# the services/superbrain/upgrade/pre hook pulls web+migrate at the target +# version before the redeploy. CONTAINER in the service file must equal +# that first image's repository, and the web container must be named +# exactly "superbrain" (upgrade_app probes it by name). # # Database: the shared suite postgres (container "postgresql", -# postgresql.$DOMAIN on the core network). A fresh database is bootstrapped -# with db/schema.sql applied AS the superbrain user (object ownership!), then -# the migrate one-shot runs the checksummed ledger on top — migrations are NOT +# postgresql.$DOMAIN on the core network). The migrate image owns schema +# lifecycle end to end: empty database => schema.sql applied AS the +# superbrain user (object ownership! migrations must be able to ALTER +# these objects), then the checksummed ledger on top — migrations are NOT # a full schema by themselves (see db/check-convergence.sh in the repo). # # Networking: fixed core IPs — web 192.168.0.93 (traefik target; container @@ -40,44 +43,26 @@ PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sb get_appvars . /etc/federated -SUPERBRAIN_SRC="/federated/tmp/superbrain-src" SUPERBRAIN_WEB_IP="192.168.0.93" SUPERBRAIN_APP_IP="192.168.0.94" SUPERBRAIN_MIGRATE_IP="192.168.0.95" +# Release to install; the generic `upgrade` flow keeps .env in step with the +# service file's VERSION afterwards. +SUPERBRAIN_IMAGE_VERSION="1.0.0" -config_superbrain() { - echo -ne "* Configuring Superbrain container.." - - [ -f "$SUPERBRAIN_SRC/main.go" ] || failcheck "superbrain source not staged at $SUPERBRAIN_SRC (see lib/superbrain.sh header for the sync command)" - - mkdir -p /federated/apps/superbrain - cp -a "$SUPERBRAIN_SRC/." /federated/apps/superbrain/ - - SUPERBRAIN_DB_PASSWORD=$(create_password) - SUPERBRAIN_AUTH_SECRET=$(create_password) - SUPERBRAIN_ENCRYPTION_KEY=$(create_password) - - # Shared house SMTP sender credential (fcore) for the notification - # engine's email channel. Reuse the secret other apps already hold; never - # generate a new one — the mail server is LDAP-provisioned and - # `setup email add` does not exist there (ACCOUNT_PROVISIONER is not - # FILE). Verified end-to-end 2026-10-26: net/smtp STARTTLS + AUTH PLAIN - # to mail.$DOMAIN:587 from the core network delivers with a per-app From - # address (sender != login user is allowed; authelia does the same). - if [ -f /federated/apps/authelia/data/secrets/NOTIFIER_SMTP_PASSWORD ]; then - SUPERBRAIN_SMTP_PASSWORD=$(cat /federated/apps/authelia/data/secrets/NOTIFIER_SMTP_PASSWORD) - else - SUPERBRAIN_SMTP_PASSWORD=$(sed -n 's/^EMAIL_HOST_PASSWORD=//p' /federated/apps/superpanel/.env | tail -1) - fi - [ -n "$SUPERBRAIN_SMTP_PASSWORD" ] || failcheck "could not find the fcore SMTP password (authelia secret or superpanel .env)" - +# render_superbrain_compose writes the app-dir compose file. Called by +# config_superbrain (install) and by deploy/federated/update.sh after a lib +# sync, so a release that changes the compose shape can be applied without +# reinstalling. Requires DOMAIN, EXTERNALIP (get_appvars / /etc/federated) +# and the SUPERBRAIN_*_IP constants below. +render_superbrain_compose() { # app is deliberately the FIRST service with an image: key — upgrade_app() - # reads the first image: line and compares it to CONTAINER in the service file. + # reads the first image: line and compares it to CONTAINER in the service + # file (federatedcomputer/superbrain-app). cat > /federated/apps/superbrain/docker-compose.yml < /federated/apps/superbrain/.env </dev/null docker exec postgresql psql -U postgres -c "CREATE DATABASE superbrain" &>/dev/null docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE superbrain TO superbrain" &>/dev/null docker exec postgresql psql -U postgres -c "ALTER DATABASE superbrain OWNER TO superbrain" &>/dev/null - # Bootstrap a fresh database with schema.sql, applied AS the superbrain - # user so every object is owned by it (later migrations must be able to - # ALTER these). Empty-database gate: never re-runs over live data. The - # migrate one-shot then records the ledger chain on top at first start. - SB_TABLES=$(docker exec postgresql psql -U postgres -d superbrain -t -A -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public'" 2>/dev/null) - if [ "${SB_TABLES:-0}" = "0" ]; then - docker exec -e PGPASSWORD="$SUPERBRAIN_DB_PASSWORD" -i postgresql \ - psql -h 127.0.0.1 -U superbrain -d superbrain -v ON_ERROR_STOP=1 -q \ - < /federated/apps/superbrain/db/schema.sql || failcheck "superbrain schema.sql failed to apply" - fi - - # Build app+web images from the staged source (a few minutes on first - # build, layer-cached afterwards). - echo -ne "\n* Building superbrain images (this takes a few minutes)..\n" - (cd /federated/apps/superbrain && docker compose build) || failcheck "superbrain image build failed" + # Pull the release images up front so registry/auth problems fail here + # with a clear message instead of mid-`up`. + echo -ne "\n* Pulling superbrain images ($SUPERBRAIN_IMAGE_VERSION)..\n" + (cd /federated/apps/superbrain && docker compose pull) || failcheck "could not pull federatedcomputer/superbrain-*:$SUPERBRAIN_IMAGE_VERSION - does the release exist on Docker Hub?" echo -ne "done.\n" } @@ -267,7 +270,7 @@ uninstall_superbrain() { echo -ne "* Uninstalling superbrain container.." docker compose -f /federated/apps/superbrain/docker-compose.yml -p superbrain down &>/dev/null - docker image rm superbrain-app:local superbrain-web:local &>/dev/null || true + docker images --format '{{.Repository}}:{{.Tag}}' | grep '^federatedcomputer/superbrain-' | xargs -r docker image rm &>/dev/null || true docker exec postgresql psql -U postgres -c "DROP DATABASE IF EXISTS superbrain" &>/dev/null docker exec postgresql psql -U postgres -c "DROP USER IF EXISTS superbrain" &>/dev/null diff --git a/deploy/federated/service b/deploy/federated/service index d8a08a6..b354fee 100644 --- a/deploy/federated/service +++ b/deploy/federated/service @@ -1,8 +1,8 @@ NAME=superbrain DESCRIPTION="Bookmark & Knowledge Base" DOCS=https://github.com/andrew/superbrain -CONTAINER=superbrain-app -VERSION=0.1.0 +CONTAINER=federatedcomputer/superbrain-app +VERSION=1.0.0 INTERNAL_IP=192.168.0.93 DEPENDS="postgresql" PORTS=3000 diff --git a/deploy/federated/update.sh b/deploy/federated/update.sh index 5808556..0774251 100755 --- a/deploy/federated/update.sh +++ b/deploy/federated/update.sh @@ -1,131 +1,93 @@ #!/usr/bin/env bash # -# Update Superbrain on a federated core host (interim source-build mode). +# Update Superbrain on a federated core host (REGISTRY mode). # -# sudo bash /federated/apps/superbrain/deploy/federated/update.sh [git-ref] +# The app dir holds only compose + .env (no source), so this script runs +# from a repo clone: # -# or with overrides: -# sudo SUPERBRAIN_REF=v1.2.3 SUPERBRAIN_REPO= bash .../update.sh +# git clone /tmp/superbrain-repo +# sudo bash /tmp/superbrain-repo/deploy/federated/update.sh [git-ref] # -# What it does, in house-safety order: -# 1. Re-executes itself from /tmp (the update overwrites the app dir this -# script lives in — never pull the rug out mid-execution). -# 2. Clones the repo at REF (default: main) into the staging dir. -# 3. Records the current image ids and takes a compressed pre-update -# pg_dump (keeps the last 5). -# 4. Syncs the source into the app dir (.env, backups and data are -# untouched — only tracked files are overwritten), refreshes the suite -# integration files (lib + service), rebuilds the images, and -# recreates the stack (the migrate one-shot applies new migrations). -# 5. Health-probes app + web. On ANY failure: retags the previous images, -# recreates, and points at the dump — the update is roll-backable. +# What it does: +# 1. Clones the repo at REF (default main) — or uses $SUPERBRAIN_SRC. +# 2. Syncs the suite integration files (lib, service file, upgrade/pre +# hook) with backups and a parse check — the service file carries the +# desired VERSION, which is how a release reaches the host. +# 3. Re-renders the app-dir compose from the fresh lib (so a release that +# changes the compose shape applies without reinstalling). +# 4. Runs the house flow: /federated/bin/upgrade superbrain — version +# compare, pre hook (pg_dump + pull all three images), btrfs snapshot, +# redeploy, .env IMAGE_VERSION rewrite, superpanel refresh. +# 5. compose up -d safety pass (applies same-version compose-only +# changes), then health-probes app + web. # -# Endgame note: once CI publishes registry images -# (federatedcomputer/superbrain-{app,web,migrate}, see STRATEGY.md), the -# generic house `upgrade` flow and the panel button supersede this script; -# drop IMAGE_VERSION_HOLD from .env at that point. +# Environment: SUPERBRAIN_REPO, SUPERBRAIN_REF (or $1), SUPERBRAIN_SRC. # set -euo pipefail +REPO_DEFAULT="https://gitea.federated.computer/Federated_Computer/brain.git" APP_DIR=/federated/apps/superbrain -STAGE=/federated/tmp/superbrain-src -REPO="${SUPERBRAIN_REPO:-https://gitea.federated.computer/Federated_Computer/brain.git}" +CLONE=/tmp/superbrain-update-src REF="${1:-${SUPERBRAIN_REF:-main}}" -DUMPS="$APP_DIR/.update-backups" say() { printf '\033[1;34m==>\033[0m %s\n' "$*"; } die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; } -# --- 0. Self-relocation ------------------------------------------------------ -# The synced tree overwrites deploy/federated/update.sh while we run; bash -# reads scripts incrementally, so continue from a private copy. -if [ "${SUPERBRAIN_UPDATE_REEXEC:-0}" != "1" ]; then - SELF=/tmp/superbrain-update-$$ - cp "$0" "$SELF" - SUPERBRAIN_UPDATE_REEXEC=1 exec bash "$SELF" "$@" -fi - -# --- 1. Preflights ------------------------------------------------------------- +# --- 1. Preflights + source ---------------------------------------------------- [ "$(id -u)" = 0 ] || die "run as root on the core host" -[ -d "$APP_DIR" ] || die "$APP_DIR missing — is superbrain installed? (deploy/federated/install.sh)" -command -v git >/dev/null || die "git not found" -docker container inspect superbrain-app >/dev/null 2>&1 || die "superbrain-app container unknown to docker" +[ -x /federated/bin/upgrade ] || die "/federated/bin/upgrade missing — not a federated suite host?" +[ -f "$APP_DIR/docker-compose.yml" ] && [ -f "$APP_DIR/.env" ] \ + || die "$APP_DIR does not look installed (compose/.env missing) — run deploy/federated/install.sh first" -# --- 2. Clone the requested revision -------------------------------------------- -say "Fetching $REPO @ $REF" -rm -rf "$STAGE" -if ! git clone --quiet --depth 1 --branch "$REF" "$REPO" "$STAGE" 2>/dev/null; then - # REF may be a commit sha: full clone, then detach. - git clone --quiet "$REPO" "$STAGE" || die "git clone failed — check repository access" - git -C "$STAGE" checkout --quiet "$REF" || die "ref $REF not found in $REPO" +if [ -n "${SUPERBRAIN_SRC:-}" ]; then + SRC="$SUPERBRAIN_SRC" + [ -f "$SRC/deploy/federated/lib-superbrain.sh" ] || die "SUPERBRAIN_SRC lacks deploy/federated files" +else + command -v git >/dev/null || die "git not found (or set SUPERBRAIN_SRC=/path/to/repo)" + say "Fetching ${SUPERBRAIN_REPO:-$REPO_DEFAULT} @ $REF" + rm -rf "$CLONE" + if ! git clone --quiet --depth 1 --branch "$REF" "${SUPERBRAIN_REPO:-$REPO_DEFAULT}" "$CLONE" 2>/dev/null; then + git clone --quiet "${SUPERBRAIN_REPO:-$REPO_DEFAULT}" "$CLONE" || die "git clone failed — check repository access" + git -C "$CLONE" checkout --quiet "$REF" || die "ref $REF not found" + fi + SRC="$CLONE" fi -for f in main.go Dockerfile db/schema.sql web/Dockerfile docker-compose.yml; do - [ -e "$STAGE/$f" ] || die "staged source is missing $f — wrong repo/ref?" -done -NEW_REV=$(git -C "$STAGE" rev-parse --short HEAD) -# The app dir is the Docker build context and the suite's source of truth — -# keep the clone's history out of it (depth-1 or not, it is dead weight). -rm -rf "$STAGE/.git" -say "Updating to revision $NEW_REV" +NEW_REV=$(git -C "$SRC" rev-parse --short HEAD 2>/dev/null || echo "$REF") -# --- 3. Rollback anchors: current image ids + database dump ---------------------- -OLD_APP_IMAGE=$(docker image inspect superbrain-app:local -f '{{.Id}}' 2>/dev/null || true) -OLD_WEB_IMAGE=$(docker image inspect superbrain-web:local -f '{{.Id}}' 2>/dev/null || true) -mkdir -p "$DUMPS"; chmod 700 "$DUMPS" -DUMP="$DUMPS/pre-update-$(date +%Y%m%d-%H%M%S).sql.gz" -say "Backing up the database to $DUMP" -docker exec postgresql pg_dump -U postgres -d superbrain | gzip > "$DUMP" \ - || die "database backup failed — refusing to update without one" -# gzip writes a ~30-byte header even for empty input: a real dump is bigger. -[ "$(stat -c%s "$DUMP")" -gt 100 ] || die "database dump is suspiciously empty — refusing to update" -ls -1t "$DUMPS"/pre-update-*.sql.gz 2>/dev/null | tail -n +6 | xargs -r rm -f +# --- 2. Sync suite files (parse-checked, backed up) ------------------------------ +say "Syncing suite integration files (revision $NEW_REV)" +LIB=/federated/lib/superbrain.sh +cp "$SRC/deploy/federated/lib-superbrain.sh" /tmp/lib-superbrain.sh.new +bash -n /tmp/lib-superbrain.sh.new || die "staged lib-superbrain.sh does not parse — aborting" +[ -f "$LIB" ] && cp -a "$LIB" "$LIB.bak-$NEW_REV" +mv /tmp/lib-superbrain.sh.new "$LIB" -rollback() { - say "ROLLING BACK to previous images" - [ -n "$OLD_APP_IMAGE" ] && docker tag "$OLD_APP_IMAGE" superbrain-app:local - [ -n "$OLD_WEB_IMAGE" ] && docker tag "$OLD_WEB_IMAGE" superbrain-web:local - (cd "$APP_DIR" && docker compose -p superbrain up -d --force-recreate app web migrate) || true - die "update failed — previous images restored. Database dump (if needed): $DUMP" -} +mkdir -p /federated/services/superbrain/upgrade +[ -f /federated/services/superbrain/service ] && cp -a /federated/services/superbrain/service "/federated/services/superbrain/service.bak-$NEW_REV" +cp "$SRC/deploy/federated/service" /federated/services/superbrain/service +cp "$SRC/deploy/federated/upgrade-pre" /federated/services/superbrain/upgrade/pre +chmod 755 /federated/services/superbrain/upgrade/pre -# --- 4. Sync, refresh suite files, build, recreate -------------------------------- -# Payload-sync ONLY the tracked source paths (same list as the installer's -# staging). Never `cp -a` the whole clone over the app dir: the app dir's -# docker-compose.yml is GENERATED by config_superbrain (fixed IPs, core -# network, env_file) and the repo's dev compose would clobber it — hit in -# production 2026-10-29, caught by the rollback. .env, .update-backups and -# the generated compose are untouchable here. -say "Syncing source into $APP_DIR (generated compose/.env/data untouched)" -(cd "$STAGE" && tar cf - --exclude=node_modules --exclude=.next \ - main.go go.mod go.sum Dockerfile .dockerignore internal db web deploy) \ - | tar xf - -C "$APP_DIR" - -# Sanity: the app dir must still hold the GENERATED federated compose -# (config_superbrain's), not the repo's dev stack. +# --- 3. Re-render the compose from the fresh lib ---------------------------------- +say "Re-rendering the app compose" +bash -c '. /federated/lib/functions.sh; . /federated/lib/superbrain.sh; render_superbrain_compose' \ + || die "compose re-render failed" grep -q "container_name: superbrain-app" "$APP_DIR/docker-compose.yml" \ - || die "$APP_DIR/docker-compose.yml is not the generated federated compose — refusing to build against it" + || die "rendered compose is missing the app service — aborting" +(cd "$APP_DIR" && docker compose -p superbrain config >/dev/null) \ + || die "rendered compose does not parse — aborting" -# Keep the house integration in step with the repo (both are backed up by -# install.sh conventions; a failing lib parse aborts BEFORE anything else). -if [ -f "$STAGE/deploy/federated/lib-superbrain.sh" ]; then - cp "$STAGE/deploy/federated/lib-superbrain.sh" /tmp/lib-superbrain.sh.new - bash -n /tmp/lib-superbrain.sh.new || die "staged lib-superbrain.sh does not parse — aborting" - [ -f /federated/lib/superbrain.sh ] && cp -a /federated/lib/superbrain.sh "/federated/lib/superbrain.sh.bak-$NEW_REV" - mv /tmp/lib-superbrain.sh.new /federated/lib/superbrain.sh -fi -if [ -f "$STAGE/deploy/federated/service" ]; then - mkdir -p /federated/services/superbrain - [ -f /federated/services/superbrain/service ] && cp -a /federated/services/superbrain/service "/federated/services/superbrain/service.bak-$NEW_REV" - cp "$STAGE/deploy/federated/service" /federated/services/superbrain/service -fi +# --- 4. House upgrade flow ---------------------------------------------------------- +WANT_VERSION=$(sed -n 's/^VERSION=//p' /federated/services/superbrain/service | tr -d '"' | head -1) +HAVE_VERSION=$(sed -n 's/^IMAGE_VERSION=//p' "$APP_DIR/.env" | tr -d '"' | tail -1) +say "Running the house upgrade flow (have $HAVE_VERSION, service file wants $WANT_VERSION)" +/federated/bin/upgrade superbrain || die "upgrade failed — inspect the output above" -say "Building images (several minutes on a cold cache)" -(cd "$APP_DIR" && docker compose build) || rollback +# --- 5. Same-version safety pass + health probe -------------------------------------- +# bin/upgrade no-ops when the version is unchanged; if this release only +# changed the compose shape, apply it now (idempotent otherwise). +(cd "$APP_DIR" && docker compose -p superbrain up -d) || die "compose up failed after upgrade" -say "Recreating the stack (migrations run automatically)" -(cd "$APP_DIR" && docker compose -p superbrain up -d --force-recreate app web migrate) || rollback - -# --- 5. Health probe ---------------------------------------------------------------- say "Waiting for health" healthy=0 for _ in $(seq 1 60); do @@ -134,19 +96,10 @@ for _ in $(seq 1 60); do if [ "$a" = healthy ] && [ "$w" = healthy ]; then healthy=1; break; fi sleep 3 done -[ "$healthy" = 1 ] || { docker logs --tail 30 superbrain-app >&2 || true; rollback; } +if [ "$healthy" != 1 ]; then + docker logs --tail 30 superbrain-app >&2 || true + die "stack did not become healthy — the pre-upgrade dump is in $APP_DIR/.update-backups, and upgrade_app took a btrfs snapshot of /federated" +fi -say "Superbrain updated to $NEW_REV" -cat < "$DUMP" +ls -1t .update-backups/pre-upgrade-*.sql.gz 2>/dev/null | tail -n +6 | xargs -r rm -f + +echo "* Pulling superbrain images at $NEW" +IMAGE_VERSION="$NEW" docker compose pull app web migrate diff --git a/docker-compose.yml b/docker-compose.yml index 836922b..9abb8c2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,7 +29,7 @@ services: DB_NAME: superbrain volumes: - ./db:/db:ro - command: [sh, /db/migrate.sh] + command: [sh, /db/bootstrap.sh] networks: [backend] app: