From bffdec995ffd30541022743086dcf7132abc209a Mon Sep 17 00:00:00 2001 From: rodrigopavezi Date: Tue, 17 Nov 2026 05:39:48 -0300 Subject: [PATCH] fix: keep Caddy up across app-only seeder releases On the pull/release path every release recreated the web (Caddy) container, because the web image baked the commit, so every app client dropped with a bare 1006 and nothing held its redial. release.yml now builds a separately pinned, signed varanda-caddy image (rebuilt only when Dockerfile.caddy changes) and records its digest in /app/caddy.json inside the signed seeder image; release.json is unchanged, so installed servers keep accepting releases. In the full profile update.sh runs web from that image, binds the Caddyfile from a content-addressed path and serves www through an atomically swapped link, brings up seeder and account first, and recreates web only when the Caddy digest or the Caddyfile changed. The health gate and rollback are kept; rollback restores the previous Caddy. A release without caddy.json runs in the old mode. deploy.sh now stages the app beside www and merges it file by file with renames (index.html last) instead of emptying www while Caddy serves it. --- .github/workflows/release.yml | 107 +++++++++- .gitignore | 1 + README.md | 6 +- apps/cli/test/deploy.test.js | 108 +++++++++- apps/cli/test/release.test.js | 84 +++++++- apps/cli/test/update.test.js | 189 +++++++++++++++++ deploy/seeder/Dockerfile | 15 ++ deploy/seeder/compose.release.web.yaml | 2 + deploy/seeder/compose.web.yaml | 9 +- deploy/seeder/deploy.sh | 83 ++++++-- deploy/seeder/update.sh | 257 ++++++++++++++++++++---- docs/changelog/fix-caddy-stays-up.md | 1 + docs/verification/fix-caddy-stays-up.md | 30 +++ 13 files changed, 813 insertions(+), 79 deletions(-) create mode 100644 docs/changelog/fix-caddy-stays-up.md create mode 100644 docs/verification/fix-caddy-stays-up.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ddd2c57d2..18896dcc6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,15 @@ # back. Servers pull and verify; nothing here connects to a server. The # channel stable moves only in promote.yml. # +# The Caddy image (ghcr.io/varanda-org/varanda-caddy, from +# deploy/seeder/Dockerfile.caddy) is built only when that Dockerfile changes: +# it is tagged caddy-, and an existing tag is +# reused when its digest verifies under this workflow's identity and carries +# the same Dockerfile hash label. The seeder pins it by digest in +# /app/caddy.json (release.json keeps its format, which installed servers +# check), so update.sh recreates Caddy only when that digest or the Caddyfile +# changes. It has no channel tag: servers pull it by digest. +# # Runs are queued per ref and a newer push replaces a pending run, so a main # commit can end up with no image; a manual run builds only the tip. # @@ -29,8 +38,9 @@ # environment without any protection the first time a job names it. # 2. Settings > Secrets and variables > Actions > Variables: # VARANDA_RELEASE = true (any other value pauses releases). -# 3. After the first run: organization Packages > varanda-seeder and -# varanda-web > Package settings > Change visibility > Public. +# 3. After the first run: organization Packages > varanda-seeder, +# varanda-web and varanda-caddy > Package settings > Change visibility > +# Public. # 4. Only after step 1: VARANDA_PROMOTE = true enables promote.yml. name: release @@ -222,6 +232,7 @@ jobs: env: SEEDER_REPO: ghcr.io/varanda-org/varanda-seeder WEB_REPO: ghcr.io/varanda-org/varanda-web + CADDY_REPO: ghcr.io/varanda-org/varanda-caddy COSIGN_ISSUER: https://token.actions.githubusercontent.com COSIGN_IDENTITY: https://github.com/Varanda-org/varanda/.github/workflows/release.yml@refs/heads/main steps: @@ -249,8 +260,15 @@ jobs: echo "::error::deploy/seeder/cosign.ref inválido (ghcr.io/sigstore/cosign/cosign:v@sha256:<64 hex>)" exit 1 fi + caddy_hash="$(sha256sum deploy/seeder/Dockerfile.caddy)" + caddy_hash="${caddy_hash%% *}" + if ! [[ "$caddy_hash" =~ ^[0-9a-f]{64}$ ]]; then + echo "::error::sha256 de deploy/seeder/Dockerfile.caddy ilegível" + exit 1 + fi { echo "SEQ=$seq" + echo "CADDY_TAG=caddy-$caddy_hash" echo "COSIGN_IMAGE=$cosign_ref" echo "DOCKER_CONFIG=$RUNNER_TEMP/docker-config" } >> "$GITHUB_ENV" @@ -275,7 +293,10 @@ jobs: # rebuilt from scratch, both images, overwriting the sha- tags. # A registry that does not answer fails the step instead: an outage must # not lead to a second build of a released commit. The image is verified - # before it is ever run. + # before it is ever run. A release reused whole reuses the Caddy digest + # its caddy.json names (verified the same way); otherwise the Caddy image + # of caddy- is reused when it verifies and its + # label names the same hash, and is built when it does not. - name: Reuse a release already signed for this commit run: | set -Eeuo pipefail @@ -308,12 +329,13 @@ jobs: } tag="sha-$GITHUB_SHA" re='^\{"v":1,"commit":"([0-9a-f]{40})","seq":([1-9][0-9]{0,9}),"web":"ghcr\.io/varanda-org/varanda-web@(sha256:[0-9a-f]{64})"\}$' - # Prints " " of a release this workflow + caddy_re='^\{"v":1,"caddy":"ghcr\.io/varanda-org/varanda-caddy@(sha256:[0-9a-f]{64})"\}$' + # Prints " " of a release this workflow # already signed for this commit. Returns 1 when there is none to # reuse (build) and 2 when the registry did not answer (the step # fails: an outage must not produce a second build of a commit). signed_release() { - local seeder release web found_web + local seeder release web found_web caddy_json caddy found_caddy seeder="$(digest_of "$SEEDER_REPO:$tag")" || return 2 [ -n "$seeder" ] || return 1 cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$SEEDER_REPO@$seeder" > /dev/null || return 1 @@ -325,7 +347,27 @@ jobs: found_web="$(digest_of "$WEB_REPO@$web")" || return 2 [ "$found_web" = "$web" ] || return 1 cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$WEB_REPO@$web" > /dev/null || return 1 - printf '%s %s\n' "$seeder" "$web" + caddy_json="$(docker run --rm --network none --entrypoint cat "$SEEDER_REPO@$seeder" /app/caddy.json)" || return 1 + [[ "$caddy_json" =~ $caddy_re ]] || return 1 + caddy="${BASH_REMATCH[1]}" + found_caddy="$(digest_of "$CADDY_REPO@$caddy")" || return 2 + [ "$found_caddy" = "$caddy" ] || return 1 + cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$CADDY_REPO@$caddy" > /dev/null || return 1 + printf '%s %s %s\n' "$seeder" "$web" "$caddy" + } + # Prints the digest of caddy- when this + # workflow signed it and its label names the same hash. Returns 1 + # when there is none to reuse (build) and 2 when the registry did + # not answer. + signed_caddy() { + local caddy label + caddy="$(digest_of "$CADDY_REPO:$CADDY_TAG")" || return 2 + [ -n "$caddy" ] || return 1 + cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$CADDY_REPO@$caddy" > /dev/null || return 1 + docker pull --quiet "$CADDY_REPO@$caddy" > /dev/null || return 1 + label="$(docker image inspect -f '{{index .Config.Labels "org.varanda.dockerfile-caddy"}}' "$CADDY_REPO@$caddy")" || return 1 + [ "caddy-$label" = "$CADDY_TAG" ] || return 1 + printf '%s\n' "$caddy" } rc=0 found="$(signed_release)" || rc=$? @@ -333,21 +375,39 @@ jobs: echo "::error::o registro não respondeu sobre $tag; nada foi construído nem assinado, rode de novo mais tarde" exit 1 elif [ "$rc" -eq 0 ]; then - read -r seeder web <<< "$found" + read -r seeder web caddy <<< "$found" echo "::notice::$SEEDER_REPO:$tag já foi publicado e assinado pelo release; nada é construído nem assinado de novo" { echo "RELEASE_SOURCE=reused" echo "VERIFIED_SEEDER_DIGEST=$seeder" echo "VERIFIED_WEB_DIGEST=$web" + echo "CADDY_SOURCE=reused" + echo "VERIFIED_CADDY_DIGEST=$caddy" } >> "$GITHUB_ENV" else echo "::notice::nenhuma versão assinada de $tag; as duas imagens são construídas agora" echo "RELEASE_SOURCE=build" >> "$GITHUB_ENV" + rc=0 + caddy="$(signed_caddy)" || rc=$? + if [ "$rc" -eq 2 ]; then + echo "::error::o registro não respondeu sobre $CADDY_REPO:$CADDY_TAG; rode de novo mais tarde" + exit 1 + elif [ "$rc" -eq 0 ]; then + echo "::notice::$CADDY_REPO:$CADDY_TAG já foi assinado pelo release; a imagem do Caddy é reaproveitada" + { + echo "CADDY_SOURCE=reused" + echo "VERIFIED_CADDY_DIGEST=$caddy" + } >> "$GITHUB_ENV" + else + echo "CADDY_SOURCE=build" >> "$GITHUB_ENV" + fi fi # Both images, always together: the web image of an earlier attempt is # never reused. Each digest comes from the output of its own push, and - # the seeder embeds the web image by that digest. + # the seeder embeds the web image by that digest. The Caddy image is + # built first, only when no signed one exists for this Dockerfile.caddy, + # pushed as caddy-, and the seeder embeds it by digest too. - name: Build and push both images run: | set -Eeuo pipefail @@ -403,10 +463,25 @@ jobs: --label org.opencontainers.image.revision="$GITHUB_SHA" \ -f deploy/seeder/Dockerfile.web -t "$WEB_REPO:$tag" . web="$(push_digest "$WEB_REPO")" + case "$CADDY_SOURCE" in + reused) caddy="$VERIFIED_CADDY_DIGEST" ;; + build) + docker build --platform linux/amd64 --provenance=false --sbom=false \ + --label org.varanda.dockerfile-caddy="${CADDY_TAG#caddy-}" \ + -f deploy/seeder/Dockerfile.caddy -t "$CADDY_REPO:$CADDY_TAG" deploy/seeder + caddy="$(tag="$CADDY_TAG" push_digest "$CADDY_REPO")" + ;; + *) echo "::error::CADDY_SOURCE inválido"; exit 1 ;; + esac + if ! [[ "$caddy" =~ ^sha256:[0-9a-f]{64}$ ]]; then + echo "::error::digest da imagem do Caddy inválido" + exit 1 + fi docker build --platform linux/amd64 --provenance=false --sbom=false \ --build-arg VARANDA_COMMIT="$GITHUB_SHA" \ --build-arg VARANDA_SEQ="$SEQ" \ --build-arg VARANDA_WEB_IMAGE="$WEB_REPO@$web" \ + --build-arg VARANDA_CADDY_IMAGE="$CADDY_REPO@$caddy" \ --label org.opencontainers.image.revision="$GITHUB_SHA" \ -f deploy/seeder/Dockerfile -t "$SEEDER_REPO:$tag" . seeder="$(push_digest "$SEEDER_REPO")" @@ -417,9 +492,15 @@ jobs: echo "::error::/app/release.json de $SEEDER_REPO@$seeder não confere com este commit" exit 1 fi + caddy_json="$(docker run --rm --network none --entrypoint cat "$SEEDER_REPO@$seeder" /app/caddy.json)" + if [ "$caddy_json" != "{\"v\":1,\"caddy\":\"$CADDY_REPO@$caddy\"}" ]; then + echo "::error::/app/caddy.json de $SEEDER_REPO@$seeder não confere com a imagem do Caddy" + exit 1 + fi { echo "WEB_DIGEST=$web" echo "SEEDER_DIGEST=$seeder" + echo "CADDY_DIGEST=$caddy" } >> "$GITHUB_ENV" # Keyless signing with the job's GitHub OIDC token; the request URL and @@ -440,6 +521,13 @@ jobs: -v "$DOCKER_CONFIG:/docker-config:ro" \ "$COSIGN_IMAGE" "$@" } + # A reused Caddy digest was verified by the reuse step; only one this + # run pushed is signed. + if [ "$CADDY_SOURCE" = build ]; then + cosign sign "$CADDY_REPO@$CADDY_DIGEST" + cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$CADDY_REPO@$CADDY_DIGEST" > /dev/null + echo "VERIFIED_CADDY_DIGEST=$CADDY_DIGEST" >> "$GITHUB_ENV" + fi for ref in "$WEB_REPO@$WEB_DIGEST" "$SEEDER_REPO@$SEEDER_DIGEST"; do cosign sign "$ref" cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$ref" > /dev/null @@ -485,7 +573,7 @@ jobs: return 1 fi } - for d in "${VERIFIED_WEB_DIGEST:-}" "${VERIFIED_SEEDER_DIGEST:-}"; do + for d in "${VERIFIED_WEB_DIGEST:-}" "${VERIFIED_SEEDER_DIGEST:-}" "${VERIFIED_CADDY_DIGEST:-}"; do if ! [[ "$d" =~ ^sha256:[0-9a-f]{64}$ ]]; then echo "::error::falta um digest verificado" exit 1 @@ -544,6 +632,7 @@ jobs: echo "- origem: $RELEASE_SOURCE" echo "- web: $WEB_REPO@$VERIFIED_WEB_DIGEST" echo "- seeder: $SEEDER_REPO@$VERIFIED_SEEDER_DIGEST" + echo "- caddy: $CADDY_REPO@$VERIFIED_CADDY_DIGEST" echo "- edge: $EDGE_STATUS" } >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index 5472a8843..b7c2b2a92 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ deploy/seeder/.env deploy/seeder/www/ # cópia exportada do commit onde deploy/seeder/deploy.sh gera o app web /.deploy-build/ +/.deploy-www/ diff --git a/README.md b/README.md index 606f2a200..5d4f21b4b 100644 --- a/README.md +++ b/README.md @@ -836,7 +836,7 @@ O script só implanta se esse SHA for a ponta de `origin/main`. Se `main` já av - guarda a imagem que o semeador está rodando (etiquetada `varanda-seeder:anterior`) e uma cópia do `deploy/seeder/www` em `/var/lib/varanda-deploy`; o commit que está no ar fica anotado em `/var/lib/varanda-deploy/implantado` desde a última implantação; - atualiza o checkout e gera o app web (`build-web.sh`) numa cópia exportada do commit (`.deploy-build/`, nunca no checkout, e como o usuário `nobody`, nunca como root: os scripts de instalação das dependências não podem reescrever os compose, o Caddyfile nem deixar nada com poder de root no servidor); o `deploy.sh` passa o commit ao build web (`EXPO_PUBLIC_VARANDA_COMMIT`, embutido no bundle junto com `EXPO_PUBLIC_VARANDA_BUILD_DATE` por `scripts/resolve-build-info.js`); o build e o `deploy.sh` conferem que `sw.js` foi gerado, e o build, que o `index.html` tem a marca `varanda-release` e que existe a cópia do nó com esse nome (`varanda-node-.js`); -- constrói a imagem do semeador e a do Caddy (`deploy/seeder/Dockerfile.caddy`: o Caddy oficial por digest mais o módulo `caddy-ratelimit` em versão fixa, que limita `/index/*` e `/media/*` por cliente; a anterior fica guardada como `varanda-caddy:anterior`), copia o app para `www` (só arquivos e diretórios comuns: um link simbólico deixado pelo build é recusado; o `index.html` entra por último, depois do `sw.js`, para que uma página nova nunca chegue antes do nó que ela carrega), e depois da cópia reescreve `www/version.json` a partir do SHA conferido, e sobe o semeador e o Caddy; +- constrói a imagem do semeador e a do Caddy (`deploy/seeder/Dockerfile.caddy`: o Caddy oficial por digest mais o módulo `caddy-ratelimit` em versão fixa, que limita `/index/*` e `/media/*` por cliente; a anterior fica guardada como `varanda-caddy:anterior`), copia o app para `www` (só arquivos e diretórios comuns: um link simbólico deixado pelo build é recusado; a cópia é montada ao lado, em `.deploy-www`, e entra arquivo a arquivo, cada um trocado de uma vez por cópia temporária e `mv`, sem esvaziar o `www` antes; o `index.html` entra por último, depois do `sw.js`, para que uma página nova nunca chegue antes do nó que ela carrega, e os arquivos que saíram são apagados no fim), e depois da cópia reescreve `www/version.json` a partir do SHA conferido, e sobe o semeador e o Caddy; - confere a saúde: `/health` do semeador com 200 em até 180 s, o `index.html` e o `varanda-node.js` servidos pelo domínio byte a byte iguais aos de `www` em até 60 s, também `sw.js` quando existe em `www`, o bundle com hash citado no `index.html` e a cópia do nó com o nome da versão marcada nele (`varanda-node-.js`), e `/version.json` quando existe em `www` (o arquivo servido comparado à cópia de `www`), `/varanda.json` com o corpo exato `{"v":1,"association":""}` e um WebSocket de verdade aberto em `wss:///seeder` com o Origin de produção; a primeira implantação depois desta mudança ainda executa o `deploy.sh` anterior, então a sonda de `sw.js` só roda a partir da segunda; o mesmo vale para a sonda da cópia do nó e para a cópia com o `index.html` por último; a primeira implantação com esta mudança de `/version.json` também roda o `deploy.sh` anterior, publica o arquivo pela cópia do build (o `build-web.sh` novo o grava no dist e o `cp` antigo o leva para `www`) e pula a sonda nova (confira com `curl https:///version.json`); a volta restaura o arquivo anterior ou a ausência dele; - se algo falhar (ou se receber Ctrl-C ou SIGTERM no meio), volta sozinho para o commit, as imagens (semeador e Caddy) e o `www` anteriores (com o `index.html` de novo por último), sem reconstruir nada, e sai com 1. Só reinicia o semeador e o Caddy se eles já tinham sido trocados: uma falha no build não derruba nada. Os últimos registros do semeador e do Caddy ficam em `/var/lib/varanda-deploy/deploy.log`. @@ -974,6 +974,8 @@ Configure (passo 2) e rode `cd /root/varanda-bootstrap && ./update.sh install -- Toda troca (`run` em `auto`, `apply`, ou o primeiro `apply` do `install`) faz um pré-voo (arquivo de ambiente e `docker compose config -q`) antes de tocar no que roda, sobe a versão nova com `up -d --no-build` e só dá por concluída depois da verificação de saúde: `/health` do semeador com 200 em até 180 s e, no perfil `full`, o app, `/varanda.json`, `/account/health` e o painel de moderação servidos pelo domínio como esperado em até 60 s, um WebSocket de verdade em `wss:///seeder` e cada serviço rodando a imagem da versão. Se algo falhar (ou chegar SIGTERM no meio), volta sozinho para a versão anterior (ou, num servidor que veio do deploy por SSH, ao checkout antigo) e sai com 1. Um digest que voltou fica em `/var/lib/varanda-update/recusadas` e, em `auto`, nunca é aplicado de novo; só um `apply` explícito o força. Códigos de saída: 0 feito ou nada a fazer, 1 falha (nada mudou ou voltou), 2 uso errado. +**O Caddy fica de pé.** Desde `fix/caddy-stays-up`, o `release` publica também `ghcr.io/varanda-org/varanda-caddy`, a imagem de `deploy/seeder/Dockerfile.caddy` (o Caddy sem o app), e grava o digest dela em `/app/caddy.json` dentro da imagem assinada do semeador. No perfil `full`, o `update.sh` roda o serviço `web` com essa imagem e monta caminhos que não mudam de uma versão para outra: o `Caddyfile` copiado para `/opt/varanda-release/Caddyfile-` e o app pelo link `/opt/varanda-release/web`, que aponta para o `www` da versão e é trocado de uma vez (link novo e `mv`), visto pelo Caddy em `/srv/web`. A troca sobe primeiro o semeador e o serviço de conta, depois troca o link e só então roda `up -d` do `web`, que só recria o Caddy quando o digest dele ou o conteúdo do `Caddyfile` mudou; numa versão que só muda o código, o Caddy segue no ar. A verificação de saúde de 180 s e a volta continuam iguais, e a volta põe de novo o Caddy, o `Caddyfile` e o link da versão anterior. Uma versão sem `/app/caddy.json` (as anteriores a esta mudança) segue o modo antigo: o Caddy roda a imagem `varanda-web` e é recriado a cada troca. Num servidor que já atualiza por imagem, a primeira versão com `caddy.json` ainda é aplicada pelo `update.sh` antigo, no modo antigo; a seguinte, já com o `update.sh` novo, recria o Caddy uma vez, porque as montagens mudam, e daí em diante ele só é recriado quando muda. O Caddy enxerga `/opt/varanda-release` inteiro, só leitura (os pacotes públicos das versões; os segredos ficam em `/var/lib/varanda-update`). + **Intervenção.** Se nem a volta funcionou (ou a versão nova subiu e saudável, mas o estado não pôde ser gravado), o `update.sh` grava o motivo em `/var/lib/varanda-update/intervencao` e o `status` o mostra. Enquanto o arquivo existir, `run` não troca nada: só registra "intervenção pendente" e sai com 1; `check`, `status`, `reconfigure` e `compose` continuam funcionando. Corrija a causa (o registro do servidor, em `update.log`, diz qual) e rode `update.sh apply` (com a versão instalada já em dia, ele a sobe de novo e, se ela passar na verificação, apaga o arquivo; com uma versão nova, a troca que dá certo o apaga) ou `update.sh rollback` (quando volta para uma versão instalada e dá certo, também o apaga). Uma exceção, de propósito: uma volta ao checkout antigo, automática (o primeiro `apply` falhou) ou por `update.sh rollback`, deixa a intervenção anotada. O servidor roda de novo o checkout, mas `run` não troca nada até você decidir. Nesse caso só um `apply` que dê certo (prepara a versão, troca e passa na verificação de saúde) apaga o arquivo; outro `rollback` volta ao checkout de novo e a anota outra vez. **5. Migrar um servidor que usa o deploy por SSH.** @@ -1011,7 +1013,7 @@ Passos de quem mantém o repositório: **7. Para quem mantém o repositório** (uma vez, nesta ordem; nenhum agente faz isso): 1. Em Settings > Secrets and variables > Actions > Variables, crie `VARANDA_RELEASE` com o valor `true`. Só liga o `release.yml`. -2. Depois da primeira execução do `release`, torne públicos os dois pacotes (`varanda-seeder` e `varanda-web`): Packages > pacote > Package settings > Change visibility > Public. Sem isso o servidor não baixa sem credencial. +2. Depois da primeira execução do `release`, torne públicos os três pacotes (`varanda-seeder`, `varanda-web` e, desde `fix/caddy-stays-up`, `varanda-caddy`): Packages > pacote > Package settings > Change visibility > Public. Sem isso o servidor não baixa sem credencial. 3. Confira, em cada pacote (Package settings > Manage Actions access), que o repositório tem acesso Write; sem ele o `promote` falha ao mover a tag. Pode não ser preciso quando o fluxo que publica está no mesmo repositório que o pacote: confira em vez de supor. 4. Settings > Environments > New environment `release-stable`: revisores obrigatórios (quem mantém), sem autorrevisão e implantação só a partir de `main`. Faça isto ANTES de definir `VARANDA_PROMOTE`: o GitHub cria um ambiente que falta sem proteção nenhuma na primeira vez que um job o cita. 5. Só então defina a variável `VARANDA_PROMOTE` com o valor `true` (liga só o `promote.yml`). diff --git a/apps/cli/test/deploy.test.js b/apps/cli/test/deploy.test.js index e0acda5c3..8f655d88e 100644 --- a/apps/cli/test/deploy.test.js +++ b/apps/cli/test/deploy.test.js @@ -235,9 +235,11 @@ test('deploy.sh: executable, required strings and last line', (t) => { // the release mark of the www index.html, and the page lands last. 'versao=$(versao_web "$www/index.html")', '[ -z "$versao" ] || servido_igual "varanda-node-$versao.js" "varanda-node-$versao.js"', - 'copiar_app "$base/src/apps/app/dist" "$www"', - // The rollback restores the saved www the same way, attributes kept. - 'copiar_app "$state/www-anterior" "$www" -a', + 'copiar_app "$base/src/apps/app/dist" "$novo"', + // The new tree is built beside www and merged in by renames; the rollback + // restores the saved www the same way (cp -a keeps its attributes). + 'mesclar_www "$novo" "$www"', + 'mesclar_www "$state/www-anterior" "$www"', // The account service is probed through the domain, and its OAuth client // must be configured before anything changes. '/account/health', @@ -274,7 +276,7 @@ test('deploy.sh: executable, required strings and last line', (t) => { // The build gets the validated commit, and root rewrites version.json in // www from it; the probe compares with the www copy, so a rollback passes. 'EXPO_PUBLIC_VARANDA_COMMIT="$target"', - 'gravar_versao "$www" "$target"', + 'gravar_versao "$novo" "$target"', 'servido_igual version.json version.json', '[ ! -f "$www/version.json" ]', // The optional seeder limits are validated by shape before anything changes. @@ -288,6 +290,7 @@ test('deploy.sh: executable, required strings and last line', (t) => { t.absent(wait && wait[0].includes('$target'), 'aguardar_web never compares with $target (a rollback must pass)') t.absent(shCode.includes('cp -R "$base/src/apps/app/dist/." "$www/"'), 'www is never filled in directory order') t.absent(shCode.includes('cp -a "$state/www-anterior/." "$www/"'), 'nor restored in directory order by the rollback') + t.absent(/find "\$www" -mindepth 1 -delete/.test(shCode), 'www is never emptied while Caddy serves it') }) test('deploy.sh: forbidden constructs are absent', (t) => { @@ -957,9 +960,100 @@ test('build-web.sh: writes the association files and refuses malformed values', t.ok(argNoCopy.stderr.includes(NO_COPY), 'and says what is missing') }) -// The deploy, its rollback and build-web.sh empty www and refill it: the page -// comes last, after sw.js, so an index.html never lands before the node copy -// it loads. +// www is a bind mount that Caddy serves while the deploy runs: the new tree +// goes in by renames, index.html last, and only then the old files go away. +test('deploy.sh: mesclar_www swaps www without emptying it', (t) => { + if (!hasBash(t)) return + const src = fs.readFileSync(SCRIPT, 'utf8') + const fn = src.match(/^mesclar_www\(\) \{\n[\s\S]*?^\}\n/m) + t.ok(fn, 'mesclar_www located') + if (!fn) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'varanda-mesclar-')) + t.teardown(() => fs.rmSync(dir, { recursive: true, force: true })) + const novo = path.join(dir, 'novo') + const www = path.join(dir, 'www') + const log = path.join(dir, 'mv.log') + const write = (base, rel, text) => { + fs.mkdirSync(path.dirname(path.join(base, rel)), { recursive: true }) + fs.writeFileSync(path.join(base, rel), text) + } + write(www, 'index.html', 'old page') + write(www, 'sw.js', 'old sw') + write(www, 'old-bundle.js', 'old bundle') + write(www, 'shared.js', 'old shared') + write(www, 'gone/x.txt', 'gone') + write(www, 'flip', 'a file that becomes a directory') + write(novo, 'index.html', 'new page') + write(novo, 'sw.js', 'new sw') + write(novo, 'new-bundle.js', 'new bundle') + write(novo, 'shared.js', 'new shared') + write(novo, '.well-known/assetlinks.json', '[]') + write(novo, 'flip/inner.txt', 'inner') + // Every rename is logged with what www holds at that moment. + const script = 'set -Eeuo pipefail\n' + + 'mv() { printf "%s %s\\n" "$' + '{*: -1}" "$(cat ' + JSON.stringify(www) + '/index.html 2>/dev/null || echo NONE)" >> ' + JSON.stringify(log) + '; command mv "$@"; }\n' + + 'export -f mv\n' + fn[0] + 'mesclar_www ' + JSON.stringify(novo) + ' ' + JSON.stringify(www) + '\n' + const r = spawnSync('bash', ['-c', script], { encoding: 'utf8' }) + t.is(r.status, 0, 'merges: ' + r.stderr) + const tree = (base) => { + const out = [] + const walk = (d) => { + for (const e of fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { + const p = path.join(d, e.name) + if (e.isDirectory()) walk(p) + else out.push(path.relative(base, p) + '=' + fs.readFileSync(p, 'utf8')) + } + } + walk(base) + return out + } + t.alike(tree(www), tree(novo), 'www ends equal to the new tree, old files gone') + t.ok(fs.existsSync(path.join(novo, 'index.html')), 'the source is left intact') + const moves = fs.readFileSync(log, 'utf8').trim().split('\n') + t.ok(moves.every((l) => !l.endsWith(' NONE')), 'index.html never missing during the swap') + t.ok(moves[moves.length - 1].startsWith(path.join(www, 'index.html') + ' ') || moves[moves.length - 1].startsWith(www + '/./index.html '), 'index.html is renamed last') + const swAt = moves.findIndex((l) => /\/sw\.js /.test(l)) + t.ok(swAt === moves.length - 2, 'sw.js right before index.html') + t.ok(moves.slice(0, -1).every((l) => l.endsWith(' old page')), 'the old page stays until its own rename') +}) + +// The rollback calls mesclar_www inside `if !`, where bash ignores errexit: +// a failed copy must still fail the call, before anything is deleted. A +// symlink already at a file path is replaced, never followed out of www. +test('deploy.sh: mesclar_www fails under if ! on a failed copy and never follows a link', (t) => { + if (!hasBash(t)) return + const src = fs.readFileSync(SCRIPT, 'utf8') + const fn = src.match(/^mesclar_www\(\) \{\n[\s\S]*?^\}\n/m) + t.ok(fn, 'mesclar_www located') + if (!fn) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'varanda-mesclar-')) + t.teardown(() => fs.rmSync(dir, { recursive: true, force: true })) + const novo = path.join(dir, 'novo') + const www = path.join(dir, 'www') + const fora = path.join(dir, 'fora') + fs.mkdirSync(novo) + fs.mkdirSync(www) + fs.mkdirSync(fora) + fs.writeFileSync(path.join(novo, 'index.html'), 'new page') + fs.writeFileSync(path.join(novo, 'a.js'), 'new a') + fs.writeFileSync(path.join(www, 'index.html'), 'old page') + fs.writeFileSync(path.join(www, 'old.js'), 'old') + fs.symlinkSync(fora, path.join(www, 'a.js')) + const run = (pre) => spawnSync('bash', ['-c', 'set -Eeuo pipefail\n' + pre + fn[0] + + 'if ! mesclar_www ' + JSON.stringify(novo) + ' ' + JSON.stringify(www) + '; then echo FAILED; fi\n'], { encoding: 'utf8' }) + + const failed = run('cp() { return 1; }\nexport -f cp\n') + t.ok(failed.stdout.includes('FAILED'), 'a failed copy fails the call: ' + failed.stderr) + t.ok(fs.existsSync(path.join(www, 'old.js')), 'nothing is deleted after a failed copy') + t.is(fs.readFileSync(path.join(www, 'index.html'), 'utf8'), 'old page', 'the old page stays') + + const ok = run('') + t.absent(ok.stdout.includes('FAILED'), 'merges: ' + ok.stderr) + t.alike(fs.readdirSync(fora), [], 'nothing was written through the link') + t.absent(fs.lstatSync(path.join(www, 'a.js')).isSymbolicLink(), 'the link is replaced by the file') + t.is(fs.readFileSync(path.join(www, 'a.js'), 'utf8'), 'new a', 'with the new content') +}) + test('well-known.sh: copiar_app copies index.html last and versao_web reads the release mark', (t) => { if (!hasBash(t)) return const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'varanda-copy-')) diff --git a/apps/cli/test/release.test.js b/apps/cli/test/release.test.js index 0cc928dbb..7ed08fdcd 100644 --- a/apps/cli/test/release.test.js +++ b/apps/cli/test/release.test.js @@ -3,6 +3,8 @@ const test = require('brittle') const fs = require('node:fs') const path = require('node:path') +const os = require('node:os') +const { spawnSync } = require('node:child_process') const repoRoot = path.resolve(__dirname, '../../..') const WORKFLOW = path.join(repoRoot, '.github/workflows/release.yml') @@ -227,7 +229,7 @@ test('release.yml: a rerun reuses sha- only when both images verify', (t const seq = reuse.indexOf('[ "$' + '{BASH_REMATCH[2]}" = "$SEQ" ] || return 1') const web = reuse.indexOf('web="$' + '{BASH_REMATCH[3]}"') const verifyWeb = reuse.indexOf('cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$WEB_REPO@$web" > /dev/null || return 1') - const print = reuse.indexOf('printf \'%s %s\\n\' "$seeder" "$web"') + const print = reuse.indexOf('printf \'%s %s %s\\n\' "$seeder" "$web" "$caddy"') t.ok(verifySeeder !== -1 && run !== -1 && commit !== -1 && seq !== -1 && web !== -1 && verifyWeb !== -1 && print !== -1, 'seeder verify, release.json, commit, seq, web verify and result present') t.ok(verifySeeder < run, 'the seeder is verified before it is ever run') t.ok(run < commit && commit < seq && seq < web && web < verifyWeb && verifyWeb < print, 'a release counts only after every check') @@ -237,9 +239,9 @@ test('release.yml: a rerun reuses sha- only when both images verify', (t const match = reuse.indexOf('[[ "$release" =~ $re ]] || return 1') t.ok(matchRe !== -1 && matchRe < run, 'the reuse step holds the same anchored release.json regex') t.ok(match !== -1 && run < match && match < commit, 'release.json is matched whole before its fields are compared') - t.ok(/^ {10}rc=0\n {10}found="\$\(signed_release\)" \|\| rc=\$\?\n {10}if \[ "\$rc" -eq 2 \]; then\n {12}echo "::error::[^"\n]*"\n {12}exit 1\n {10}elif \[ "\$rc" -eq 0 \]; then\n {12}read -r seeder web <<< "\$found"\n/m.test(reuse), 'a registry error fails the step; reused only when signed_release succeeds') + t.ok(/^ {10}rc=0\n {10}found="\$\(signed_release\)" \|\| rc=\$\?\n {10}if \[ "\$rc" -eq 2 \]; then\n {12}echo "::error::[^"\n]*"\n {12}exit 1\n {10}elif \[ "\$rc" -eq 0 \]; then\n {12}read -r seeder web caddy <<< "\$found"\n/m.test(reuse), 'a registry error fails the step; reused only when signed_release succeeds') t.ok(/\n {14}echo "RELEASE_SOURCE=reused"\n {14}echo "VERIFIED_SEEDER_DIGEST=\$seeder"\n {14}echo "VERIFIED_WEB_DIGEST=\$web"\n/.test(reuse), 'the reused digests are the verified ones') - t.ok(/\n {10}else\n[^\n]*\n {12}echo "RELEASE_SOURCE=build" >> "\$GITHUB_ENV"\n {10}fi/.test(reuse), 'anything else builds') + t.ok(/\n {10}else\n[^\n]*\n {12}echo "RELEASE_SOURCE=build" >> "\$GITHUB_ENV"\n/.test(reuse), 'anything else builds') t.is((code.match(/RELEASE_SOURCE=reused/g) || []).length, 1, 'only the reuse step marks a release reused') // The build and sign steps stop on a reused release and refuse an unknown state. @@ -261,11 +263,14 @@ test('release.yml: image names, build flags and the digests from the push', (t) t.ok(validate.includes("re='^ghcr\\.io/sigstore/cosign/cosign:v[0-9]+\\.[0-9]+\\.[0-9]+@sha256:[0-9a-f]{64}$'"), 'cosign.ref must be the pinned cosign image') const builds = lines.filter((l) => /docker (buildx )?build\b/.test(l)) - t.is(builds.length, 2, 'two image builds') + t.is(builds.length, 3, 'three image builds: web, seeder and, when needed, Caddy') const build = stepNamed('Build and push both images') t.ok(build, 'build step found') - const cmds = build.split(/(?=docker build )/).slice(1).map((c) => c.split(/ \.\n/)[0]) - t.is(cmds.length, 2, 'two build commands') + const all = build.split(/(?=docker build )/).slice(1) + t.is(all.length, 3, 'three build commands') + // The release images carry the commit; the Caddy image is shared by many. + const cmds = all.filter((c) => !c.includes('Dockerfile.caddy')).map((c) => c.split(/ \.\n/)[0]) + t.is(cmds.length, 2, 'two release build commands') for (const c of cmds) { for (const f of ['--platform linux/amd64', '--provenance=false', '--sbom=false', '--build-arg VARANDA_COMMIT="$GITHUB_SHA"', '--label org.opencontainers.image.revision="$GITHUB_SHA"']) { t.ok(c.includes(f), 'build has ' + f) @@ -293,7 +298,7 @@ test('release.yml: image names, build flags and the digests from the push', (t) t.ok(build.includes("re='^\\{\"v\":1,\"commit\":\"([0-9a-f]{40})\",\"seq\":([1-9][0-9]{0,9}),\"web\":\"ghcr\\.io/varanda-org/varanda-web@(sha256:[0-9a-f]{64})\"\\}$'"), 'release.json matched whole by one anchored regex') t.ok(/\[ "\$\{BASH_REMATCH\[1\]\}" != "\$GITHUB_SHA" \]/.test(build) && /\[ "\$\{BASH_REMATCH\[2\]\}" != "\$SEQ" \]/.test(build), 'release.json names this commit and seq') t.ok(/\|\| \[ "\$\{BASH_REMATCH\[3\]\}" != "\$web" \]; then\n[^\n]*\n\s+exit 1/.test(build), 'release.json names the pushed web digest') - t.ok(/\n {10}\{\n {12}echo "WEB_DIGEST=\$web"\n {12}echo "SEEDER_DIGEST=\$seeder"\n {10}\} >> "\$GITHUB_ENV"/.test(build), 'the pushed digests are handed to signing') + t.ok(/\n {10}\{\n {12}echo "WEB_DIGEST=\$web"\n {12}echo "SEEDER_DIGEST=\$seeder"\n {12}echo "CADDY_DIGEST=\$caddy"\n {10}\} >> "\$GITHUB_ENV"/.test(build), 'the pushed digests are handed to signing') t.is((code.match(/echo "(WEB|SEEDER)_DIGEST=/g) || []).length, 2, 'only the build step sets the digests to sign') }) @@ -317,7 +322,7 @@ test('release.yml: cosign keyless, only as the pinned container, verified', (t) t.ok(/^ {12}cosign sign "\$ref"\n {12}cosign verify --certificate-identity "\$COSIGN_IDENTITY" --certificate-oidc-issuer "\$COSIGN_ISSUER" "\$ref" > \/dev\/null\n {10}done$/m.test(sign), 'each is verified right after signing, with the exact identity and issuer') // A verify that cannot fail the job would let an unsigned digest through. const verifies = lines.filter((l) => /cosign verify/.test(l)) - t.is(verifies.length, 3, 'three verifies: the two reuse checks and the post-sign check') + t.is(verifies.length, 6, 'six verifies: seeder, web and Caddy of a reused release, a reused Caddy tag, a built Caddy and the post-sign loop') for (const l of verifies) { t.ok(/--certificate-identity "\$COSIGN_IDENTITY" --certificate-oidc-issuer "\$COSIGN_ISSUER" "[^"]+" > \/dev\/null( \|\| return 1)?$/.test(l), 'verify pins identity and issuer and can fail: ' + l.trim()) t.absent(/\|\|\s*(true|:)\b|;\s*true\b/.test(l), 'verify failure is never ignored: ' + l.trim()) @@ -328,6 +333,67 @@ test('release.yml: cosign keyless, only as the pinned container, verified', (t) t.is((code.match(/echo "VERIFIED_(WEB|SEEDER)_DIGEST=/g) || []).length, 4, 'only the reuse and sign steps record verified digests') }) +test('release.yml: the Caddy image is built only for a new Dockerfile.caddy and pinned in caddy.json', (t) => { + t.ok(/^ {6}CADDY_REPO:\s*ghcr\.io\/varanda-org\/varanda-caddy\s*$/m.test(publish), 'Caddy image name') + const validate = publishSteps.find((s) => /deploy\/seeder\/cosign\.ref/.test(s)) || '' + t.ok(validate.includes('caddy_hash="$(sha256sum deploy/seeder/Dockerfile.caddy)"') && validate.includes('echo "CADDY_TAG=caddy-$caddy_hash"'), 'the Caddy tag is the Dockerfile.caddy hash') + const reuse = stepNamed('Reuse a release already signed for this commit') + const readCaddy = reuse.indexOf('caddy_json="$(docker run --rm --network none --entrypoint cat "$SEEDER_REPO@$seeder" /app/caddy.json)" || return 1') + const verifyCaddy = reuse.indexOf('cosign verify --certificate-identity "$COSIGN_IDENTITY" --certificate-oidc-issuer "$COSIGN_ISSUER" "$CADDY_REPO@$caddy" > /dev/null || return 1') + const print = reuse.indexOf('printf \'%s %s %s\\n\' "$seeder" "$web" "$caddy"') + t.ok(readCaddy !== -1 && verifyCaddy > readCaddy && print > verifyCaddy, 'a reused release reuses only a verified caddy.json digest') + t.ok(reuse.includes('found_caddy="$(digest_of "$CADDY_REPO@$caddy")" || return 2\n [ "$found_caddy" = "$caddy" ] || return 1'), 'the caddy.json digest must exist') + const tagged = reuse.indexOf('caddy="$(digest_of "$CADDY_REPO:$CADDY_TAG")" || return 2') + const labelCheck = reuse.indexOf('[ "caddy-$label" = "$CADDY_TAG" ] || return 1') + t.ok(tagged !== -1 && labelCheck > reuse.indexOf('"$CADDY_REPO@$caddy" > /dev/null || return 1', tagged), 'a Caddy tag is reused only after verify and a matching Dockerfile hash label') + t.ok(/\n {16}echo "CADDY_SOURCE=reused"\n {16}echo "VERIFIED_CADDY_DIGEST=\$caddy"\n/.test(reuse) && /\n {14}echo "CADDY_SOURCE=build" >> "\$GITHUB_ENV"\n/.test(reuse), 'reused when verified, built otherwise') + + const build = stepNamed('Build and push both images') + t.ok(/^ {14}docker build --platform linux\/amd64 --provenance=false --sbom=false \\\n {16}--label org\.varanda\.dockerfile-caddy="\$\{CADDY_TAG#caddy-\}" \\\n {16}-f deploy\/seeder\/Dockerfile\.caddy -t "\$CADDY_REPO:\$CADDY_TAG" deploy\/seeder\n {14}caddy="\$\(tag="\$CADDY_TAG" push_digest "\$CADDY_REPO"\)"\n/m.test(build), 'Caddy built only in the build branch, labelled, pushed as caddy-, digest from its push') + t.ok(build.includes('reused) caddy="$VERIFIED_CADDY_DIGEST" ;;'), 'a reused Caddy keeps its verified digest') + t.ok(build.includes('--build-arg VARANDA_CADDY_IMAGE="$CADDY_REPO@$caddy"'), 'the seeder pins the Caddy image by digest') + t.ok(build.indexOf('--build-arg VARANDA_CADDY_IMAGE') > build.indexOf('caddy="$(tag='), 'Caddy pushed before the seeder build') + t.ok(build.includes('if [ "$caddy_json" != "{\\"v\\":1,\\"caddy\\":\\"$CADDY_REPO@$caddy\\"}" ]; then'), 'caddy.json read back and compared') + + const sign = stepNamed('Sign and verify the pushed digests') + t.ok(/^ {10}if \[ "\$CADDY_SOURCE" = build \]; then\n {12}cosign sign "\$CADDY_REPO@\$CADDY_DIGEST"\n {12}cosign verify [^\n]*"\$CADDY_REPO@\$CADDY_DIGEST" > \/dev\/null\n {12}echo "VERIFIED_CADDY_DIGEST=\$CADDY_DIGEST" >> "\$GITHUB_ENV"\n {10}fi\n/m.test(sign), 'only a Caddy image this run pushed is signed, then verified') + t.absent(/CADDY_REPO:edge|CADDY_REPO" "\$VERIFIED_CADDY/.test(code), 'no channel tag for the Caddy image') + const summary = publishSteps.find((s) => /GITHUB_STEP_SUMMARY/.test(s)) || '' + t.ok(summary.includes('$CADDY_REPO@$VERIFIED_CADDY_DIGEST'), 'summary names the Caddy digest') +}) + +test('Dockerfile: caddy.json is written only with a Caddy image, in its own RUN', { skip: process.platform === 'win32' }, (t) => { + const df = fs.readFileSync(path.join(repoRoot, 'deploy/seeder/Dockerfile'), 'utf8').split('\n').filter((l) => !/^\s*#/.test(l)) + let i = df.indexOf('ARG VARANDA_CADDY_IMAGE=""') + t.ok(i !== -1, 'ARG VARANDA_CADDY_IMAGE with an empty default') + while (i !== -1 && i < df.length && !/^RUN\s/.test(df[i])) i++ + const out = [] + for (; i !== -1 && i < df.length; i++) { + out.push(df[i].replace(/\\$/, '')) + if (!/\\$/.test(df[i])) break + } + t.ok(i < df.findIndex((l) => /^USER\s+node/.test(l)), 'before USER node') + const script = out.join('\n').replace(/^RUN\s+/, '') + const run = (env) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'varanda-caddy-')) + const file = path.join(dir, 'caddy.json') + const r = spawnSync('sh', ['-c', script.split('/app/caddy.json').join(file)], { + env: { PATH: process.env.PATH, VARANDA_COMMIT: '', VARANDA_CADDY_IMAGE: '', ...env }, encoding: 'utf8' + }) + const content = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null + fs.rmSync(dir, { recursive: true, force: true }) + return { status: r.status, content } + } + const ref = 'ghcr.io/varanda-org/varanda-caddy@sha256:' + 'c'.repeat(64) + const commit = 'a'.repeat(40) + t.alike(run({}), { status: 0, content: null }, 'no argument, no file') + t.alike(run({ VARANDA_COMMIT: commit, VARANDA_CADDY_IMAGE: ref }), { status: 0, content: '{"v":1,"caddy":"' + ref + '"}\n' }, 'the exact line update.sh accepts') + t.is(run({ VARANDA_CADDY_IMAGE: ref }).status, 1, 'a Caddy image without a commit is refused') + for (const bad of ['ghcr.io/varanda-org/varanda-web@sha256:' + 'c'.repeat(64), ref + 'c', ref.slice(0, -1), ref.toUpperCase(), 'varanda-caddy:local']) { + t.alike(run({ VARANDA_COMMIT: commit, VARANDA_CADDY_IMAGE: bad }), { status: 1, content: null }, 'refused: ' + bad) + } +}) + test('release.yml: edge moves only from the tip of main, by digest, read back', (t) => { const creates = lines.filter((l) => /imagetools create/.test(l)) t.ok(creates.length > 0, 'edge is moved with imagetools create') @@ -346,7 +412,7 @@ test('release.yml: edge moves only from the tip of main, by digest, read back', t.ok(fetch < tip && tip < first, 'the tip check comes before any move') t.ok(/if \[ "\$tip" != "\$GITHUB_SHA" \]; then\n(\s+echo[^\n]*\n){2}\s+exit 0\n/.test(edge), 'not the tip: a notice and a green exit, nothing moved') - t.ok(/for d in "\$\{VERIFIED_WEB_DIGEST:-\}" "\$\{VERIFIED_SEEDER_DIGEST:-\}"; do\n\s+if ! \[\[ "\$d" =~ \^sha256:\[0-9a-f\]\{64\}\$ \]\]; then\n[^\n]*\n\s+exit 1/.test(edge), 'both verified digests must be present') + t.ok(/for d in "\$\{VERIFIED_WEB_DIGEST:-\}" "\$\{VERIFIED_SEEDER_DIGEST:-\}" "\$\{VERIFIED_CADDY_DIGEST:-\}"; do\n\s+if ! \[\[ "\$d" =~ \^sha256:\[0-9a-f\]\{64\}\$ \]\]; then\n[^\n]*\n\s+exit 1/.test(edge), 'every verified digest must be present, the Caddy one too') t.ok(/^ {10}if ! move "\$WEB_REPO" "\$VERIFIED_WEB_DIGEST"; then\n {12}restore "\$WEB_REPO" "\$web_prev"\n {12}exit 1\n/m.test(edge), 'web moves to its verified digest; a failure restores it and fails') t.ok(/^ {10}if ! move "\$SEEDER_REPO" "\$VERIFIED_SEEDER_DIGEST"; then\n {12}restore "\$SEEDER_REPO" "\$seeder_prev"\n {12}restore "\$WEB_REPO" "\$web_prev"\n {12}exit 1\n/m.test(edge), 'seeder moves last; a failure restores both and fails') t.ok(edge.indexOf('web_prev="$(digest_of "$WEB_REPO:edge")"') < edge.indexOf('if ! move') && edge.indexOf('seeder_prev="$(digest_of "$SEEDER_REPO:edge")"') < edge.indexOf('if ! move'), 'the previous edge digests are read first') diff --git a/apps/cli/test/update.test.js b/apps/cli/test/update.test.js index b7c4a8975..f62c42f5e 100644 --- a/apps/cli/test/update.test.js +++ b/apps/cli/test/update.test.js @@ -86,6 +86,45 @@ mount_source() { } # The last non-empty-or-empty assignment of $1 in env file $2, quotes dropped. env_valor() { sed -n "s/^$1=//p" "$2" | tail -n 1 | tr -d "'\""; } +# Models when Compose recreates a container: on up, each named service (all +# of the profile when none is named) whose resolved config differs from the +# last one in $FIX/cfg_, or every one with --force-recreate, is +# logged to $FIX/recreated. The web config is its image and the two bind +# sources, resolved like Compose does from the variables of compose.web.yaml. +compose_up() { + local a depois=0 forcar=0 web=0 svc cfg ci ws wd + local -a alvo=() + for a in "$@"; do + case $a in + up) depois=1 ;; + --force-recreate) forcar=1 ;; + compose.web.yaml) web=1 ;; + -*) ;; + *) if [ "$depois" = 1 ]; then alvo+=("$a"); fi ;; + esac + done + if [ "$` + '{#alvo[@]}' + String.raw`" = 0 ]; then + alvo=(seeder) + if [ "$web" = 1 ]; then alvo+=(account web); fi + fi + for svc in "$` + '{alvo[@]}' + String.raw`"; do + if [ "$svc" = web ]; then + ci=$(printenv VARANDA_CADDYFILE_SRC || printf './Caddyfile') + ws=$(printenv VARANDA_WWW_SRC || printf './www') + wd=$(printenv VARANDA_WWW_DST || printf '/srv/web') + case $ci in ./*) ci="$PWD/$` + '{ci#./}' + String.raw`" ;; esac + case $ws in ./*) ws="$PWD/$` + '{ws#./}' + String.raw`" ;; esac + cfg="img=$(printenv VARANDA_WEB_IMAGE || true) caddyfile=$ci www=$ws:$wd" + else + cfg="img=$(printenv VARANDA_SEEDER_IMAGE || true)" + fi + if [ "$forcar" = 1 ] || [ "$cfg" != "$(cat "$FIX/cfg_$svc" 2>/dev/null || true)" ]; then + printf 'recreate %s %s +' "$svc" "$cfg" >>"$FIX/recreated" + printf '%s' "$cfg" >"$FIX/cfg_$svc" + fi + done +} docker() { local a ultimo='' svc='' si wi prev='' ef='' for a in "$@"; do ultimo=$a; done @@ -110,6 +149,7 @@ docker() { fi ;; esac fi + case " $* " in *" up "*) compose_up "$@" ;; esac return 0 ;; esac printf 'docker %s\n' "$*" >>"$CALLS" @@ -174,6 +214,13 @@ docker() { *" verify "*) printf '%s\n' "$*" >>"$FIX/cosign_calls" if [ -f "$FIX/cosign_fail" ]; then return 1; fi ;; + *" --entrypoint test "*" -e /app/caddy.json "*) + if [ -f "$FIX/caddy_err" ]; then return 125; fi + if [ -f "$FIX/caddy.json" ]; then return 0; fi + return 1 ;; + *" /app/caddy.json "*) + [ -f "$FIX/caddy.json" ] || return 1 + cat "$FIX/caddy.json" ;; *" --entrypoint cat "*) cat "$FIX/release.json" ;; esac ;; @@ -264,6 +311,7 @@ dono_modo() { cat "$FIX/dono_modo" 2>/dev/null || printf '0 600\n' } trocar_atual() { rm -f "$releases/current"; ln -s "$1" "$releases/current"; } +trocar_link() { rm -f "$2"; ln -s "$1" "$2"; printf 'link %s -> %s\n' "$2" "$1" >>"$CALLS"; } # The gate is replaced unless $FIX/real_gate exists. $FIX/term_at_gate_ # sends SIGTERM to the script during the n-th gate. if [ ! -f "$FIX/real_gate" ]; then @@ -676,6 +724,147 @@ test('update.sh: apply prepares, swaps and records a full-profile release', (t) t.ok(r.calls.includes('docker image prune -f'), 'prunes dangling images') }) +// Caddy (the web service) stays up across app-only releases: with +// /app/caddy.json the web runs the pinned Caddy image and mounts stable paths +// in $releases (the Caddyfile by its sha256, the www through the web link), so +// Compose recreates it only when that image or the Caddyfile changes. +const CADDY_1 = 'ghcr.io/varanda-org/varanda-caddy@sha256:' + H('3', 64) +const CADDY_2 = 'ghcr.io/varanda-org/varanda-caddy@sha256:' + H('4', 64) +const COMMIT_B = H('2', 40) +const DIGEST_B = 'sha256:' + H('6', 64) +const SEEDER_B = 'ghcr.io/varanda-org/varanda-seeder@' + DIGEST_B +const caddyJson = (ref) => '{"v":1,"caddy":"' + ref + '"}\n' + +// A full server on an old-mode release that applies release A (COMMIT, seq 5, +// Caddy CADDY_1). The fixtures are then reset for the second apply. +function caddyServer (t) { + const s = server(t) + s.write('etc/update.conf', 'VARANDA_UPDATE=manual\nVARANDA_PROFILE=full\n') + s.write('etc/varanda.env', FULL_ENV) + s.write('state/atual', record(OLD_COMMIT, 1, OLD_SEEDER, OLD_WEB)) + installRelease(s, OLD_COMMIT) + s.write('fix/bundle/Caddyfile', 'caddyfile one\n') + s.write('fix/caddy.json', caddyJson(CADDY_1)) + const first = s.run(MAIN + 'cmd_apply') + t.is(first.status, 0, 'release A applied: ' + first.out) + // Release B: another seeder image and commit, the same web image. + s.write('fix/digest', DIGEST_B + '\n') + s.write('fix/release.json', '{"v":1,"commit":"' + COMMIT_B + '","seq":6,"web":"' + WEB_REF + '"}\n') + fs.rmSync(s.p('calls')) + fs.rmSync(s.p('fix/recreated')) + return s +} + +const recreated = (s) => s.read('fix/recreated').split('\n').filter(Boolean) +const webCfg = (s, caddy, caddyfile) => 'recreate web img=' + caddy + ' caddyfile=' + s.p('releases', 'Caddyfile-' + sha256(caddyfile)) + + ' www=' + s.p('releases') + ':/srv' + +test('update.sh: a commit-only release does not recreate Caddy', (t) => { + if (!hasBash(t)) return + const s = caddyServer(t) + t.is(s.read('state/atual'), record(COMMIT, 5, SEEDER_REF, WEB_REF) + 'caddy=' + CADDY_1 + '\n', 'the record keeps the Caddy image') + t.is(linkOf(s.p('releases/web')), COMMIT + '/www', 'the web link serves release A') + const r = s.run(MAIN + 'cmd_apply') + t.is(r.status, 0, 'release B applied: ' + r.out) + t.alike(recreated(s), ['recreate seeder img=' + SEEDER_B, 'recreate account img=' + SEEDER_B], 'seeder and account recreated, web left running') + t.is(linkOf(s.p('releases/web')), COMMIT_B + '/www', 'the web link now serves release B') + t.is(s.read('releases/Caddyfile-' + sha256('caddyfile one\n')), 'caddyfile one\n', 'the Caddyfile copy is the stable bind source') + const upApp = r.calls.indexOf(' up -d --no-build seeder account\n') + const link = r.calls.indexOf('link ' + s.p('releases/web') + ' -> ' + COMMIT_B + '/www\n') + const upWeb = r.calls.indexOf(' up -d --no-build web\n') + t.ok(upApp !== -1 && link > upApp && upWeb > link, 'seeder and account first, then the www swap, then web') + t.ok(r.calls.includes('compose pwd=' + s.p('releases', COMMIT_B) + ' seeder=' + SEEDER_B + ' web=' + CADDY_1 + ' compose '), 'compose runs with the pinned Caddy image') + t.is(s.read('state/atual'), record(COMMIT_B, 6, SEEDER_B, WEB_REF) + 'caddy=' + CADDY_1 + '\n', 'atual is release B') +}) + +test('update.sh: a Caddyfile change recreates Caddy with the new file', (t) => { + if (!hasBash(t)) return + const s = caddyServer(t) + s.write('fix/bundle/Caddyfile', 'caddyfile two\n') + const r = s.run(MAIN + 'cmd_apply') + t.is(r.status, 0, 'release B applied: ' + r.out) + t.ok(recreated(s).includes(webCfg(s, CADDY_1, 'caddyfile two\n')), 'web recreated on the same Caddy image with the new Caddyfile') + t.is(s.read('releases/Caddyfile-' + sha256('caddyfile two\n')), 'caddyfile two\n', 'the new Caddyfile is in place under its hash') + t.is(s.read('releases/Caddyfile-' + sha256('caddyfile one\n')), 'caddyfile one\n', 'the previous one stays for the rollback') +}) + +test('update.sh: a Caddy digest change recreates Caddy', (t) => { + if (!hasBash(t)) return + const s = caddyServer(t) + s.write('fix/caddy.json', caddyJson(CADDY_2)) + const r = s.run(MAIN + 'cmd_apply') + t.is(r.status, 0, 'release B applied: ' + r.out) + t.ok(recreated(s).includes(webCfg(s, CADDY_2, 'caddyfile one\n')), 'web recreated on the new Caddy image') + t.ok(r.calls.includes('docker pull ' + CADDY_2) || s.read('fix/tags').includes('varanda-caddy:atual sha256:id-' + CADDY_2), 'the new Caddy image is used') + t.is(s.read('state/atual'), record(COMMIT_B, 6, SEEDER_B, WEB_REF) + 'caddy=' + CADDY_2 + '\n', 'the record names the new Caddy image') +}) + +test('update.sh: a failed release with a new Caddy rolls back to the previous Caddy, Caddyfile and www', (t) => { + if (!hasBash(t)) return + const s = caddyServer(t) + s.write('fix/caddy.json', caddyJson(CADDY_2)) + s.write('fix/bundle/Caddyfile', 'caddyfile two\n') + // The first gate was release A's; the second is release B's. + s.write('fix/gate_fail_2', '') + const r = s.run(MAIN + 'cmd_apply') + t.is(r.status, 1, 'release B fails its gate') + t.ok(r.log.includes('voltou para a versão anterior'), 'rolled back: ' + r.log) + const all = recreated(s) + const failed = all.indexOf(webCfg(s, CADDY_2, 'caddyfile two\n')) + const back = all.lastIndexOf(webCfg(s, CADDY_1, 'caddyfile one\n')) + t.ok(failed !== -1 && back > failed, 'web went to the new Caddy, then back to the previous Caddy and Caddyfile') + t.is(linkOf(s.p('releases/web')), COMMIT + '/www', 'the web link serves release A again') + t.is(s.read('state/atual'), record(COMMIT, 5, SEEDER_REF, WEB_REF) + 'caddy=' + CADDY_1 + '\n', 'atual is still release A') + t.ok(fs.existsSync(s.p('releases', COMMIT, 'www/index.html')), 'release A www kept') +}) + +test('update.sh: a docker error reading caddy.json postpones the release, never falls back to the old mode', (t) => { + if (!hasBash(t)) return + const s = server(t) + s.write('etc/update.conf', 'VARANDA_UPDATE=manual\nVARANDA_PROFILE=full\n') + s.write('etc/varanda.env', FULL_ENV) + s.write('fix/caddy.json', caddyJson(CADDY_1)) + s.write('fix/caddy_err', '') + const r = s.run(MAIN + 'cmd_apply') + t.is(r.status, 1, 'refused') + t.ok(r.log.includes('não foi possível ler /app/caddy.json de ' + SEEDER_REF + ' (saída 125)'), 'says why: ' + r.log) + t.absent(r.log.includes('sem /app/caddy.json'), 'not read as absent') + t.absent(composeRan(r.calls), 'nothing ran') +}) + +test('update.sh: a Caddyfile that cannot be hashed keeps every Caddyfile copy', (t) => { + if (!hasBash(t)) return + if (process.getuid && process.getuid() === 0) { t.comment('root reads any file'); return } + const s = caddyServer(t) + s.write('fix/bundle/Caddyfile', 'caddyfile two\n') + fs.chmodSync(s.p('releases', COMMIT, 'Caddyfile'), 0o000) + const r = s.run(MAIN + 'cmd_apply') + fs.chmodSync(s.p('releases', COMMIT, 'Caddyfile'), 0o644) + t.is(r.status, 0, 'release B applied: ' + r.out) + t.ok(r.log.includes('não foi possível calcular o sha256 de ' + s.p('releases', COMMIT, 'Caddyfile')), 'the hash failure reaches the log: ' + r.log) + t.ok(fs.existsSync(s.p('releases', 'Caddyfile-' + sha256('caddyfile one\n'))), 'release A copy kept') + t.ok(fs.existsSync(s.p('releases', 'Caddyfile-' + sha256('caddyfile two\n'))), 'release B copy kept') +}) + +test('update.sh: a release without caddy.json keeps the old mode', (t) => { + if (!hasBash(t)) return + const s = server(t) + s.write('etc/update.conf', 'VARANDA_UPDATE=manual\nVARANDA_PROFILE=full\n') + s.write('etc/varanda.env', FULL_ENV) + s.write('fix/caddy.json', '{"v":1,"caddy":"ghcr.io/varanda-org/varanda-web@sha256:' + H('3', 64) + '"}\n') + const bad = s.run(MAIN + 'cmd_apply') + t.is(bad.status, 1, 'a malformed caddy.json is refused') + t.ok(bad.log.includes('caddy.json de ' + SEEDER_REF + ' fora do formato esperado'), 'says why') + t.absent(composeRan(bad.calls), 'nothing ran') + fs.rmSync(s.p('fix/caddy.json')) + const r = s.run(MAIN + 'cmd_apply') + t.is(r.status, 0, 'applied: ' + r.out) + t.ok(r.log.includes('sem /app/caddy.json'), 'logs the old mode') + t.is(s.read('state/atual'), record(COMMIT, 5, SEEDER_REF, WEB_REF), 'no caddy line in the record') + t.ok(recreated(s).includes('recreate web img=' + WEB_REF + ' caddyfile=' + s.p('releases', COMMIT, 'Caddyfile') + ' www=' + s.p('releases', COMMIT, 'www') + ':/srv/web'), 'web runs the web image with the version binds') + t.is(linkOf(s.p('releases/web')), null, 'no web link') +}) + test('update.sh: extracted trees are normalised and links refused', (t) => { if (!hasBash(t)) return const s = server(t) diff --git a/deploy/seeder/Dockerfile b/deploy/seeder/Dockerfile index eb5ac9588..8522151d8 100644 --- a/deploy/seeder/Dockerfile +++ b/deploy/seeder/Dockerfile @@ -71,6 +71,21 @@ RUN set -eu; \ fi; \ printf '{"v":1,"commit":"%s","seq":%s,"web":"%s"}\n' "$VARANDA_COMMIT" "$VARANDA_SEQ" "$VARANDA_WEB_IMAGE" > /app/release.json; \ chmod 0444 /app/release.json +# A imagem do Caddy (Dockerfile.caddy), fixada por digest num arquivo à parte: +# o release.json fica com o formato que os servidores já instalados conferem. +# Com ela, o update.sh roda o web dessa imagem e só o recria quando ela ou o +# Caddyfile mudam. Sem o argumento, nada muda e não há caddy.json. +ARG VARANDA_CADDY_IMAGE="" +RUN set -eu; \ + [ -n "$VARANDA_CADDY_IMAGE" ] || exit 0; \ + [ -n "$VARANDA_COMMIT" ] || { echo 'caddy.json: VARANDA_CADDY_IMAGE exige VARANDA_COMMIT' >&2; exit 1; }; \ + digest="${VARANDA_CADDY_IMAGE#ghcr.io/varanda-org/varanda-caddy@sha256:}"; \ + case "$digest" in ''|*[!0-9a-f]*) echo 'caddy.json: VARANDA_CADDY_IMAGE inválido' >&2; exit 1 ;; esac; \ + if [ "$digest" = "$VARANDA_CADDY_IMAGE" ] || [ "${#digest}" -ne 64 ]; then \ + echo 'caddy.json: VARANDA_CADDY_IMAGE inválido' >&2; exit 1; \ + fi; \ + printf '{"v":1,"caddy":"%s"}\n' "$VARANDA_CADDY_IMAGE" > /app/caddy.json; \ + chmod 0444 /app/caddy.json USER node VOLUME /data # SIGTERM fecha o semeador (store, quarentena e lock) e ele sai com 0. diff --git a/deploy/seeder/compose.release.web.yaml b/deploy/seeder/compose.release.web.yaml index e5e7a41b2..183128b61 100644 --- a/deploy/seeder/compose.release.web.yaml +++ b/deploy/seeder/compose.release.web.yaml @@ -5,6 +5,8 @@ # fica, mas nunca é usado (o atualizador passa sempre --no-build), e as # variáveis de ambiente continuam só em compose.web.yaml. Os binds relativos # ./Caddyfile e ./www resolvem dentro do diretório da versão, que tem os dois. +# Quando a versão traz a imagem do Caddy (caddy.json), o update.sh passa ela +# em VARANDA_WEB_IMAGE e os binds fixos de compose.web.yaml. # docker compose -p varanda-seeder -f compose.yaml -f compose.web.yaml \ # -f compose.release.yaml -f compose.release.web.yaml up -d --no-build services: diff --git a/deploy/seeder/compose.web.yaml b/deploy/seeder/compose.web.yaml index af5153025..5aa6769cb 100644 --- a/deploy/seeder/compose.web.yaml +++ b/deploy/seeder/compose.web.yaml @@ -72,10 +72,15 @@ services: # Chave pública da associação, servida em /varanda.json (Caddyfile). VARANDA_ASSOCIATION: "${VARANDA_ASSOCIATION:?defina VARANDA_ASSOCIATION em deploy/seeder/.env}" volumes: - - ./Caddyfile:/etc/caddy/Caddyfile:ro + # Sem as variáveis (deploy.sh e o compose à mão), ./Caddyfile e ./www. + # O update.sh, com a imagem do Caddy, passa caminhos fixos em + # /opt/varanda-release (o Caddyfile por sha256 e o diretório inteiro em + # /srv, onde o link web aponta para o www da versão): uma versão só de + # app não muda nada aqui e o Caddy não é recriado. + - ${VARANDA_CADDYFILE_SRC:-./Caddyfile}:/etc/caddy/Caddyfile:ro # Preenchido por deploy/seeder/build-web.sh (nunca recriado, só o # conteúdo: o mount continua valendo depois de cada atualização). - - ./www:/srv/web:ro + - ${VARANDA_WWW_SRC:-./www}:${VARANDA_WWW_DST:-/srv/web}:ro - caddy-data:/data - caddy-config:/config read_only: true diff --git a/deploy/seeder/deploy.sh b/deploy/seeder/deploy.sh index 1899b6ef2..5d7bb40f0 100755 --- a/deploy/seeder/deploy.sh +++ b/deploy/seeder/deploy.sh @@ -754,15 +754,69 @@ construir_web() { # Publica em www o app que construir_web gerou e conferiu. Fica para depois # do build da imagem: se ele falhar, o site nunca serviu o app novo. publicar_web() { - local base="$root/.deploy-build" - # www é um bind mount: troca-se o conteúdo, nunca o diretório. - www_trocado=1 - find "$www" -mindepth 1 -delete - copiar_app "$base/src/apps/app/dist" "$www" - publicar_associacoes + local base="$root/.deploy-build" novo="$root/.deploy-www" + # O app inteiro primeiro ao lado, com as associações e o version.json, e + # só então em www (mesclar_www): o Caddy nunca serve um www vazio. + rm -rf "$novo" + mkdir -m 0755 "$novo" + copiar_app "$base/src/apps/app/dist" "$novo" + gravar_associacoes "$novo" # Root refaz os bytes a partir do $target conferido; nunca os lê da cópia. - gravar_versao "$www" "$target" - rm -rf "$base" + gravar_versao "$novo" "$target" + www_trocado=1 + mesclar_www "$novo" "$www" + rm -rf "$novo" "$base" +} + +# Põe em $2 (www, um bind mount: troca-se o conteúdo, nunca o diretório) o +# conteúdo de $1, que fica intacto. Nada é apagado antes: cada arquivo entra +# por uma cópia ao lado e um rename, que é atômico, primeiro tudo o que a +# página carrega, depois sw.js e por último index.html; só então sai o que $1 +# não tem. Quem pede um arquivo no meio da troca recebe a versão antiga ou a +# nova dele, nunca um 404 de um www vazio. $1 é um caminho absoluto. +mesclar_www() { + local novo=$1 destino=$2 + ( + # Chamada dentro de um `if !` (a volta), o bash ignora o errexit aqui + # dentro: cada passo confere o próprio status. + set -Eeuo pipefail + cd "$novo" || exit 1 + # Um caminho que muda de tipo (arquivo virou pasta, ou o contrário) sai + # antes; é o único que fica um instante ausente. + instalar() { + local rel=$1 tmp + tmp="$destino/${rel%/*}/.${rel##*/}.mesclar" + # Um link no lugar sai antes: o mv o seguiria e gravaria fora de www. + if [ -L "$destino/$rel" ]; then + rm -f "$destino/$rel" || return 1 + elif [ -d "$destino/$rel" ]; then + rm -rf "${destino:?}/$rel" || return 1 + fi + rm -rf "$tmp" || return 1 + cp -a "$novo/$rel" "$tmp" && mv -f "$tmp" "$destino/$rel" + } + find . -mindepth 1 -type d -print0 | while IFS= read -r -d '' rel; do + if [ -L "$destino/$rel" ] || { [ -e "$destino/$rel" ] && [ ! -d "$destino/$rel" ]; }; then + rm -f "$destino/$rel" || exit 1 + fi + mkdir -p "$destino/$rel" || exit 1 + done || exit 1 + find . ! -type d ! -path ./sw.js ! -path ./index.html -print0 | while IFS= read -r -d '' rel; do + instalar "$rel" || exit 1 + done || exit 1 + for rel in ./sw.js ./index.html; do + if [ -e "$rel" ] || [ -L "$rel" ]; then + instalar "$rel" || exit 1 + fi + done + cd "$destino" || exit 1 + find . -mindepth 1 -depth -print0 | while IFS= read -r -d '' rel; do + if [ -e "$novo/$rel" ] || [ -L "$novo/$rel" ]; then + continue + fi + rm -rf "${destino:?}/$rel" || exit 1 + done || exit 1 + ) } # Os arquivos de associação do app nativo, em www/.well-known, com os valores @@ -811,7 +865,7 @@ voltar() { # diz. Só diagnóstico: o resultado não muda a volta. compose run --rm --no-deps -T web caddy adapt --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null fi - rm -rf "$root/.deploy-build" + rm -rf "$root/.deploy-build" "$root/.deploy-www" if ! git reset -q --hard "$previous"; then falhas=$((falhas + 1)) @@ -825,11 +879,11 @@ voltar() { log "volta: sem registro da versão anterior; confira se $previous é o commit que rodava" fi if [ "$www_trocado" = 1 ]; then - # www é um bind mount: troca-se o conteúdo, nunca o diretório. A página - # anterior também entra por último, depois do nó dela (copiar_app). + # www é um bind mount: troca-se o conteúdo, nunca o diretório. A cópia + # guardada entra como no deploy (mesclar_www, com dono, modo e data dela): + # sem apagar antes, e a página anterior por último, depois do nó dela. if ! { mkdir -p "$www" \ - && find "$www" -mindepth 1 -delete \ - && copiar_app "$state/www-anterior" "$www" -a; }; then + && mesclar_www "$state/www-anterior" "$www"; }; then falhas=$((falhas + 1)) log "volta: restaurar deploy/seeder/www falhou (a cópia está em $state/www-anterior)" fi @@ -945,8 +999,7 @@ main() { # Daqui em diante, qualquer falha volta para a versão anterior. Cada passo é # um comando solto (fora de if, || e &&) para que a falha chegue ao trap. - # Um Ctrl-C ou SIGTERM no meio (a troca de www esvazia o diretório antes de - # copiar) também volta. + # Um Ctrl-C ou SIGTERM no meio (com o www em parte trocado) também volta. log "implantando $target (antes: $previous)" trap voltar ERR trap 'voltar sinal' INT TERM diff --git a/deploy/seeder/update.sh b/deploy/seeder/update.sh index 6d2abcdd4..50cec1fcc 100755 --- a/deploy/seeder/update.sh +++ b/deploy/seeder/update.sh @@ -24,7 +24,8 @@ # assinada (cosign keyless) pelo workflow do canal em main. A assinatura é # conferida com o cosign fixado no cosign.ref ao lado deste script (nunca o # da imagem candidata), e o release.json da imagem assinada fixa por digest a -# imagem da web. Passo a passo no README, seção "Atualização por imagem (pull)". +# imagem da web (e o caddy.json, quando existe, a do Caddy). Passo a passo no +# README, seção "Atualização por imagem (pull)". # # Códigos de saída: 0 feito ou nada a fazer; 1 falha (nada mudou, ou voltou # para a versão anterior); 2 uso errado. @@ -67,6 +68,12 @@ web_ref_re='^ghcr\.io/varanda-org/varanda-web@sha256:[0-9a-f]{64}$' # A linha inteira de /app/release.json (sem jq no servidor): chaves nesta # ordem, sem espaços, a web só de ghcr.io/varanda-org/varanda-web por digest. release_re='^\{"v":1,"commit":"([0-9a-f]{40})","seq":([1-9][0-9]{0,9}),"web":"(ghcr\.io/varanda-org/varanda-web@sha256:[0-9a-f]{64})"\}$' +# A imagem do Caddy, fixada por digest em /app/caddy.json, um arquivo à parte: +# o release.json fica como era, porque o update.sh das versões já instaladas o +# confere com a regex acima e recusaria uma chave nova. Sem caddy.json (versão +# antiga), o Caddy roda da imagem web e é recriado a cada versão, como antes. +caddy_ref_re='^ghcr\.io/varanda-org/varanda-caddy@sha256:[0-9a-f]{64}$' +caddy_json_re='^\{"v":1,"caddy":"(ghcr\.io/varanda-org/varanda-caddy@sha256:[0-9a-f]{64})"\}$' cosign_re='^ghcr\.io/sigstore/cosign/cosign:v[0-9]+\.[0-9]+\.[0-9]+@sha256:[0-9a-f]{64}$' # Dono root e nenhum acesso de grupo ou outros (saída de dono_modo). privado_re='^0 ([0-7]*00|0)$' @@ -146,6 +153,8 @@ cand_seeder='' cand_commit='' cand_seq='' cand_web='' +# Vazio quando a imagem não traz /app/caddy.json. +cand_caddy='' cand_dir='' em_dia=0 # 1 quando preparar_versao substituiu um diretório que já existia. @@ -157,6 +166,10 @@ piso_preparada=1 alvo_dir='' alvo_seeder='' alvo_web='' +# Com a imagem do Caddy, o web roda dela e monta o www e o Caddyfile por +# caminhos fixos em $releases (trocar_web): uma versão só de app não recria o +# Caddy. Vazio, o web roda da imagem web e monta o diretório da versão. +alvo_caddy='' alvo_checkout=0 www='' caddyfile='' @@ -166,6 +179,7 @@ r_commit='' r_seq='' r_seeder='' r_web='' +r_caddy='' # Abre uma conexão WebSocket de verdade, com o Origin de produção, usando o # ws da própria CLI dentro da imagem do semeador (que confere o TLS). Os @@ -405,12 +419,14 @@ ler_estado() { } # Lê commit, seq, seeder e web de um registro (atual, anterior, preparada) e -# confere a forma de cada um; fora dela, retorna 1. +# confere a forma de cada um; fora dela, retorna 1. O caddy é opcional (um +# registro de antes da imagem do Caddy não o tem), mas, se existe, tem forma. ler_registro() { r_commit='' r_seq='' r_seeder='' r_web='' + r_caddy='' if [ ! -f "$1" ]; then return 1 fi @@ -418,14 +434,18 @@ ler_registro() { r_seq=$(ler_estado "$1" seq) r_seeder=$(ler_estado "$1" seeder) r_web=$(ler_estado "$1" web) + r_caddy=$(ler_estado "$1" caddy) [[ $r_commit =~ $sha_re ]] && [[ $r_seq =~ $seq_re ]] \ - && [[ $r_seeder =~ $seeder_ref_re ]] && [[ $r_web =~ $web_ref_re ]] + && [[ $r_seeder =~ $seeder_ref_re ]] && [[ $r_web =~ $web_ref_re ]] \ + && { [ -z "$r_caddy" ] || [[ $r_caddy =~ $caddy_ref_re ]]; } } -# Grava um registro de estado com um rename: nunca fica pela metade. +# Grava um registro de estado com um rename: nunca fica pela metade. A linha +# caddy= só existe quando a versão traz a imagem do Caddy. gravar_estado() { - local destino=$1 - if ! { printf 'commit=%s\nseq=%s\nseeder=%s\nweb=%s\n' "$2" "$3" "$4" "$5" >"$destino.tmp" \ + local destino=$1 caddy=${6:-} + if ! { { printf 'commit=%s\nseq=%s\nseeder=%s\nweb=%s\n' "$2" "$3" "$4" "$5" \ + && if [ -n "$caddy" ]; then printf 'caddy=%s\n' "$caddy"; fi; } >"$destino.tmp" \ && mv -f "$destino.tmp" "$destino"; }; then rm -f "$destino.tmp" 2>/dev/null || true log "não foi possível gravar $destino" @@ -557,6 +577,41 @@ ler_release() { rm -f "$arquivo" } +# /app/caddy.json da mesma imagem conferida, lido do mesmo jeito. Ausente +# (test -e sai com 1), a versão segue com o Caddy da imagem web, como antes; +# qualquer outra saída (docker, imagem) adia a troca, como um release.json +# ilegível. Presente, precisa ser exatamente uma linha na forma de +# caddy_json_re mais LF. +ler_caddy() { + local arquivo="$state/caddy.json.tmp" linha='' saida=0 + cand_caddy='' + rm -f "$arquivo" + docker run --rm --network none --read-only --cap-drop ALL --security-opt no-new-privileges \ + --entrypoint test "$cand_seeder" -e /app/caddy.json 2>/dev/null || saida=$? + if [ "$saida" = 1 ]; then + log "sem /app/caddy.json em $cand_seeder: o Caddy segue a imagem web" + return 0 + fi + if [ "$saida" != 0 ] || ! docker run --rm --network none --read-only --cap-drop ALL --security-opt no-new-privileges \ + --entrypoint cat "$cand_seeder" /app/caddy.json 2>/dev/null | head -c 1024 >"$arquivo" \ + || [ ! -s "$arquivo" ]; then + rm -f "$arquivo" + log "não foi possível ler /app/caddy.json de $cand_seeder (saída $saida); nada mudou" + return 1 + fi + IFS= read -r linha <"$arquivo" || true + if [[ $linha =~ $caddy_json_re ]] && printf '%s\n' "$linha" | cmp -s - "$arquivo"; then + cand_caddy=${linha#*\"caddy\":\"} + cand_caddy=${cand_caddy%\"\}} + fi + rm -f "$arquivo" + if ! [[ $cand_caddy =~ $caddy_ref_re ]]; then + cand_caddy='' + log "caddy.json de $cand_seeder fora do formato esperado" + return 1 + fi +} + # Sem versão instalada, o piso é a preparada ou a anterior (uma volta ao # checkout apaga atual): mais antiga é recusada; a mesma vale, porque o # primeiro apply usa a versão que install preparou. install --image de uma @@ -606,7 +661,7 @@ verificar() { if ! verificar_assinatura "$cand_seeder"; then return 1 fi - if ! ler_release; then + if ! ler_release || ! ler_caddy; then return 1 fi if [ -f "$state/atual" ]; then @@ -622,7 +677,7 @@ verificar() { elif ! piso_sem_atual; then return 1 fi - if ! gravar_estado "$state/disponivel" "$cand_commit" "$cand_seq" "$cand_seeder" "$cand_web"; then + if ! gravar_estado "$state/disponivel" "$cand_commit" "$cand_seq" "$cand_seeder" "$cand_web" "$cand_caddy"; then return 1 fi log "versão verificada: $cand_commit (seq $cand_seq, canal $canal)" @@ -1246,9 +1301,17 @@ restaurar_segredos() { # fixadas por digest. Sempre --no-build em quem sobe (o build dos compose # nunca é usado aqui) e nunca --remove-orphans: ele removeria os contêineres # avulsos de um docker compose run do operador. +# +# Com a imagem do Caddy ($4), o web roda dela e monta caminhos que não mudam +# de uma versão para outra: $releases inteiro em /srv (o Caddyfile serve +# /srv/web, o link $releases/web que trocar_web aponta para /www) e o +# Caddyfile por um nome que é o sha256 do conteúdo. Assim o compose só recria +# o web quando a imagem do Caddy ou o Caddyfile mudam. Sem ela, os binds +# relativos ./Caddyfile e ./www do diretório da versão, como antes. compose_em() { - local dir=$1 seeder=$2 web=$3 real - shift 3 + local dir=$1 seeder=$2 web=$3 caddy=$4 real soma + local caddyfile_src=./Caddyfile www_src=./www www_dst=/srv/web + shift 4 local -a arquivos=(-f compose.yaml) local -a envs=() if [ "$perfil" = full ]; then @@ -1262,13 +1325,68 @@ compose_em() { envs=(--env-file "$env_file") fi real=$(readlink -f "$dir") || return 1 + if [ "$perfil" = full ] && [ -n "$caddy" ]; then + soma=$(soma_caddyfile "$real/Caddyfile") || return 1 + web=$caddy + caddyfile_src="$releases/Caddyfile-$soma" + www_src=$releases + www_dst=/srv + fi ( cd "$real" && - VARANDA_SEEDER_IMAGE=$seeder VARANDA_WEB_IMAGE=$web \ + VARANDA_CADDYFILE_SRC=$caddyfile_src VARANDA_WWW_SRC=$www_src VARANDA_WWW_DST=$www_dst \ + VARANDA_SEEDER_IMAGE=$seeder VARANDA_WEB_IMAGE=$web \ docker compose -p varanda-seeder ${envs[@]+"${envs[@]}"} "${arquivos[@]}" "$@" ) } +# O sha256 de um Caddyfile (64 hexadecimais), o nome da cópia em $releases. +soma_caddyfile() { + local saida + if ! saida=$(sha256sum <"$1") || ! [[ ${saida%% *} =~ $hash_re ]]; then + log "não foi possível calcular o sha256 de $1" >&2 + return 1 + fi + printf '%s\n' "${saida%% *}" +} + +# Link simbólico trocado por rename, como current: nunca some no meio. +trocar_link() { + rm -f "$2.tmp" + ln -s "$1" "$2.tmp" && mv -Tf "$2.tmp" "$2" +} + +# O que o web monta no modo da imagem do Caddy, apontado para a versão em $1: +# a cópia do Caddyfile por sha256 (escrita uma vez, por rename, nunca alterada +# depois) e o link $releases/web, relativo para valer também dentro do +# contêiner (/srv/web -> /srv//www). O link troca num rename, então o +# Caddy nunca serve um www pela metade, e o www antigo fica inteiro em disco. +trocar_web() { + local dir=$1 nome soma destino + nome=${dir##*/} + if ! soma=$(soma_caddyfile "$dir/Caddyfile"); then + return 1 + fi + destino="$releases/Caddyfile-$soma" + # Um compose up sem o arquivo deixaria um diretório no lugar dele. + if [ -L "$destino" ] || { [ -e "$destino" ] && [ ! -f "$destino" ]; }; then + rm -rf "$destino" + fi + if [ ! -f "$destino" ]; then + rm -f "$destino.tmp" + if ! { cp "$dir/Caddyfile" "$destino.tmp" && chmod 0644 "$destino.tmp" \ + && mv -f "$destino.tmp" "$destino"; }; then + rm -f "$destino.tmp" 2>/dev/null || true + log "não foi possível gravar $destino" + return 1 + fi + fi + if ! trocar_link "$nome/www" "$releases/web"; then + log "não foi possível apontar $releases/web para $nome/www" + return 1 + fi +} + # O compose do alvo atual: uma versão, ou o checkout antigo (com o .env, o # Caddyfile e o www dele, o mesmo comando de deploy.sh). compose_alvo() { @@ -1282,7 +1400,7 @@ compose_alvo() { # pelo trap ERR devolve o status que disparou o trap. return $? fi - compose_em "$alvo_dir" "$alvo_seeder" "$alvo_web" "$@" + compose_em "$alvo_dir" "$alvo_seeder" "$alvo_web" "$alvo_caddy" "$@" } alvo_versao() { @@ -1290,6 +1408,7 @@ alvo_versao() { alvo_dir=$1 alvo_seeder=$2 alvo_web=$3 + alvo_caddy=${4:-} www="$1/www" caddyfile="$1/Caddyfile" } @@ -1301,6 +1420,7 @@ alvo_do_checkout() { alvo_dir=$1 alvo_seeder=varanda-seeder:antes-do-pull alvo_web=varanda-caddy:antes-do-pull + alvo_caddy='' www="$1/www" caddyfile="$1/Caddyfile" if [ "$perfil" = full ] && [ -f "$1/.env" ]; then @@ -1447,6 +1567,10 @@ em_uso() { return 0 fi fi + # O www que o Caddy serve pelo link web. + if [ "$(readlink "$releases/web" 2>/dev/null || true)" = "$nome/www" ]; then + return 0 + fi montado "$dir" } @@ -1527,7 +1651,7 @@ montar_versao() { rm -rf "$tmp" return 1 fi - if ! compose_em "$tmp" "$cand_seeder" "$cand_web" config -q; then + if ! compose_em "$tmp" "$cand_seeder" "$cand_web" "$cand_caddy" config -q; then log "docker compose config recusou a versão $cand_commit; nada mudou" rm -rf "$tmp" return 1 @@ -1757,7 +1881,7 @@ sondar_ws() { # Cada serviço do perfil roda a imagem do alvo (pelo id): um compose up que # não recriou um contêiner não passa. conferir_imagens() { - local id_seeder id_web servico esperado cid img + local id_seeder id_web servico esperado cid img img_web=${alvo_caddy:-$alvo_web} local -a servicos=(seeder) if ! id_seeder=$(docker image inspect -f '{{.Id}}' "$alvo_seeder") || [ -z "$id_seeder" ]; then log "não foi possível ler o id de $alvo_seeder" @@ -1766,8 +1890,8 @@ conferir_imagens() { id_web='' if [ "$perfil" = full ]; then servicos+=(account web) - if ! id_web=$(docker image inspect -f '{{.Id}}' "$alvo_web") || [ -z "$id_web" ]; then - log "não foi possível ler o id de $alvo_web" + if ! id_web=$(docker image inspect -f '{{.Id}}' "$img_web") || [ -z "$id_web" ]; then + log "não foi possível ler o id de $img_web" return 1 fi fi @@ -1811,11 +1935,14 @@ verificar_saude() { log 'saúde: health 200, imagens conferidas' } -# Mantém só o diretório da versão nova, o de current e o da anterior. +# Mantém só o diretório da versão nova, o de current, o da anterior e o que +# o link web serve, e só as cópias do Caddyfile que um deles ainda usa. limpar_versoes() { - local p nome manter_atual='' manter_ant='' + local p nome manter_atual='' manter_ant='' manter_web='' somas='' soma manter_atual=$(readlink "$releases/current" 2>/dev/null || true) manter_atual=${manter_atual##*/} + manter_web=$(readlink "$releases/web" 2>/dev/null || true) + manter_web=${manter_web%/www} if [ -f "$state/anterior" ] && [ "$(ler_estado "$state/anterior" origem)" != checkout ]; then manter_ant=$(ler_estado "$state/anterior" commit) fi @@ -1824,11 +1951,32 @@ limpar_versoes() { if ! [[ $nome =~ ^[0-9a-f]{40}(\.tmp)?$ ]]; then continue fi - if [ "$nome" = "$cand_commit" ] || [ "$nome" = "$manter_atual" ] || [ "$nome" = "$manter_ant" ]; then + if [ "$nome" = "$cand_commit" ] || [ "$nome" = "$manter_atual" ] || [ "$nome" = "$manter_ant" ] \ + || [ "$nome" = "$manter_web" ]; then continue fi rm -rf "$p" || log "aviso: não foi possível apagar $p" done + # Uma soma que falha deixa todas as cópias: sem ela, a cópia de uma versão + # mantida pareceria sobra. + for p in "$releases"/*/Caddyfile; do + if [ ! -f "$p" ]; then + continue + fi + if ! soma=$(soma_caddyfile "$p"); then + log "aviso: as cópias $releases/Caddyfile-* ficam até a próxima limpeza" + return 0 + fi + somas="$somas $soma " + done + for p in "$releases"/Caddyfile-*; do + nome=${p##*/Caddyfile-} + if ! [[ $nome =~ $hash_re ]]; then + continue + fi + case $somas in *" $nome "*) continue ;; esac + rm -f "$p" || log "aviso: não foi possível apagar $p" + done } # O docker image prune não apaga uma imagem baixada por digest no store do @@ -1842,11 +1990,11 @@ apagar_imagens_velhas() { fi for ref in "$state/atual" "$state/anterior"; do if [ -f "$ref" ]; then - manter="$manter $(ler_estado "$ref" seeder) $(ler_estado "$ref" web) " + manter="$manter $(ler_estado "$ref" seeder) $(ler_estado "$ref" web) $(ler_estado "$ref" caddy) " fi done - for ref in "$(ler_estado "$f" seeder)" "$(ler_estado "$f" web)"; do - if ! [[ $ref =~ $seeder_ref_re ]] && ! [[ $ref =~ $web_ref_re ]]; then + for ref in "$(ler_estado "$f" seeder)" "$(ler_estado "$f" web)" "$(ler_estado "$f" caddy)"; do + if ! [[ $ref =~ $seeder_ref_re ]] && ! [[ $ref =~ $web_ref_re ]] && ! [[ $ref =~ $caddy_ref_re ]]; then continue fi case $manter in *" $ref "*) continue ;; esac @@ -1872,8 +2020,8 @@ concluir() { if ! trocar_atual "$cand_dir"; then log "aviso: não foi possível apontar $releases/current para $cand_dir" fi - if ! gravar_estado "$state/atual" "$cand_commit" "$cand_seq" "$cand_seeder" "$cand_web"; then - marcar_intervencao "atualizado para $cand_commit e saudável, mas $state/atual não foi gravado: grave-o à mão (commit=, seq=, seeder=, web=)$depois" + if ! gravar_estado "$state/atual" "$cand_commit" "$cand_seq" "$cand_seeder" "$cand_web" "$cand_caddy"; then + marcar_intervencao "atualizado para $cand_commit e saudável, mas $state/atual não foi gravado: grave-o à mão (commit=, seq=, seeder=, web=${cand_caddy:+, caddy=})$depois" exit 1 fi apagar_imagens_velhas @@ -1927,9 +2075,12 @@ aplicar() { if [ "$perfil" = full ] && ! garantir_imagem "$cand_web"; then exit 1 fi + if [ "$perfil" = full ] && [ -n "$cand_caddy" ] && ! garantir_imagem "$cand_caddy"; then + exit 1 + fi if ! etiquetar_rodando seeder varanda-seeder:anterior || ! etiquetar_rodando web varanda-caddy:anterior \ || ! docker image tag "$cand_seeder" varanda-seeder:atual \ - || { [ "$perfil" = full ] && ! docker image tag "$cand_web" varanda-caddy:atual; }; then + || { [ "$perfil" = full ] && ! docker image tag "${cand_caddy:-$cand_web}" varanda-caddy:atual; }; then log 'não foi possível etiquetar as imagens; nada do que roda mudou' exit 1 fi @@ -1956,7 +2107,7 @@ aplicar() { log "não foi possível trocar $segredos/efetivo.env; nada do que roda mudou" exit 1 fi - alvo_versao "$cand_dir" "$cand_seeder" "$cand_web" + alvo_versao "$cand_dir" "$cand_seeder" "$cand_web" "$cand_caddy" log "aplicando $cand_commit (seq $cand_seq)" # Cada passo é um comando solto (fora de if, || e &&) para que a falha # chegue ao trap. @@ -1966,7 +2117,17 @@ aplicar() { fi trap voltar ERR trap 'voltar sinal' INT TERM - compose_alvo up -d --no-build ${recriacao[@]+"${recriacao[@]}"} + if [ "$perfil" = full ] && [ -n "$cand_caddy" ]; then + # Primeiro o semeador e o serviço de conta, depois o www e o Caddyfile + # trocam por rename, e por fim o web, que o compose só recria se a imagem + # do Caddy ou o Caddyfile mudaram (o recriar não vale para ele: o web não + # monta o diretório da versão). + compose_alvo up -d --no-build ${recriacao[@]+"${recriacao[@]}"} seeder account + trocar_web "$cand_dir" + compose_alvo up -d --no-build web + else + compose_alvo up -d --no-build ${recriacao[@]+"${recriacao[@]}"} + fi verificar_saude trap - ERR INT TERM concluir @@ -1985,7 +2146,8 @@ voltar_versao() { return 1 fi log "voltando para $r_commit" - if ! garantir_imagem "$r_seeder" || { [ "$perfil" = full ] && ! garantir_imagem "$r_web"; }; then + if ! garantir_imagem "$r_seeder" || { [ "$perfil" = full ] && ! garantir_imagem "$r_web"; } \ + || { [ "$perfil" = full ] && [ -n "$r_caddy" ] && ! garantir_imagem "$r_caddy"; }; then marcar_intervencao "as imagens da versão anterior ($r_commit) não estão disponíveis" return 1 fi @@ -1994,10 +2156,29 @@ voltar_versao() { marcar_intervencao "não foi possível restaurar $segredos/efetivo.env da versão anterior ($r_commit)" return 1 fi - alvo_versao "$dir" "$r_seeder" "$r_web" - if ! compose_alvo up -d --no-build --force-recreate; then + alvo_versao "$dir" "$r_seeder" "$r_web" "$r_caddy" + if [ "$perfil" = full ] && [ -n "$r_caddy" ]; then + # O www e o Caddyfile da anterior voltam por rename; o web volta para a + # imagem do Caddy e o Caddyfile dela, e o compose só o recria se um dos + # dois mudou. + if ! compose_alvo up -d --no-build --force-recreate seeder account; then + falhas=$((falhas + 1)) + log 'volta: compose up falhou' + fi + if ! trocar_web "$dir"; then + falhas=$((falhas + 1)) + log 'volta: não foi possível apontar o www e o Caddyfile para a versão anterior' + elif ! compose_alvo up -d --no-build web; then + falhas=$((falhas + 1)) + log 'volta: compose up do web falhou' + fi + elif ! compose_alvo up -d --no-build --force-recreate; then falhas=$((falhas + 1)) log 'volta: compose up falhou' + else + # O web voltou a montar o www da própria versão: o link não segura mais + # a versão que falhou. + rm -f "$releases/web" || log "aviso: não foi possível apagar $releases/web" fi if ! verificar_saude; then falhas=$((falhas + 1)) @@ -2039,6 +2220,8 @@ voltar_checkout() { if ! compose_alvo up -d --no-build --force-recreate; then falhas=$((falhas + 1)) log 'volta: compose up no checkout falhou' + else + rm -f "$releases/web" || log "aviso: não foi possível apagar $releases/web" fi if ! verificar_saude; then falhas=$((falhas + 1)) @@ -2138,7 +2321,8 @@ subir_instalada() { return 1 fi adiar_google=0 - if ! garantir_imagem "$r_seeder" || { [ "$perfil" = full ] && ! garantir_imagem "$r_web"; }; then + if ! garantir_imagem "$r_seeder" || { [ "$perfil" = full ] && ! garantir_imagem "$r_web"; } \ + || { [ "$perfil" = full ] && [ -n "$r_caddy" ] && ! garantir_imagem "$r_caddy"; }; then return 1 fi if ! conferir_arvore "$dir" || ! preparar_segredos "$r_seeder" "$dir"; then @@ -2164,7 +2348,10 @@ subir_instalada() { log "não foi possível trocar $segredos/efetivo.env; nada mudou" return 1 fi - alvo_versao "$dir" "$r_seeder" "$r_web" + alvo_versao "$dir" "$r_seeder" "$r_web" "$r_caddy" + if [ "$perfil" = full ] && [ -n "$r_caddy" ] && ! trocar_web "$dir"; then + return 1 + fi if ! compose_alvo up -d --no-build "$@"; then log 'compose up falhou' return 1 @@ -2306,7 +2493,7 @@ cmd_rollback() { fi case $rc in 0) - if ! gravar_estado "$state/atual" "$r_commit" "$r_seq" "$r_seeder" "$r_web"; then + if ! gravar_estado "$state/atual" "$r_commit" "$r_seq" "$r_seeder" "$r_web" "$r_caddy"; then marcar_intervencao "voltou para $r_commit, mas $state/atual não foi gravado" exit 1 fi @@ -2378,7 +2565,7 @@ cmd_compose() { if [ ! -d "$releases/current" ]; then morrer_cedo 1 "$releases/current não existe" fi - compose_em "$releases/current" "$r_seeder" "$r_web" "$@" + compose_em "$releases/current" "$r_seeder" "$r_web" "$r_caddy" "$@" } instalar_unidades() { @@ -2521,7 +2708,7 @@ cmd_install() { log "não foi possível gravar $segredos/efetivo.env; nada foi iniciado" exit 1 fi - if ! gravar_estado "$state/preparada" "$cand_commit" "$cand_seq" "$cand_seeder" "$cand_web"; then + if ! gravar_estado "$state/preparada" "$cand_commit" "$cand_seq" "$cand_seeder" "$cand_web" "$cand_caddy"; then log "não foi possível registrar a versão preparada em $cand_dir" exit 1 fi diff --git a/docs/changelog/fix-caddy-stays-up.md b/docs/changelog/fix-caddy-stays-up.md new file mode 100644 index 000000000..40a3fde5e --- /dev/null +++ b/docs/changelog/fix-caddy-stays-up.md @@ -0,0 +1 @@ +- O Caddy fica no ar nas atualizações por imagem que só mudam o código (PR `fix/caddy-stays-up`): o `release` publica a imagem `ghcr.io/varanda-org/varanda-caddy` (de `deploy/seeder/Dockerfile.caddy`) e grava o digest dela em `/app/caddy.json` na imagem assinada do semeador. No perfil `full`, o `update.sh` roda o `web` com essa imagem, monta o `Caddyfile` por um caminho que só muda com o conteúdo e o app pelo link `/opt/varanda-release/web`, trocado de uma vez; sobe o semeador e a conta primeiro, troca o link e só recria o Caddy quando o digest dele ou o `Caddyfile` mudou. A verificação de saúde de 180 s e a volta continuam, e a volta põe de novo o Caddy anterior. Uma versão sem `caddy.json` segue o modo antigo; num servidor que já atualiza por imagem, o Caddy ainda é recriado uma vez, na segunda versão com `caddy.json`. O `deploy.sh` monta o app novo ao lado e o troca arquivo a arquivo, sem esvaziar o `www`. Quem mantém precisa tornar público o pacote `varanda-caddy`. Verificação em `docs/verification/fix-caddy-stays-up.md`. diff --git a/docs/verification/fix-caddy-stays-up.md b/docs/verification/fix-caddy-stays-up.md new file mode 100644 index 000000000..753253d68 --- /dev/null +++ b/docs/verification/fix-caddy-stays-up.md @@ -0,0 +1,30 @@ +# O Caddy fica de pé nas atualizações por imagem (branch fix/caddy-stays-up) + +Mudança: o `release.yml` constrói `ghcr.io/varanda-org/varanda-caddy` a partir de `deploy/seeder/Dockerfile.caddy`, com a etiqueta `caddy-` e o rótulo `org.varanda.dockerfile-caddy`, só quando esse arquivo muda (senão reaproveita a imagem assinada cujo rótulo confere), assina e confere a assinatura, e passa o digest ao build do semeador (`--build-arg VARANDA_CADDY_IMAGE`), que grava `/app/caddy.json` (`{"v":1,"caddy":"ghcr.io/varanda-org/varanda-caddy@sha256:<64>"}`); o `release.json` não muda de formato. O `update.sh` lê e valida o `caddy.json` da imagem conferida e o anota no estado (`caddy=`). No perfil `full`, com o `caddy.json`, o serviço `web` roda essa imagem e monta `/opt/varanda-release/Caddyfile-` em `/etc/caddy/Caddyfile` e `/opt/varanda-release` em `/srv`, onde o link relativo `web -> /www` faz `/srv/web` continuar sendo o `root` do `Caddyfile`; a troca sobe `seeder account`, troca o link (link novo e `mv -Tf`) e roda `up -d --no-build web`, que o Compose só recria quando a imagem ou o caminho do `Caddyfile` mudou. A volta faz o mesmo com a versão anterior (o Caddy, o `Caddyfile` e o link dela). Sem `caddy.json`, tudo segue como antes. No `deploy.sh`, `publicar_web` monta o app em `.deploy-www` e `mesclar_www` o põe no `www` arquivo a arquivo (cópia temporária e `mv`, o `sw.js` e o `index.html` por último, depois apaga o que saiu), em vez de apagar o `www` e copiar de novo; a volta usa o mesmo caminho a partir de `www-anterior`. + +## Comandos de teste + +```sh +node apps/cli/test/update.test.js +node apps/cli/test/release.test.js +node apps/cli/test/release-bundle.test.js +node apps/cli/test/web-image.test.js +node apps/cli/test/caddyfile.test.js +node apps/cli/test/deploy.test.js +node apps/cli/test/changelog.test.js +node apps/cli/test/readme-help.test.js +bash -n deploy/seeder/update.sh deploy/seeder/deploy.sh +``` + +Os testes novos de `update.test.js` (versão só de código não recria o Caddy; `Caddyfile` novo o recria; digest novo do Caddy o recria; uma falha volta ao Caddy, ao `Caddyfile` e ao link anteriores; sem `caddy.json`, o modo antigo), os de `release.test.js` (o Caddy só é construído para um `Dockerfile.caddy` novo e fica em `caddy.json`; o `Dockerfile` só grava `caddy.json` com uma imagem do Caddy) e o de `deploy.test.js` (`mesclar_www` troca o `www` sem esvaziá-lo) falham com os arquivos de antes desta mudança: cada um foi rodado com a versão anterior do script ou do fluxo no lugar. + +## Limites conhecidos + +- [ ] Nenhuma VM real exercitada: os testes do `update.sh` rodam com `docker` simulado, e o Compose de verdade não foi exercitado (que ele recria o `web` só quando a imagem ou a origem de uma montagem muda, e não o recria quando nada mudou, é o comportamento documentado, não conferido aqui). +- [ ] Não está verificado que o Caddy segue o link `/srv/web` a cada pedido: o `file_server` resolve o caminho a cada pedido, então ele deve servir a versão nova logo depois da troca, mas isso não foi conferido com um Caddy de verdade. Se ele guardar o caminho resolvido, a versão nova só apareceria na próxima recriação do Caddy. +- [ ] Num servidor que já atualiza por imagem, a primeira versão com `caddy.json` é aplicada pelo `update.sh` antigo, no modo antigo (o Caddy é recriado como sempre); a seguinte, com o `update.sh` novo, recria o Caddy mais uma vez, porque as montagens mudam. Só depois disso ele fica de pé nas versões que só mudam o código. +- [ ] O Caddy passa a enxergar `/opt/varanda-release` inteiro, só leitura: os pacotes das versões, que são públicos. Os segredos ficam em `/var/lib/varanda-update`. +- [ ] Um `update.sh compose up` à mão antes da primeira troca no modo novo pode fazer o Docker criar um diretório no caminho do `Caddyfile`; a troca seguinte o apaga antes de gravar o arquivo. +- [ ] A etiqueta `caddy-` pode ser movida por quem tem escrita no pacote; o `release.yml` só a reaproveita com a assinatura e o rótulo conferidos. +- [ ] Quem mantém precisa tornar público o pacote `varanda-caddy` depois do primeiro `release` que o publicar; sem isso o servidor não baixa a imagem. +- [ ] No `deploy.sh`, um caminho que muda de tipo (arquivo que vira pasta, ou o contrário) fica um instante ausente durante a troca.