From 0f2dee08cb19c82af0b7591a34302662946d3b56 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 23 Jul 2026 08:17:56 +0330 Subject: [PATCH] implement gitlab blue-green ci cd --- .github/workflows/ci.yml | 45 --- .github/workflows/sonarqube.yml | 28 -- .gitlab-ci.yml | 150 ++++++++ README.md | 15 +- deploy/.env.server.example | 5 +- deploy/SERVER_DEPLOYMENT.md | 172 +++++---- deploy/compose.server.yaml | 79 +++-- .../nginx/warehouse-allocation-upstream.conf | 4 + .../nginx/warehouse-allocation.mvphub.ir.conf | 3 +- deploy/scripts/warehouse-allocation-deploy | 325 ++++++++++++++++++ docs/TECHNICAL_DECISIONS.md | 40 ++- pyproject.toml | 4 +- tests/integration/test_redis_live.py | 46 +++ 13 files changed, 686 insertions(+), 230 deletions(-) delete mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/sonarqube.yml create mode 100644 .gitlab-ci.yml create mode 100644 deploy/nginx/warehouse-allocation-upstream.conf create mode 100755 deploy/scripts/warehouse-allocation-deploy create mode 100644 tests/integration/test_redis_live.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 2fa8acf..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: CI - -on: - push: - branches: [main] - pull_request: - -permissions: - contents: read - -jobs: - quality-and-tests: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - cache: pip - - run: pip install -e '.[dev]' - - name: Ruff - run: ruff check . && ruff format --check . - - name: Mypy - run: mypy src - - name: Unit and integration tests - run: pytest --cov-report=xml - - uses: actions/upload-artifact@v4 - with: - name: coverage - path: coverage.xml - - container: - runs-on: ubuntu-latest - needs: quality-and-tests - steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - uses: docker/build-push-action@v6 - with: - context: . - push: false - tags: warehouse-allocation:${{ github.sha }} - cache-from: type=gha - cache-to: type=gha,mode=max - diff --git a/.github/workflows/sonarqube.yml b/.github/workflows/sonarqube.yml deleted file mode 100644 index 25b097c..0000000 --- a/.github/workflows/sonarqube.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: SonarQube - -on: - workflow_dispatch: - push: - branches: [main] - -permissions: - contents: read - -jobs: - scan: - if: ${{ vars.SONAR_HOST_URL != '' }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - run: pip install -e '.[dev]' && pytest --cov-report=xml - - uses: SonarSource/sonarqube-scan-action@v5 - with: - args: -Dsonar.qualitygate.wait=true - env: - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }} diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..5c14557 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,150 @@ +stages: + - validate + - test + - analyze + - container + - package + - deploy + +workflow: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH + - when: never + +default: + interruptible: true + +.python-job: + image: python:3.12-slim + cache: + key: "pip-${CI_COMMIT_REF_SLUG}" + paths: + - .cache/pip + variables: + PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" + PIP_DISABLE_PIP_VERSION_CHECK: "1" + before_script: + - python -m pip install -e '.[dev]' + +quality: + extends: .python-job + stage: validate + script: + - ruff check . + - ruff format --check . + - mypy src + - bash -n deploy/scripts/warehouse-allocation-deploy + - apt-get update -qq + - apt-get install -y --no-install-recommends shellcheck >/dev/null + - shellcheck deploy/scripts/warehouse-allocation-deploy + +tests: + extends: .python-job + stage: test + services: + - name: redis:7.4-alpine + alias: redis + variables: + PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" + PIP_DISABLE_PIP_VERSION_CHECK: "1" + WA_TEST_REDIS_URL: "redis://redis:6379/15" + script: + - pytest --junitxml=junit.xml --cov-report=xml + artifacts: + when: always + expire_in: 14 days + reports: + junit: junit.xml + coverage_report: + coverage_format: cobertura + path: coverage.xml + paths: + - coverage.xml + +sonarqube: + stage: analyze + image: + name: sonarsource/sonar-scanner-cli:11 + entrypoint: [""] + needs: + - job: tests + artifacts: true + variables: + SONAR_USER_HOME: "$CI_PROJECT_DIR/.sonar" + GIT_DEPTH: "0" + cache: + key: sonar + paths: + - .sonar/cache + script: + - sonar-scanner -Dsonar.qualitygate.wait=true + rules: + - if: $SONAR_HOST_URL && $SONAR_TOKEN + - when: never + +container-build: + stage: container + image: + name: gcr.io/kaniko-project/executor:v1.23.2-debug + entrypoint: [""] + script: + - >- + /kaniko/executor + --context "$CI_PROJECT_DIR" + --dockerfile "$CI_PROJECT_DIR/Dockerfile" + --destination "local/warehouse-allocation:${CI_COMMIT_SHA}" + --no-push + +package-release: + stage: package + image: alpine:3.22 + needs: + - quality + - tests + - container-build + - job: sonarqube + optional: true + before_script: + - apk add --no-cache git + script: + - git archive --format=tar.gz --output="release-${CI_COMMIT_SHA}.tar.gz" HEAD + - sha256sum "release-${CI_COMMIT_SHA}.tar.gz" > "release-${CI_COMMIT_SHA}.sha256" + artifacts: + expire_in: 7 days + paths: + - "release-${CI_COMMIT_SHA}.tar.gz" + - "release-${CI_COMMIT_SHA}.sha256" + rules: + - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_COMMIT_REF_PROTECTED == "true"' +deploy-production: + stage: deploy + image: alpine:3.22 + interruptible: false + resource_group: production + needs: + - job: package-release + artifacts: true + environment: + name: production + url: https://warehouse-allocation.mvphub.ir + before_script: + - apk add --no-cache openssh-client + - install -d -m 0700 "$HOME/.ssh" + - install -m 0600 "$DEPLOY_SSH_PRIVATE_KEY" "$HOME/.ssh/id_ed25519" + - install -m 0600 "$DEPLOY_KNOWN_HOSTS" "$HOME/.ssh/known_hosts" + script: + - test "$DEPLOY_HOST" = "188.137.233.91" + - test "$DEPLOY_PORT" = "22" + - test "$DEPLOY_USER" = "warehouse-deploy" + - checksum="$(cut -d ' ' -f 1 "release-${CI_COMMIT_SHA}.sha256")" + - >- + scp -P "$DEPLOY_PORT" -o BatchMode=yes + "release-${CI_COMMIT_SHA}.tar.gz" + "${DEPLOY_USER}@${DEPLOY_HOST}:incoming/release-${CI_COMMIT_SHA}.tar.gz" + - >- + ssh -p "$DEPLOY_PORT" -o BatchMode=yes + "${DEPLOY_USER}@${DEPLOY_HOST}" + "sudo /usr/local/sbin/warehouse-allocation-deploy '${CI_COMMIT_SHA}' '${checksum}'" + rules: + - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_COMMIT_REF_PROTECTED == "true"' diff --git a/README.md b/README.md index 6e22527..dbc6d5e 100644 --- a/README.md +++ b/README.md @@ -182,14 +182,21 @@ make benchmark ## CI/CD و استقرار -GitHub Actions این مراحل را اجرا می‌کند: +GitLab CI روی مخزن اصلی `git.sharifict.com` این مراحل را اجرا می‌کند: 1. نصب وابستگی‌ها از `pyproject.toml`؛ 2. Ruff lint/format، mypy strict؛ -3. unit و integration test با حداقل coverage برابر ۸۵٪؛ +3. unit، integration و Redis واقعی با حداقل coverage برابر ۸۵٪؛ 4. تولید `coverage.xml` و artifact؛ -5. build ایمیج Docker؛ -6. اجرای اختیاری SonarQube با `SONAR_TOKEN` و `SONAR_HOST_URL`. +5. اعتبارسنجی build ایمیج بدون دسترسی privileged؛ +6. اجرای اختیاری و blocking بودن quality gate سونار در صورت تنظیم متغیرها؛ +7. ساخت artifact نسخه‌دار و کنترل checksum؛ +8. استقرار خودکار blue-green روی production پس از موفقیت شاخه محافظت‌شده + `main`. + +در استقرار blue-green، نسخه جدید ابتدا روی slot غیرفعال سالم‌سازی می‌شود، سپس +Nginx به‌صورت graceful به آن سوییچ می‌کند. slot قبلی تا پایان health check و +smoke test عمومی روشن می‌ماند و در صورت خطا rollback خودکار انجام می‌شود. فایل `deploy/kubernetes.yaml` شامل Deployment غیر-root و read-only، probes، resource limits، Service و HPA از ۲ تا ۲۰ replica است. قبل از اعمال، آدرس image و Secret را برای محیط مقصد تنظیم کنید. diff --git a/deploy/.env.server.example b/deploy/.env.server.example index ea3a7e0..6a54cd1 100644 --- a/deploy/.env.server.example +++ b/deploy/.env.server.example @@ -1,3 +1,4 @@ -APP_VERSION=latest WA_INVENTORY_ADMIN_TOKEN=replace-with-a-long-random-secret - +ACTIVE_SLOT=blue +BLUE_IMAGE=local/warehouse-allocation:replace-with-commit-sha +GREEN_IMAGE=local/warehouse-allocation:replace-with-commit-sha diff --git a/deploy/SERVER_DEPLOYMENT.md b/deploy/SERVER_DEPLOYMENT.md index f8d837d..4a629a5 100644 --- a/deploy/SERVER_DEPLOYMENT.md +++ b/deploy/SERVER_DEPLOYMENT.md @@ -1,119 +1,105 @@ # Production deployment: `warehouse-allocation.mvphub.ir` -## Current layout +## Runtime layout | Item | Value | |---|---| -| SSH host | `ict` | | Public URL | `https://warehouse-allocation.mvphub.ir` | | Release root | `/srv/apps/warehouse-allocation` | -| Current release | `/srv/apps/warehouse-allocation/current` | | Shared environment | `/srv/apps/warehouse-allocation/shared/.env` | | Compose project | `warehouse-allocation` | -| API loopback address | `127.0.0.1:18081` | -| Nginx site | `/etc/nginx/sites-available/warehouse-allocation.mvphub.ir` | -| Certificate | `/etc/letsencrypt/live/warehouse-allocation.mvphub.ir` | -| ACME webroot | `/var/www/letsencrypt` | +| Blue slot | `127.0.0.1:18081` | +| Green slot | `127.0.0.1:18082` | +| Shared Redis | `warehouse-allocation-redis-1`, no host port | +| Nginx upstream | `/etc/nginx/conf.d/10-warehouse-allocation-upstream.conf` | +| Restricted account | `warehouse-deploy` | +| Deployment program | `/usr/local/sbin/warehouse-allocation-deploy` | -The API and Redis belong to a dedicated Compose project. Redis has no host port, and -the API port is bound only to loopback. Public traffic can reach it only through -the hostname-specific Nginx reverse proxy. +Only one API slot receives traffic after a deployment. During cutover both slots +run briefly, allowing Nginx to switch without an API interruption. Redis and its +named volume remain shared between releases. + +## GitLab pipeline + +The authoritative pipeline is [`.gitlab-ci.yml`](../.gitlab-ci.yml). It runs +quality checks, tests with a real Redis service, coverage, optional SonarQube, +container build validation, release packaging, and automatic protected-`main` +deployment. + +Required protected GitLab variables: + +| Variable | Type/value | +|---|---| +| `DEPLOY_HOST` | `188.137.233.91` | +| `DEPLOY_PORT` | `22` | +| `DEPLOY_USER` | `warehouse-deploy` | +| `DEPLOY_SSH_PRIVATE_KEY` | File variable containing the dedicated private key | +| `DEPLOY_KNOWN_HOSTS` | File variable containing the pinned server host key | + +Optional SonarQube variables are `SONAR_HOST_URL` and masked `SONAR_TOKEN`. If both +exist, the quality gate becomes mandatory for deployment. + +The CI account has no Docker-group membership and no general sudo access. It may +invoke only the root-owned deployment program through `/etc/sudoers.d`. + +## Deployment transaction + +The deploy job uploads: + +```text +/home/warehouse-deploy/incoming/release-<40-character-commit-sha>.tar.gz +``` + +It then invokes: + +```bash +sudo /usr/local/sbin/warehouse-allocation-deploy +``` + +The program: + +1. serializes deployments with `flock`; +2. validates the commit ID, checksum, and archive paths; +3. extracts an immutable release; +4. builds an exact commit-tagged image while the old slot serves traffic; +5. starts and checks the inactive slot; +6. switches only the warehouse-allocation Nginx upstream; +7. runs public health, OpenAPI, and exact Swagger-example tests twice; +8. commits the active-slot metadata and removes the old API container; +9. retains five recent releases and application images. + +If any step before commit fails, the upstream is restored, Nginx is reloaded, +the failed candidate is removed, and the previous release remains current. ## Status and logs ```bash ssh ict -docker compose \ - --env-file /srv/apps/warehouse-allocation/shared/.env \ - -f /srv/apps/warehouse-allocation/current/deploy/compose.server.yaml \ - ps +source /srv/apps/warehouse-allocation/shared/.env +echo "$ACTIVE_SLOT" +readlink -f /srv/apps/warehouse-allocation/current -docker logs --tail 100 warehouse-allocation-api-1 +docker ps --filter name=warehouse-allocation +docker logs --tail 100 warehouse-allocation-api-blue-1 +docker logs --tail 100 warehouse-allocation-api-green-1 docker logs --tail 100 warehouse-allocation-redis-1 -curl -fsS http://127.0.0.1:18081/health/ready curl -fsS https://warehouse-allocation.mvphub.ir/health/ready nginx -t ``` -Do not print or commit `/srv/apps/warehouse-allocation/shared/.env`. It contains the -inventory administration token. +Do not print or commit the shared `.env`; it contains the inventory administration +token. Do not use the root development `compose.yaml` for production. -## Starting or reconciling the current release +## Manual rollback -```bash -docker compose \ - --env-file /srv/apps/warehouse-allocation/shared/.env \ - -f /srv/apps/warehouse-allocation/current/deploy/compose.server.yaml \ - up -d --build -``` - -The production Compose file is -[`compose.server.yaml`](compose.server.yaml). It must be used instead of the local -root `compose.yaml`, because it provides the isolated loopback port, restart -policy, resource limits, persistent Redis volume, and production environment. - -## Safe release process - -1. Run tests and quality checks locally. -2. Package tracked and required untracked source files without `.env`, `.git`, or - virtual environments. -3. Upload the archive to the server and verify its SHA-256 checksum. -4. Extract it into a new immutable directory under - `/srv/apps/warehouse-allocation/releases/`. -5. Validate the new Compose file using the shared environment. -6. Point `/srv/apps/warehouse-allocation/current` at the new release. -7. Run Compose with `up -d --build`. -8. Wait for both containers to become healthy. -9. Verify loopback health, public HTTPS health, OpenAPI, and one allocation smoke - test. - -Never modify another application's Compose project, loopback port, Nginx site, or -volume as part of this release. - -## Nginx and TLS - -The repository contains: - -- [`nginx/warehouse-allocation.bootstrap.conf`](nginx/warehouse-allocation.bootstrap.conf) - for initial HTTP/ACME validation; -- [`nginx/warehouse-allocation.mvphub.ir.conf`](nginx/warehouse-allocation.mvphub.ir.conf) - for the final HTTP-to-HTTPS redirect and reverse proxy. - -Always run `nginx -t` before `systemctl reload nginx`. A reload is graceful and -must only happen after the full server configuration passes validation. - -The certificate uses Certbot's webroot authenticator. The existing -`certbot.timer` renews it automatically. - -## Rollback - -Identify the prior release first: - -```bash -find /srv/apps/warehouse-allocation/releases -mindepth 1 -maxdepth 1 -type d -print -readlink -f /srv/apps/warehouse-allocation/current -``` - -Point `current` at the explicit prior release, validate Compose, and start it: - -```bash -ln -sfn /srv/apps/warehouse-allocation/releases/ \ - /srv/apps/warehouse-allocation/current - -docker compose \ - --env-file /srv/apps/warehouse-allocation/shared/.env \ - -f /srv/apps/warehouse-allocation/current/deploy/compose.server.yaml \ - config --quiet - -docker compose \ - --env-file /srv/apps/warehouse-allocation/shared/.env \ - -f /srv/apps/warehouse-allocation/current/deploy/compose.server.yaml \ - up -d --build -``` - -Then verify `/health/ready` on loopback and HTTPS. The Redis volume is deliberately -shared between releases, so rolling application code back does not discard -inventory data. +Normal failures roll back automatically before the old slot is stopped. For a +post-deployment application regression, redeploy the desired older commit +artifact through the same deployment program. This performs the same health, +traffic-switch, and rollback protections instead of manually editing Nginx. +The deployment program is scoped to warehouse-allocation release directories, +images, two API containers, and its dedicated upstream file. It never prunes or +restarts bank-flow containers, unrelated images, Nginx sites, certificates, or +volumes. diff --git a/deploy/compose.server.yaml b/deploy/compose.server.yaml index 1e24d0f..0193f05 100644 --- a/deploy/compose.server.yaml +++ b/deploy/compose.server.yaml @@ -1,45 +1,50 @@ name: warehouse-allocation +x-api-common: &api-common + environment: + WA_ENVIRONMENT: production + WA_INVENTORY_BACKEND: redis + WA_REDIS_URL: redis://redis:6379/0 + WA_REDIS_SOCKET_TIMEOUT_SECONDS: "0.08" + WA_MAX_CANDIDATE_WAREHOUSES: "33" + WA_INVENTORY_ADMIN_TOKEN: ${WA_INVENTORY_ADMIN_TOKEN:?inventory admin token is required} + restart: unless-stopped + read_only: true + tmpfs: + - /tmp:size=32m,mode=1777 + security_opt: + - no-new-privileges:true + mem_limit: 384m + healthcheck: + test: + - CMD + - python + - -c + - "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=1)" + interval: 5s + timeout: 2s + retries: 10 + start_period: 10s + logging: + driver: json-file + options: + max-size: 10m + max-file: "3" + services: - api: - build: - context: .. - dockerfile: Dockerfile - image: local/warehouse-allocation:${APP_VERSION:-latest} - environment: - WA_ENVIRONMENT: production - WA_INVENTORY_BACKEND: redis - WA_REDIS_URL: redis://redis:6379/0 - WA_REDIS_SOCKET_TIMEOUT_SECONDS: "0.08" - WA_MAX_CANDIDATE_WAREHOUSES: "33" - WA_INVENTORY_ADMIN_TOKEN: ${WA_INVENTORY_ADMIN_TOKEN:?inventory admin token is required} + api-blue: + <<: *api-common + image: ${BLUE_IMAGE:?blue image is required} + profiles: [blue] ports: - "127.0.0.1:18081:8080" - depends_on: - redis: - condition: service_healthy - restart: unless-stopped - read_only: true - tmpfs: - - /tmp:size=32m,mode=1777 - security_opt: - - no-new-privileges:true - mem_limit: 512m - healthcheck: - test: - - CMD - - python - - -c - - "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=1)" - interval: 10s - timeout: 2s - retries: 5 - start_period: 10s - logging: - driver: json-file - options: - max-size: 10m - max-file: "3" + + api-green: + <<: *api-common + image: ${GREEN_IMAGE:?green image is required} + profiles: [green] + ports: + - "127.0.0.1:18082:8080" redis: image: redis:7.4-alpine diff --git a/deploy/nginx/warehouse-allocation-upstream.conf b/deploy/nginx/warehouse-allocation-upstream.conf new file mode 100644 index 0000000..835b25c --- /dev/null +++ b/deploy/nginx/warehouse-allocation-upstream.conf @@ -0,0 +1,4 @@ +upstream warehouse_allocation_backend { + server 127.0.0.1:18081 max_fails=3 fail_timeout=5s; + keepalive 32; +} diff --git a/deploy/nginx/warehouse-allocation.mvphub.ir.conf b/deploy/nginx/warehouse-allocation.mvphub.ir.conf index 8f050fa..7d58d51 100644 --- a/deploy/nginx/warehouse-allocation.mvphub.ir.conf +++ b/deploy/nginx/warehouse-allocation.mvphub.ir.conf @@ -38,7 +38,6 @@ server { location / { include snippets/proxy-application.conf; proxy_connect_timeout 2s; - proxy_pass http://127.0.0.1:18081; + proxy_pass http://warehouse_allocation_backend; } } - diff --git a/deploy/scripts/warehouse-allocation-deploy b/deploy/scripts/warehouse-allocation-deploy new file mode 100755 index 0000000..9280d95 --- /dev/null +++ b/deploy/scripts/warehouse-allocation-deploy @@ -0,0 +1,325 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +readonly PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +readonly APP_ROOT="/srv/apps/warehouse-allocation" +readonly RELEASES_DIR="${APP_ROOT}/releases" +readonly SHARED_ENV="${APP_ROOT}/shared/.env" +readonly INCOMING_DIR="/home/warehouse-deploy/incoming" +readonly IMAGE_REPOSITORY="local/warehouse-allocation" +readonly NGINX_UPSTREAM="/etc/nginx/conf.d/10-warehouse-allocation-upstream.conf" +readonly PUBLIC_URL="https://warehouse-allocation.mvphub.ir" +readonly LOCK_FILE="/run/lock/warehouse-allocation-deploy.lock" + +release_id="${1:-}" +expected_checksum="${2:-}" + +if [[ ! "$release_id" =~ ^[0-9a-f]{40}$ ]]; then + echo "release id must be a full 40-character lowercase commit SHA" >&2 + exit 64 +fi +if [[ ! "$expected_checksum" =~ ^[0-9a-f]{64}$ ]]; then + echo "checksum must be a lowercase SHA-256 digest" >&2 + exit 64 +fi + +readonly release_id expected_checksum +readonly archive="${INCOMING_DIR}/release-${release_id}.tar.gz" +readonly release_dir="${RELEASES_DIR}/${release_id}" +readonly candidate_image="${IMAGE_REPOSITORY}:${release_id}" + +exec 9>"$LOCK_FILE" +if ! flock -n 9; then + echo "another warehouse-allocation deployment is running" >&2 + exit 75 +fi + +umask 077 +work_dir="$(mktemp -d "${APP_ROOT}/shared/.deploy.XXXXXX")" +archive_listing="${work_dir}/archive.list" +upstream_backup="${work_dir}/upstream.conf" +openapi_file="${work_dir}/openapi.json" +example_file="${work_dir}/example.json" +response_file="${work_dir}/response.json" + +candidate_started=0 +upstream_changed=0 +deployment_complete=0 +current_changed=0 +previous_release="" +active_container="" +candidate="" +candidate_port="" +active="" +blue_image="" +green_image="" +staging_dir="" + +compose() { + env \ + BLUE_IMAGE="$blue_image" \ + GREEN_IMAGE="$green_image" \ + docker compose \ + --env-file "$SHARED_ENV" \ + -f "${release_dir}/deploy/compose.server.yaml" \ + "$@" +} + +env_value() { + local key="$1" + awk -F= -v key="$key" '$1 == key {sub(/^[^=]*=/, ""); print; exit}' "$SHARED_ENV" +} + +upsert_env() { + local key="$1" + local value="$2" + local temporary + temporary="$(mktemp "${APP_ROOT}/shared/.env.XXXXXX")" + awk -v key="$key" -v value="$value" ' + BEGIN { found = 0 } + index($0, key "=") == 1 { + print key "=" value + found = 1 + next + } + { print } + END { + if (!found) { + print key "=" value + } + } + ' "$SHARED_ENV" >"$temporary" + chmod 0600 "$temporary" + chown root:root "$temporary" + mv -f "$temporary" "$SHARED_ENV" +} + +write_upstream() { + local port="$1" + local temporary + temporary="$(mktemp "/etc/nginx/conf.d/.warehouse-allocation-upstream.XXXXXX")" + cat >"$temporary" <&2 + + if ((upstream_changed == 1)) && [[ -s "$upstream_backup" ]]; then + cp -f "$upstream_backup" "$NGINX_UPSTREAM" + if nginx -t; then + systemctl reload nginx || true + fi + fi + + if ((current_changed == 1)) && [[ -n "$previous_release" ]]; then + ln -sfn "$previous_release" "${APP_ROOT}/current" + fi + + if ((candidate_started == 1)) && [[ -n "$candidate" ]]; then + compose --profile "$candidate" stop "api-${candidate}" || true + compose --profile "$candidate" rm -f "api-${candidate}" || true + fi + + if [[ -n "$staging_dir" && -d "$staging_dir" ]]; then + rm -rf "$staging_dir" + fi + fi + + rm -rf "$work_dir" + exit "$exit_code" +} +trap rollback EXIT + +if [[ ! -f "$archive" ]]; then + echo "release archive is missing: $archive" >&2 + exit 66 +fi +if [[ ! -f "$SHARED_ENV" ]]; then + echo "shared production environment is missing: $SHARED_ENV" >&2 + exit 66 +fi + +actual_checksum="$(sha256sum "$archive" | awk '{print $1}')" +if [[ "$actual_checksum" != "$expected_checksum" ]]; then + echo "release archive checksum mismatch" >&2 + exit 65 +fi + +tar -tzf "$archive" >"$archive_listing" +if grep -Eq '(^/|(^|/)\.\.(/|$))' "$archive_listing"; then + echo "release archive contains an unsafe path" >&2 + exit 65 +fi + +if [[ -d "$release_dir" ]]; then + if [[ ! -f "${release_dir}/.release-checksum" ]] || + [[ "$(<"${release_dir}/.release-checksum")" != "$expected_checksum" ]]; then + echo "existing release directory does not match the artifact checksum" >&2 + exit 65 + fi +else + staging_dir="${RELEASES_DIR}/.${release_id}.staging" + if [[ -e "$staging_dir" ]]; then + echo "staging directory already exists: $staging_dir" >&2 + exit 73 + fi + install -d -m 0755 "$staging_dir" + tar -xzf "$archive" -C "$staging_dir" + printf '%s\n' "$expected_checksum" >"${staging_dir}/.release-checksum" + chmod 0444 "${staging_dir}/.release-checksum" + mv "$staging_dir" "$release_dir" + staging_dir="" +fi + +active="$(env_value ACTIVE_SLOT)" +if [[ -z "$active" ]]; then + active="blue" +fi +if [[ "$active" != "blue" && "$active" != "green" ]]; then + echo "ACTIVE_SLOT must be blue or green" >&2 + exit 78 +fi + +if [[ "$active" == "blue" ]]; then + candidate="green" + candidate_port="18082" +else + candidate="blue" + candidate_port="18081" +fi + +active_container="warehouse-allocation-api-${active}-1" +if ! docker inspect "$active_container" >/dev/null 2>&1; then + active_container="warehouse-allocation-api-1" +fi +if ! docker inspect "$active_container" >/dev/null 2>&1; then + echo "active API container could not be identified" >&2 + exit 69 +fi + +active_image="$(docker inspect --format '{{.Config.Image}}' "$active_container")" +if [[ "$active" == "blue" ]]; then + blue_image="$active_image" + green_image="$candidate_image" +else + blue_image="$candidate_image" + green_image="$active_image" +fi + +compose config --quiet +docker build \ + --label "ir.mvphub.service=warehouse-allocation" \ + --label "org.opencontainers.image.revision=${release_id}" \ + --tag "$candidate_image" \ + "$release_dir" + +compose --profile "$candidate" up -d --no-deps "api-${candidate}" +candidate_started=1 + +for _attempt in $(seq 1 24); do + if curl -fsS --max-time 2 "http://127.0.0.1:${candidate_port}/health/ready" \ + >/dev/null; then + break + fi + sleep 2 +done +curl -fsS --max-time 5 "http://127.0.0.1:${candidate_port}/health/ready" >/dev/null + +docker exec warehouse-allocation-redis-1 \ + redis-cli HSETNX inventory:demo-tehran DEMO-SKU-001 10000 >/dev/null +docker exec warehouse-allocation-redis-1 \ + redis-cli HSETNX inventory:demo-karaj DEMO-SKU-001 10000 >/dev/null + +cp -f "$NGINX_UPSTREAM" "$upstream_backup" +write_upstream "$candidate_port" +upstream_changed=1 +nginx -t +systemctl reload nginx + +curl -fsS --max-time 10 "${PUBLIC_URL}/health/ready" >/dev/null +curl -fsS --max-time 10 "${PUBLIC_URL}/openapi.json" >"$openapi_file" +python3 - "$openapi_file" "$example_file" <<'PY' +import json +import sys + +source, destination = sys.argv[1:] +with open(source, encoding="utf-8") as stream: + document = json.load(stream) +example = document["paths"]["/v1/allocations"]["post"]["requestBody"]["content"][ + "application/json" +]["examples"]["demoQuote"]["value"] +with open(destination, "w", encoding="utf-8") as stream: + json.dump(example, stream) +PY + +for _attempt in 1 2; do + curl -fsS --max-time 10 \ + -H "Content-Type: application/json" \ + --data-binary "@${example_file}" \ + "${PUBLIC_URL}/v1/allocations" >"$response_file" + python3 - "$response_file" <<'PY' +import json +import sys + +with open(sys.argv[1], encoding="utf-8") as stream: + response = json.load(stream) +assert response["warehouseId"] in {"demo-tehran", "demo-karaj"} +assert response["inventoryReserved"] is False +assert 0 <= response["routeOptimizationScore"] <= 100 +PY +done + +previous_release="$(readlink -f "${APP_ROOT}/current" || true)" +upsert_env BLUE_IMAGE "$blue_image" +upsert_env GREEN_IMAGE "$green_image" + +new_current="${APP_ROOT}/.current-${release_id}" +ln -s "$release_dir" "$new_current" +mv -Tf "$new_current" "${APP_ROOT}/current" +current_changed=1 +upsert_env ACTIVE_SLOT "$candidate" + +deployment_complete=1 +candidate_started=0 +upstream_changed=0 + +docker rm -f "$active_container" >/dev/null 2>&1 || true +rm -f "$archive" + +current_release="$(readlink -f "${APP_ROOT}/current")" +mapfile -t old_releases < <( + find "$RELEASES_DIR" -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\n' | + sort -nr | + tail -n +6 | + cut -d ' ' -f 2- +) +for old_release in "${old_releases[@]}"; do + if [[ "$old_release" != "$current_release" ]]; then + rm -rf "$old_release" + fi +done + +mapfile -t old_images < <( + docker image ls "$IMAGE_REPOSITORY" --format '{{.Repository}}:{{.Tag}}' | + tail -n +6 +) +for old_image in "${old_images[@]}"; do + docker image rm "$old_image" >/dev/null 2>&1 || true +done + +rm -rf "$work_dir" +trap - EXIT + +echo "warehouse-allocation ${release_id} is active in the ${candidate} slot" diff --git a/docs/TECHNICAL_DECISIONS.md b/docs/TECHNICAL_DECISIONS.md index c7a6b81..9f67430 100644 --- a/docs/TECHNICAL_DECISIONS.md +++ b/docs/TECHNICAL_DECISIONS.md @@ -623,27 +623,32 @@ Coverage is a guardrail, not proof of correctness. Important business scenarios ## 19. CI/CD decisions -GitHub Actions performs: +The canonical repository is hosted on the self-managed GitLab instance, so +GitLab CI is the authoritative pipeline. Merge requests and the protected default +branch run: -1. dependency installation; -2. Ruff lint and formatting verification; -3. strict mypy type checking; -4. unit and integration tests; -5. coverage artifact generation; -6. Docker image build; -7. optional SonarQube scan with quality-gate waiting. +1. Ruff lint and formatting verification; +2. strict mypy type checking; +3. unit, API, adapter, and real-Redis tests; +4. the 85% coverage gate and report generation; +5. optional SonarQube analysis with a blocking quality gate when configured; +6. an unprivileged container build; +7. immutable release packaging and SHA-256 generation. -The image is built but not automatically pushed or deployed because no registry, environment, release policy, or deployment authorization was supplied. +Every successful protected `main` pipeline deploys automatically. CI uploads the +verified source artifact over pinned-host-key SSH to a restricted deployment +account. A root-owned wrapper validates the artifact and performs the only +privileged operations. -Production delivery should add: +Production uses two fixed loopback slots. The candidate is built and started in +the inactive slot; Nginx switches its dedicated upstream only after readiness +succeeds. The former slot remains available until public HTTPS health, OpenAPI, +and repeatable demo-allocation smoke tests pass. Any failure restores the old +upstream and removes the candidate. -- a locked dependency process; -- software-bill-of-materials generation; -- dependency and container vulnerability scanning; -- signed images; -- registry push for protected branches/tags; -- staged deployment; -- smoke tests and automated rollback. +The project registry is not currently configured, so production builds the +verified source artifact while the old slot continues serving. A future registry +can replace this with build-once image promotion and signed images. ## 20. Security decisions @@ -692,4 +697,3 @@ Before production rollout, the following decisions remain: 10. Define authentication and authorization for every endpoint. These are intentionally documented rather than hidden behind placeholder code. Each one can materially change correctness, operations, or business behavior. - diff --git a/pyproject.toml b/pyproject.toml index b302b3a..2f207bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,6 +33,9 @@ packages = ["src/warehouse_allocation"] addopts = "-q --strict-markers --cov=warehouse_allocation --cov-report=term-missing --cov-fail-under=85" asyncio_mode = "auto" testpaths = ["tests"] +markers = [ + "redis: tests that require the WA_TEST_REDIS_URL integration service", +] [tool.coverage.run] branch = true @@ -49,4 +52,3 @@ select = ["E", "F", "I", "UP", "B", "SIM", "RUF"] python_version = "3.11" strict = true plugins = ["pydantic.mypy"] - diff --git a/tests/integration/test_redis_live.py b/tests/integration/test_redis_live.py new file mode 100644 index 0000000..555a04d --- /dev/null +++ b/tests/integration/test_redis_live.py @@ -0,0 +1,46 @@ +import asyncio +import os +from contextlib import suppress +from uuid import uuid4 + +import pytest +from redis.asyncio import Redis +from redis.exceptions import RedisError + +from warehouse_allocation.infrastructure.inventory import RedisInventoryRepository + + +@pytest.mark.redis +async def test_real_redis_reservation_is_atomic() -> None: + redis_url = os.getenv("WA_TEST_REDIS_URL") + if not redis_url: + pytest.skip("WA_TEST_REDIS_URL is not configured") + + client = Redis.from_url(redis_url, decode_responses=True) + repository = RedisInventoryRepository(client) + warehouse_id = f"ci-{uuid4().hex}" + key = f"inventory:{warehouse_id}" + + try: + for _attempt in range(20): + try: + if await client.ping(): + break + except RedisError: + await asyncio.sleep(0.25) + else: + pytest.fail("Redis integration service did not become ready") + + await repository.set_levels(warehouse_id, {"ATOMIC-SKU": 5}) + + results = await asyncio.gather( + repository.reserve(warehouse_id, {"ATOMIC-SKU": 4}), + repository.reserve(warehouse_id, {"ATOMIC-SKU": 4}), + ) + + assert sorted(results) == [False, True] + assert await client.hget(key, "ATOMIC-SKU") == "1" + finally: + with suppress(RedisError): + await client.delete(key) + await repository.close()