Files
canina/scripts/deploy.sh
T
2026-10-23 18:31:23 +00:00

115 lines
5.9 KiB
Bash

#!/bin/bash
set -euo pipefail
set +x
# CI/CD-only Stage rollout; Production awaits separate reviewed authorization.
if [ "${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}}" != true ] || [ "${1:-}" != develop ] || [ "$#" != 1 ]; then
echo 'ERROR: refusing deployment outside CI/CD Stage rollout' >&2
exit 2
fi
if [[ ! "${DEPLOY_SHA:-}" =~ ^[0-9a-f]{40}$ ]]; then
echo 'ERROR: refusing deployment without an immutable commit SHA' >&2
exit 2
fi
# END ROLLOUT GUARD
exec 9>/opt/services/canina/stage-backend-deploy.lock
flock -n 9 || { echo 'Stage deployment already in progress' >&2; exit 1; }
umask 077
export DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1
# Stage is an operational reference, NEVER a checkout/build target.
STAGE_DIR=/opt/services/canina/stage
RELEASE_ROOT=/opt/services/canina/releases
TARGET_DIR="$RELEASE_ROOT/$DEPLOY_SHA"
mkdir -p "$RELEASE_ROOT"
[ ! -L "$RELEASE_ROOT" ] && [ "$(realpath "$RELEASE_ROOT")" = "$RELEASE_ROOT" ]
# Do not overwrite a prior release or retry with stale generated configuration.
mkdir "$TARGET_DIR"
git clone --no-checkout --single-branch --branch develop https://git.parsaaghayi.ir/parsa/canina.git "$TARGET_DIR"
cd "$TARGET_DIR"
git cat-file -e "${DEPLOY_SHA}^{commit}"
git merge-base --is-ancestor "$DEPLOY_SHA" origin/develop
git checkout --detach "$DEPLOY_SHA"
[ "$(git rev-parse HEAD)" = "$DEPLOY_SHA" ]
# Provision against the pristine approved SHA, before any tracked render edits.
source scripts/rollout-stage.sh
if [ "${STAGE_PROVISION_ENABLED:-false}" = true ]; then
stage_runtime_provision
elif [ -e /opt/services/canina/stage-runtime ] && [ "${STAGE_PROVISION_ENABLED:-}" != false ]; then
echo 'ERROR: existing runtime requires explicit Stage CI opt-in on every deploy' >&2
exit 2
fi
# Keep operational files out of status/accidental commits in this disposable clone.
printf '\n.support-chat.env\n.revalidation.env\n.stage-base.json\n.stage-compose.json\n.stage-runtime.json\n.stage-runtime-merged.json\n' >> .git/info/exclude
# Runtime secrets/config must never enter the frontend Docker build context.
printf '\n.support-chat.env\n.revalidation.env\n.stage-*.json\n' >> .dockerignore
# Only these backend/frontend runtime env files are required. Do not copy the
# dirty compose, .env, uploads, bot state, certificates, or arbitrary Stage files.
for name in .support-chat.env .revalidation.env; do
if [ -e "$STAGE_DIR/$name" ] || [ -L "$STAGE_DIR/$name" ]; then
[ -f "$STAGE_DIR/$name" ] && [ ! -L "$STAGE_DIR/$name" ]
[ -z "$(git -C "$STAGE_DIR" ls-files -- "$name")" ]
[ -z "$(git ls-files -- "$name")" ]
install -m 600 "$STAGE_DIR/$name" "$TARGET_DIR/$name"
fi
done
[ -s .support-chat.env ] || { echo 'ERROR: missing Stage support runtime env' >&2; exit 1; }
# Never inspect/recreate/mutate the shared support bot or infer keys from it.
# Certs remain the explicit operational absolute bind from tracked compose.
python3 - <<'PY'
from pathlib import Path
p = Path('nginx.conf')
s = p.read_text()
for key, value in {'__BACKEND_HOST__': 'backend_stage', '__APP_HOST__': 'stage.canina.ir', '__ADMIN_HOST__': 'stageadmin.canina.ir'}.items():
s = s.replace(key, value)
p.write_text(s)
PY
# Wrapper also covers every compose call in the sourced rollout helper. Explicit
# project/files/env-file prevent release-SHA projects and ambient .env loading.
docker() {
if [ "${1:-}" = compose ]; then
shift
command docker compose -p stage --env-file /dev/null --project-directory "$TARGET_DIR" -f "$TARGET_DIR/.stage-compose.json" "$@"
else
command docker "$@"
fi
}
# Render privately: config contains env secrets, so never emit it to CI logs.
command docker compose -p stage --env-file /dev/null --project-directory "$TARGET_DIR" -f scripts/compose.stage.yml config --format json > .stage-base.json
python3 - <<'PY'
import json
from pathlib import Path
config = json.loads(Path('.stage-base.json').read_text())
expected = {'canina_stage_db': 'stage_canina_stage_db', 'canina_stage_uploads': 'stage_canina_stage_uploads'}
if set(config['services']) != {'db_stage', 'redis_stage', 'backend_stage', 'frontend_stage'}:
raise SystemExit('ERROR: unexpected Stage service set')
for key, name in expected.items():
if config['volumes'][key].get('name') != name:
raise SystemExit('ERROR: Stage volume identity mismatch')
config['volumes'][key] = {'name': name, 'external': True}
if config['networks']['traefik_public'].get('name') != 'traefik_public' or not config['networks']['traefik_public'].get('external'):
raise SystemExit('ERROR: Stage network identity mismatch')
backend = config['services']['backend_stage']
if backend['container_name'] != 'canino_backend_stage' or config['services']['frontend_stage']['container_name'] != 'canino_frontend_stage':
raise SystemExit('ERROR: Stage container identity mismatch')
mounts = backend.get('volumes', [])
if not any(m.get('type') == 'volume' and m.get('source') == 'canina_stage_uploads' and m.get('target') == '/app/uploads' for m in mounts):
raise SystemExit('ERROR: missing Stage uploads volume')
for service in config['services'].values():
for mount in service.get('volumes', []):
if mount.get('type') == 'bind' and (mount.get('source'), mount.get('target')) != ('/opt/services/proxy/certs/canina', '/app/ssl_certs'):
raise SystemExit('ERROR: unexpected Stage bind mount')
Path('.stage-compose.json').write_text(json.dumps(config))
Path('.stage-base.json').unlink()
PY
if [ "${STAGE_PROVISION_ENABLED:-false}" = true ]; then
stage_runtime_render
fi
# Read-only checks: missing external storage must fail, never provision blank DB.
docker volume inspect stage_canina_stage_db stage_canina_stage_uploads >/dev/null
docker network inspect traefik_public >/dev/null
[ -d /opt/services/proxy/certs/canina ]
# Builds only app images; DB/Redis and support-bot remain untouched.
docker compose --progress plain build backend_stage frontend_stage
source scripts/rollout-stage.sh
stage_rollout
echo 'Deployment for develop completed successfully!'