c_agri_trade_code/docs/runbooks/DEPLOYMENT_RUNBOOK.md

177 lines
6.7 KiB
Markdown

# Agriculture Trading Backoffice (ATB) — Deployment Runbook
| Field | Value |
|---|---|
| **Product** | Agriculture Trading Backoffice (ATB) |
| **Release Version** | `v1.0.0` (Production / UAT Release) |
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.5 Standard Enterprise Tier) |
| **Document Path** | `04_generated_documentation/08_review_ready_baselines/02_handover_package/DEPLOYMENT_RUNBOOK.md` |
| **Audience** | DevOps Engineers, System Administrators, Infrastructure Architects |
---
## 1. System Requirements & Prerequisites
### 1.1 Hardware Specifications
- **Minimum (UAT / Staging):** 4 vCPU, 8 GB RAM, 50 GB SSD storage.
- **Recommended (Production):** 8 vCPU, 16 GB RAM, 200 GB high-IOPS NVMe SSD storage.
- **Network:** Static public IP / Domain with reverse-proxy TLS termination (443/80).
### 1.2 Operating System & Core Software
- **Operating System:** Linux (Ubuntu 22.04 LTS, Ubuntu 24.04 LTS, Debian 12, or RHEL 9).
- **Container Runtime:** Docker Engine `v24.0.0+` with containerd.
- **Compose Tool:** Docker Compose plugin `v2.20.0+`.
- **System Utilities:** `curl`, `jq`, `openssl`, `git`, `postgresql-client` (optional for external checks).
---
## 2. Release Artifacts & Directory Structure
Ensure the release package is extracted into `/opt/atb` or your designated deployment directory:
```text
/opt/atb/
├── docker-compose.prod.yaml # Master production orchestration
├── .env.prod # Environment secret configuration (from .env.prod.example)
├── docker/
│ ├── Dockerfile.backend # Multi-stage Python 3.12 FastAPI image
│ ├── Dockerfile.frontend # Multi-stage Node 20 / Nginx 1.27 image
│ ├── nginx.conf # Hardened reverse-proxy & security headers
│ └── postgres/
│ └── init/
│ └── 01-create-keycloak-db.sh # Database init script for Keycloak
├── backend/ # Application source & Alembic migrations
├── frontend/ # React 18 / TypeScript SPA source
└── sandbox/ # Mock adapters (disabled in live production)
```
---
## 3. Step-by-Step Deployment Procedure
### Step 1: Environment Secret Configuration
1. Copy the production template:
```bash
cp project_code/.env.prod.example /opt/atb/.env.prod
```
2. Generate cryptographically strong secrets:
```bash
POSTGRES_PWD=$(openssl rand -base64 24)
KC_DB_PWD=$(openssl rand -base64 24)
KC_ADMIN_PWD=$(openssl rand -base64 24)
VALKEY_AUTH=$(openssl rand -base64 24)
```
3. Update `/opt/atb/.env.prod` with your domain names, generated passwords, and Keycloak client secrets. Ensure `USE_IDENTITY_MOCK=False` and `ENVIRONMENT=production`.
### Step 2: Initialize Volumes & Launch Data Tier
Start the PostgreSQL 17 database and Valkey cache service:
```bash
docker compose -f docker-compose.prod.yaml --env-file .env.prod up -d postgres valkey
```
Verify that both containers reach healthy status:
```bash
docker compose -f docker-compose.prod.yaml ps
```
*Expected: `atb-prod-postgres` and `atb-prod-valkey` display `(healthy)`.*
### Step 3: Launch Keycloak Identity Provider
Start the Keycloak IAM container:
```bash
docker compose -f docker-compose.prod.yaml --env-file .env.prod up -d keycloak
```
Monitor container logs until readiness probe succeeds:
```bash
docker logs -f atb-prod-keycloak
```
*Wait until log output reports `Keycloak 26.8.0 on JVM (powered by Quarkus) started in ...`.*
### Step 4: Execute Database Migrations (Alembic)
Apply all 14 database migration revisions to create the 39 production tables and enforce Row-Level Security:
```bash
docker compose -f docker-compose.prod.yaml --env-file .env.prod run --rm backend \
sh -c "cd /app/backend && alembic upgrade head"
```
Verify migration status and RLS enablement:
```bash
docker exec -it atb-prod-postgres psql -U atb -d atb -c "
SELECT schemaname, tablename, rowsecurity
FROM pg_tables
WHERE schemaname = 'public' AND tablename IN ('procurement_contracts', 'stock_ledger', 'sales_contracts');
"
```
*Expected: `rowsecurity` must be `t` (true) for all tenant-scoped tables.*
### Step 5: Launch Backend Application Services
Start the core FastAPI backend service:
```bash
docker compose -f docker-compose.prod.yaml --env-file .env.prod up -d backend
```
Validate application health:
```bash
curl -f http://127.0.0.1:8000/health
```
*Expected response: `{"status":"healthy","database":"connected","tenancy":"rls_enforced"}`.*
### Step 6: Launch Web Portal Frontend (Nginx SPA)
Start the hardened Nginx frontend container:
```bash
docker compose -f docker-compose.prod.yaml --env-file .env.prod up -d frontend
```
Verify portal accessibility:
```bash
curl -f http://127.0.0.1/healthz
```
*Expected response: `healthy`.*
---
## 4. Post-Deployment Smoke Verification
Execute the automated smoke verification script against the deployed stack:
```bash
#!/bin/bash
set -e
echo "1. Checking Frontend Liveness..."
curl -s -f http://127.0.0.1/healthz > /dev/null && echo " -> Frontend OK"
echo "2. Checking Backend API Liveness..."
curl -s -f http://127.0.0.1/api/health > /dev/null && echo " -> Backend API OK"
echo "3. Checking Keycloak OpenID Configuration..."
curl -s -f http://127.0.0.1:8080/auth/realms/atb/.well-known/openid-configuration > /dev/null && echo " -> Keycloak OIDC OK"
echo "4. Checking Database Row-Level Security Count..."
RLS_COUNT=$(docker exec atb-prod-postgres psql -U atb -d atb -t -c "SELECT count(*) FROM pg_tables WHERE schemaname = 'public' AND rowsecurity = true;")
echo " -> Tables with Row-Level Security: $RLS_COUNT"
echo "== All Post-Deployment Smoke Checks Passed =="
```
---
## 5. Troubleshooting & FAQ
| Symptom | Probable Cause | Corrective Action |
|---|---|---|
| `backend` exits with `connection refused` on port 5432 | Database starting slower than backend container | Inspect `postgres` healthcheck via `docker inspect atb-prod-postgres`. Backend automatically restarts per `restart: unless-stopped`. |
| Keycloak logs report `FATAL: database "keycloak" does not exist` | Init script did not execute on first volume init | Verify `01-create-keycloak-db.sh` is mounted into `/docker-entrypoint-initdb.d/`. If volume was initialized earlier, manually create database: `psql -U atb -c "CREATE DATABASE keycloak;"`. |
| `400 TENANT_CONTEXT_REQUIRED` on API requests | Request lacks `X-Tenant-ID` header or OIDC session context | Ensure client applications pass the `X-Tenant-ID: <UUID>` header or authenticate with a valid JWT token. |
| Inward weighbridge rejects tare weight | Tare weight entered exceeds gross weighbridge recording | Physical invariant violated: verify weighbridge calibration and gross scale reading. |