#!/usr/bin/env bash # # scripts/deploy_compose.sh # 用途:按环境增量构建/拉起 hxops 前后端容器,并为镜像打版本 tag 供回滚使用。 # 依赖:docker compose、docker-compose.yml、.env.、healthcheck.sh。 # 逻辑:Jenkins Deploy 阶段 SSH 调用;回滚时以预构建镜像模式传入 FRONTEND_IMAGE/BACKEND_IMAGE。 set -euo pipefail # Git 默认短 hash 长度(与 Sourcetree/GitHub 展示一致) SHORT_SHA_LEN=7 # 参数说明: # 1: 环境名(dev/test/prod) # 2: 前端镜像名(可空;非空表示使用预构建镜像) # 3: 后端镜像名(可空;非空表示使用预构建镜像) # 4: 前端是否有变更(true/false) # 5: 后端是否有变更(true/false) # 6: 部署配置是否有变更(true/false) # 7: 是否跳过 flask db upgrade(true/false;镜像回滚时应为 true) ENV_NAME="${1:-default}" FRONTEND_IMAGE="${2:-}" BACKEND_IMAGE="${3:-}" FRONTEND_CHANGED="${4:-false}" BACKEND_CHANGED="${5:-false}" DEPLOY_CONFIG_CHANGED="${6:-false}" SKIP_DB_MIGRATE="${7:-false}" # 统一使用仓库根目录下的 compose 和环境文件 ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" COMPOSE_FILE="${ROOT_DIR}/docker-compose.yml" ENV_FILE="${ROOT_DIR}/.env.${ENV_NAME}" SHARED_ENV_FILE="${ROOT_DIR}/.env.shared" ORACLE_CLIENT_DIR="${ROOT_DIR}/oracle_client" BACKEND_DOCKERFILE="${ROOT_DIR}/backend/Dockerfile" SCHEMA_DOC_PATH="${ROOT_DIR}/docs/integrations/erp/text2sql_schema.md" ROOT_DOCKERIGNORE="${ROOT_DIR}/.dockerignore" check_oracle_client() { if [[ ! -d "${ORACLE_CLIENT_DIR}" ]]; then echo "Missing Oracle Instant Client directory: ${ORACLE_CLIENT_DIR}" echo "Please prepare oracle_client under the project root so docker-compose can mount it to /app/oracle_client." exit 1 fi if ! find "${ORACLE_CLIENT_DIR}" \( -iname "oci.dll" -o -iname "libclntsh.so" -o -iname "libclntsh.dylib" -o -type d -name "instantclient_*" \) | grep -q .; then echo "Oracle Instant Client directory exists but no client library was found: ${ORACLE_CLIENT_DIR}" echo "Expected extracted Instant Client files such as instantclient_* / oci.dll / libclntsh.so." exit 1 fi } check_backend_build_inputs() { echo "Validating backend Docker build inputs..." echo "- compose file: ${COMPOSE_FILE}" echo "- backend Dockerfile: ${BACKEND_DOCKERFILE}" echo "- schema doc: ${SCHEMA_DOC_PATH}" echo "- dockerignore: ${ROOT_DOCKERIGNORE}" if [[ ! -f "${BACKEND_DOCKERFILE}" ]]; then echo "Missing backend Dockerfile: ${BACKEND_DOCKERFILE}" exit 1 fi if [[ ! -f "${SCHEMA_DOC_PATH}" ]]; then echo "Missing Text2SQL schema doc: ${SCHEMA_DOC_PATH}" echo "Please ensure docs/integrations/erp/text2sql_schema.md exists before building hxops-backend." exit 1 fi if ! grep -Fq 'context: .' "${COMPOSE_FILE}" || ! grep -Fq 'dockerfile: backend/Dockerfile' "${COMPOSE_FILE}"; then echo "Invalid backend build settings in ${COMPOSE_FILE}" echo "hxops-backend must be built from repository root with:" echo " context: ." echo " dockerfile: backend/Dockerfile" exit 1 fi if ! grep -Fq 'COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md' "${BACKEND_DOCKERFILE}"; then echo "Invalid backend Dockerfile: schema doc is not copied into the image." echo "Expected line:" echo " COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md" exit 1 fi if [[ -f "${ROOT_DOCKERIGNORE}" ]] && grep -Eq '^(docs|docs/\*)$' "${ROOT_DOCKERIGNORE}"; then if ! grep -Fxq '!docs/integrations/erp/text2sql_schema.md' "${ROOT_DOCKERIGNORE}"; then echo "Invalid .dockerignore: docs is excluded but the Text2SQL schema is not re-included." echo "Please add the following line to ${ROOT_DOCKERIGNORE}:" echo " !docs/integrations/" echo " !docs/integrations/erp/" echo " !docs/integrations/erp/text2sql_schema.md" exit 1 fi fi } # 校验预构建镜像是否存在(精确匹配 tag,找不到则失败)。 verify_prebuilt_image() { local image="$1" if [[ -z "${image}" ]]; then echo "Prebuilt mode requires an image reference for the service being deployed." exit 1 fi if ! docker image inspect "${image}" >/dev/null 2>&1; then echo "Prebuilt image not found: ${image}" echo "List available tags on this host: docker images 'hxops-*' --format '{{.Repository}}:{{.Tag}}'" exit 1 fi } # 为本次构建的 :local 镜像打版本 tag,供 Jenkins 回滚时按 Git 短 hash 选用。 tag_built_images() { local commit_sha="${GIT_COMMIT:-}" if [[ -z "${commit_sha}" ]]; then echo "GIT_COMMIT is empty, skipping version image tags." return 0 fi local short_sha="${commit_sha:0:${SHORT_SHA_LEN}}" local version_tag="${ENV_NAME}-${short_sha}" # 对当前 :local 镜像打版本 tag(含增量部署),便于回滚时前后端 tag 成对存在 if docker image inspect hxops-frontend:local >/dev/null 2>&1; then docker tag hxops-frontend:local "hxops-frontend:${version_tag}" echo "Tagged hxops-frontend:${version_tag}" fi if docker image inspect hxops-backend:local >/dev/null 2>&1; then docker tag hxops-backend:local "hxops-backend:${version_tag}" echo "Tagged hxops-backend:${version_tag}" fi } # 保留最近 N 个 ${ENV_NAME}- 版本 tag,删除更旧的 tag 并清理悬空镜像层。 # 数量由 IMAGE_TAG_RETAIN_COUNT 控制(默认 10);设为 0 可关闭自动清理。 prune_old_version_tags() { local keep_count="${IMAGE_TAG_RETAIN_COUNT:-10}" if [[ "${keep_count}" -le 0 ]]; then echo "IMAGE_TAG_RETAIN_COUNT=${keep_count}, skipping version tag prune." return 0 fi local version_prefix="${ENV_NAME}-" declare -A tag_created=() local repo tag created for repo in hxops-frontend hxops-backend; do while IFS= read -r tag; do [[ -z "${tag}" ]] && continue [[ "${tag}" == "local" ]] && continue [[ "${tag}" == "${version_prefix}"* ]] || continue created="$(docker image inspect --format '{{.Created}}' "${repo}:${tag}" 2>/dev/null || true)" [[ -z "${created}" ]] && continue if [[ -z "${tag_created[$tag]+x}" ]] || [[ "${created}" > "${tag_created[$tag]}" ]]; then tag_created["${tag}"]="${created}" fi done < <(docker images "${repo}" --format '{{.Tag}}' 2>/dev/null || true) done local tag_count="${#tag_created[@]}" if [[ "${tag_count}" -le "${keep_count}" ]]; then echo "Version tags for '${version_prefix}*': ${tag_count} (retain ${keep_count}), no prune needed." return 0 fi mapfile -t sorted_tags < <( for tag in "${!tag_created[@]}"; do printf '%s\t%s\n' "${tag_created[$tag]}" "${tag}" done | sort -t $'\t' -k1,1r | cut -f2 ) local idx removed=0 for (( idx=keep_count; idx<${#sorted_tags[@]}; idx++ )); do local old_tag="${sorted_tags[$idx]}" for repo in hxops-frontend hxops-backend; do if docker image inspect "${repo}:${old_tag}" >/dev/null 2>&1; then echo "Removing old version tag: ${repo}:${old_tag}" if docker rmi "${repo}:${old_tag}" >/dev/null 2>&1; then removed=$((removed + 1)) else echo " (kept ${repo}:${old_tag}: still referenced by a container or other tag)" fi fi done done if [[ "${removed}" -gt 0 ]]; then docker image prune -f >/dev/null 2>&1 || true fi echo "Version tag prune done: kept latest ${keep_count} '${version_prefix}*' tag(s), removed ${removed} tag reference(s)." } # 基础文件检查:compose 文件必须存在 if [[ ! -f "${COMPOSE_FILE}" ]]; then echo "Missing compose file: ${COMPOSE_FILE}" exit 1 fi # 环境配置检查:不同环境对应不同 .env 文件 if [[ ! -f "${ENV_FILE}" ]]; then echo "Missing env file for environment '${ENV_NAME}': ${ENV_FILE}" exit 1 fi if [[ ! -f "${SHARED_ENV_FILE}" ]]; then echo "Missing shared env file: ${SHARED_ENV_FILE}" exit 1 fi # 兼容 docker compose(v2) 与 docker-compose(v1) if docker compose version >/dev/null 2>&1; then DC_CMD=(docker compose) elif command -v docker-compose >/dev/null 2>&1; then DC_CMD=(docker-compose) else echo "Missing docker compose command. Install docker compose plugin or docker-compose." exit 1 fi echo "Using compose command: ${DC_CMD[*]}" echo "Using env file: ${ENV_FILE}" declare -a compose_args=(-f "${COMPOSE_FILE}" --env-file "${ENV_FILE}") # 当传入镜像名时,认为是“预构建镜像模式” # 该模式下只拉起容器,不在目标机重新构建 PREBUILT_MODE="false" if [[ -n "${FRONTEND_IMAGE}" || -n "${BACKEND_IMAGE}" ]]; then PREBUILT_MODE="true" fi # 将镜像标签导出给 docker-compose.yml 使用(image: ${FRONTEND_IMAGE} / ${BACKEND_IMAGE}) if [[ -n "${FRONTEND_IMAGE}" ]]; then export FRONTEND_IMAGE fi if [[ -n "${BACKEND_IMAGE}" ]]; then export BACKEND_IMAGE fi cd "${ROOT_DIR}" # docker-compose.yml 中 hxops-backend.env_file 使用此文件名(相对 ROOT_DIR) export COMPOSE_ENV_BASENAME=".env.${ENV_NAME}" export COMPOSE_SHARED_ENV_BASENAME=".env.shared" # 根据变更范围决定要更新的服务,实现前后端增量部署 services=() if [[ "${FRONTEND_CHANGED}" == "true" ]]; then services+=("hxops-frontend") fi if [[ "${BACKEND_CHANGED}" == "true" ]]; then # 后台 worker 与 backend 共用镜像;仅重建 backend 时 worker 会继续跑旧容器/旧代码 services+=("hxops-backend" "hxops-kb-worker" "hxops-schedule-worker" "hxops-shipping-worker") fi # 如果只是部署配置变更(如 compose/env/脚本),但前后端代码未改,则两边都更新 if [[ ${#services[@]} -eq 0 && "${DEPLOY_CONFIG_CHANGED}" == "true" ]]; then services=("hxops-frontend" "hxops-backend" "hxops-kb-worker" "hxops-schedule-worker" "hxops-shipping-worker") fi # 无变更则直接跳过,避免无意义重启 if [[ ${#services[@]} -eq 0 ]]; then echo "No service changes detected, skipping deployment." exit 0 fi echo "Deploying environment: ${ENV_NAME}" echo "Services: ${services[*]}" echo "Prebuilt image mode: ${PREBUILT_MODE}" echo "Skip DB migrate: ${SKIP_DB_MIGRATE}" if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then echo "Checking Oracle Instant Client directory..." check_oracle_client if [[ "${PREBUILT_MODE}" != "true" ]]; then check_backend_build_inputs else echo "Skipping backend Docker input validation because prebuilt image mode is enabled." fi fi # 预构建镜像模式:只启动,不构建 # 非预构建镜像模式:在目标机本地构建并启动 if [[ "${PREBUILT_MODE}" == "true" ]]; then if printf '%s\n' "${services[@]}" | grep -qx "hxops-frontend"; then verify_prebuilt_image "${FRONTEND_IMAGE}" fi if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then verify_prebuilt_image "${BACKEND_IMAGE}" fi "${DC_CMD[@]}" "${compose_args[@]}" up -d --no-build "${services[@]}" else # Dockerfile 使用 apt/pip cache mount,需启用 BuildKit export DOCKER_BUILDKIT=1 export COMPOSE_DOCKER_CLI_BUILD=1 "${DC_CMD[@]}" "${compose_args[@]}" up -d --build "${services[@]}" tag_built_images prune_old_version_tags fi # Keep DB schema aligned with backend code after deployment. if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then if [[ "${SKIP_DB_MIGRATE}" == "true" ]]; then echo "SKIP_DB_MIGRATE=true, skipping flask db upgrade." else echo "Running database migrations (flask db upgrade)..." "${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend flask --app manage.py db upgrade fi fi "${ROOT_DIR}/scripts/healthcheck.sh" "${ENV_NAME}" "${COMPOSE_FILE}" "${ENV_FILE}"