From e3415a87788e14339c1d78db29400110086c6d6b Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Sun, 20 Sep 2026 21:16:15 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baiyue/audit/BaiyueAuditApplication.java | 2 - .../AuditOutboxRocketMqAutoConfiguration.java | 2 - .../BaiyueSchedulingAutoConfiguration.java | 13 ++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + ...BaiyueSchedulingAutoConfigurationTest.java | 26 ++++ deploy/docker-compose.overseas.yml | 1 + deploy/docker-compose.yml | 1 + deploy/scripts/deploy-blue-green-service.sh | 114 ++++++++++---- deploy/scripts/deploy-built-service.sh | 24 ++- .../eventbridge/EventBridgeApplication.java | 2 - .../baiyue/file/FileServiceApplication.java | 2 - .../finance/BaiyueFinanceApplication.java | 2 - .../baiyue/finance/FinanceContractTest.java | 4 +- .../firstleg/BaiyueFirstlegApplication.java | 2 - .../com/baiyue/iam/BaiyueIamApplication.java | 2 - .../lastleg/BaiyueLastlegApplication.java | 2 - .../baiyue/order/BaiyueOrderApplication.java | 2 - .../blue-green-deployment-contract.test.mjs | 64 ++++++++ .../blue-green-deployment-runtime.test.mjs | 140 ++++++++++++++++++ scripts/overseas-deployment-contract.test.mjs | 2 +- ...est-environment-pipeline-contract.test.mjs | 6 +- 21 files changed, 363 insertions(+), 51 deletions(-) create mode 100644 common-web/src/main/java/com/baiyue/common/web/BaiyueSchedulingAutoConfiguration.java create mode 100644 common-web/src/test/java/com/baiyue/common/web/BaiyueSchedulingAutoConfigurationTest.java create mode 100644 scripts/blue-green-deployment-contract.test.mjs create mode 100644 scripts/blue-green-deployment-runtime.test.mjs diff --git a/audit-service/src/main/java/com/baiyue/audit/BaiyueAuditApplication.java b/audit-service/src/main/java/com/baiyue/audit/BaiyueAuditApplication.java index 8a80f655c..91c60a168 100644 --- a/audit-service/src/main/java/com/baiyue/audit/BaiyueAuditApplication.java +++ b/audit-service/src/main/java/com/baiyue/audit/BaiyueAuditApplication.java @@ -6,13 +6,11 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 审计微服务启动入口,初始化 Spring Boot 应用并扫描审计日志 Mapper。 */ @MapperScan(basePackages = "com.baiyue.audit", annotationClass = Mapper.class) -@EnableScheduling @Import(MybatisPlusConfiguration.class) @SpringBootApplication public class BaiyueAuditApplication { diff --git a/common-audit/src/main/java/com/baiyue/common/audit/AuditOutboxRocketMqAutoConfiguration.java b/common-audit/src/main/java/com/baiyue/common/audit/AuditOutboxRocketMqAutoConfiguration.java index cfe3e7e4b..5d6252d0d 100644 --- a/common-audit/src/main/java/com/baiyue/common/audit/AuditOutboxRocketMqAutoConfiguration.java +++ b/common-audit/src/main/java/com/baiyue/common/audit/AuditOutboxRocketMqAutoConfiguration.java @@ -7,14 +7,12 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 审计 Outbox 的 RocketMQ 发布配置。 * 该配置与基础审计配置隔离:未引入 RocketMQ 的服务仍可使用 HTTP 审计投递。 */ @AutoConfiguration(after = BaiyueAuditAutoConfiguration.class) -@EnableScheduling @ConditionalOnClass(name = "org.apache.rocketmq.spring.core.RocketMQTemplate") @ConditionalOnBean(type = { "com.baiyue.common.audit.AuditOutboxRepository", diff --git a/common-web/src/main/java/com/baiyue/common/web/BaiyueSchedulingAutoConfiguration.java b/common-web/src/main/java/com/baiyue/common/web/BaiyueSchedulingAutoConfiguration.java new file mode 100644 index 000000000..41613a4d3 --- /dev/null +++ b/common-web/src/main/java/com/baiyue/common/web/BaiyueSchedulingAutoConfiguration.java @@ -0,0 +1,13 @@ +package com.baiyue.common.web; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** Enables scheduled workers by default while allowing blue-green web slots to disable them. */ +@AutoConfiguration +@EnableScheduling +@ConditionalOnProperty(prefix = "baiyue.runtime", name = "scheduling-enabled", + havingValue = "true", matchIfMissing = true) +public class BaiyueSchedulingAutoConfiguration { +} diff --git a/common-web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/common-web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 2d417843c..3fb8cf813 100644 --- a/common-web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/common-web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -2,3 +2,4 @@ com.baiyue.common.web.LongIdJacksonConfiguration com.baiyue.common.web.CommonWebAutoConfiguration com.baiyue.common.web.FeignTracePropagationAutoConfiguration com.baiyue.common.web.RestClientTracePropagationAutoConfiguration +com.baiyue.common.web.BaiyueSchedulingAutoConfiguration diff --git a/common-web/src/test/java/com/baiyue/common/web/BaiyueSchedulingAutoConfigurationTest.java b/common-web/src/test/java/com/baiyue/common/web/BaiyueSchedulingAutoConfigurationTest.java new file mode 100644 index 000000000..67667f8cf --- /dev/null +++ b/common-web/src/test/java/com/baiyue/common/web/BaiyueSchedulingAutoConfigurationTest.java @@ -0,0 +1,26 @@ +package com.baiyue.common.web; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.scheduling.config.TaskManagementConfigUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +class BaiyueSchedulingAutoConfigurationTest { + private final ApplicationContextRunner runner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(BaiyueSchedulingAutoConfiguration.class)); + + @Test + void schedulingIsEnabledByDefault() { + runner.run(context -> assertThat(context) + .hasBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); + } + + @Test + void blueGreenWebSlotCanDisableScheduling() { + runner.withPropertyValues("baiyue.runtime.scheduling-enabled=false") + .run(context -> assertThat(context) + .doesNotHaveBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); + } +} diff --git a/deploy/docker-compose.overseas.yml b/deploy/docker-compose.overseas.yml index b1a167ac3..3082caf78 100644 --- a/deploy/docker-compose.overseas.yml +++ b/deploy/docker-compose.overseas.yml @@ -9,6 +9,7 @@ x-overseas-common: &overseas-common environment: &overseas-environment BAIYUE_DEPLOY_SLOT: ${DEPLOY_SLOT:-rolling} BAIYUE_RELEASE_ID: ${RELEASE_ID:-local} + BAIYUE_RUNTIME_SCHEDULING_ENABLED: ${BAIYUE_RUNTIME_SCHEDULING_ENABLED:-true} SERVER_SHUTDOWN: graceful SPRING_LIFECYCLE_TIMEOUT_PER_SHUTDOWN_PHASE: ${SHUTDOWN_PHASE_TIMEOUT:-30s} SPRING_PROFILES_ACTIVE: overseas diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index d14a9a92a..a4c7dbdac 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -11,6 +11,7 @@ x-common: &common DEPLOY_ENV: ${DEPLOY_ENV:-test} BAIYUE_DEPLOY_SLOT: ${DEPLOY_SLOT:-rolling} BAIYUE_RELEASE_ID: ${RELEASE_ID:-local} + BAIYUE_RUNTIME_SCHEDULING_ENABLED: ${BAIYUE_RUNTIME_SCHEDULING_ENABLED:-true} SERVER_SHUTDOWN: graceful SPRING_LIFECYCLE_TIMEOUT_PER_SHUTDOWN_PHASE: ${SHUTDOWN_PHASE_TIMEOUT:-30s} SPRING_PROFILES_ACTIVE: ${SPRING_PROFILES_ACTIVE:-cn} diff --git a/deploy/scripts/deploy-blue-green-service.sh b/deploy/scripts/deploy-blue-green-service.sh index 0c54d4fd4..6cf70ac73 100644 --- a/deploy/scripts/deploy-blue-green-service.sh +++ b/deploy/scripts/deploy-blue-green-service.sh @@ -33,27 +33,27 @@ env_value() { service_contract() { case "$SERVICE:$COMPOSE_FILE" in - gateway:*) echo "gateway|9000|9000|gateway" ;; - auth:*) echo "auth|9100|9100|auth-service" ;; - iam:*) echo "iam|9201|9201|iam-service" ;; - firstleg:*) echo "business|9202|9202|firstleg-service" ;; - finance:*) echo "finance|9203|9203|finance-service" ;; - order:*) echo "order|9204|9204|order-service" ;; - warehouse:*) echo "warehouse|9205|9205|warehouse-service" ;; - file:*) echo "file|9206|9206|file-service" ;; - print:*) echo "print|9207|9207|print-service" ;; - integration-service:*) echo "integration|9210|9210|integration-service" ;; - audit-service:*) echo "audit|9700|9700|audit-service" ;; - gateway-overseas:*) echo "gateway-overseas|9300|9300|gateway-overseas" ;; - lastleg-service:*) echo "lastleg|9303|9303|lastleg-service" ;; - warehouse-overseas-service:*) echo "warehouse-overseas|9305|9305|warehouse-overseas-service" ;; - event-bridge-service:*overseas*) echo "event-bridge-overseas|9312|9313|event-bridge-service" ;; - event-bridge-service:*) echo "event-bridge|9312|9312|event-bridge-service" ;; + gateway:*) echo "gateway|9000|9000|gateway|gateway" ;; + auth:*) echo "auth|9100|9100|auth-service|auth" ;; + iam:*) echo "iam|9201|9201|iam-service|iam" ;; + firstleg:*) echo "business|9202|9202|firstleg-service|firstleg" ;; + finance:*) echo "finance|9203|9203|finance-service|finance" ;; + order:*) echo "order|9204|9204|order-service|order" ;; + warehouse:*) echo "warehouse|9205|9205|warehouse-service|warehouse" ;; + file:*) echo "file|9206|9206|file-service|file" ;; + print:*) echo "print|9207|9207|print-service|print" ;; + integration-service:*) echo "integration|9210|9210|integration-service|integration-service" ;; + audit-service:*) echo "audit|9700|9700|audit-service|audit-service" ;; + gateway-overseas:*) echo "gateway-overseas|9300|9300|gateway-overseas|gateway-overseas" ;; + lastleg-service:*) echo "lastleg|9303|9303|lastleg-service|lastleg-service" ;; + warehouse-overseas-service:*) echo "warehouse-overseas|9305|9305|warehouse-overseas-service|warehouse-overseas-service" ;; + event-bridge-service:*overseas*) echo "event-bridge-overseas|9312|9313|event-bridge-service|event-bridge-overseas" ;; + event-bridge-service:*) echo "event-bridge|9312|9312|event-bridge-service|event-bridge-cn" ;; *) echo "不支持蓝绿部署的服务: $SERVICE" >&2; exit 2 ;; esac } -IFS='|' read -r CONTAINER_STEM INTERNAL_PORT BASE_PORT NACOS_SERVICE </dev/null 2>&1; then active_slot="legacy" active_container="$legacy_container" @@ -100,6 +101,7 @@ else target_port=$((BASE_PORT + 10000)) fi candidate="firstleg-${DEPLOY_ENV}-${CONTAINER_STEM}-${target_slot}" +worker_candidate="${candidate}-worker" if docker inspect "$candidate" >/dev/null 2>&1; then if [ "$candidate" = "$active_container" ]; then @@ -113,20 +115,23 @@ compose() { docker compose --project-name "$BASE_PROJECT" --env-file "$ENV_FILE" -f "$COMPOSE_FILE" "$@" } -candidate_health() { +container_health() { + container="$1" docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' \ - "$candidate" 2>/dev/null || echo missing + "$container" 2>/dev/null || echo missing } cleanup_candidate() { docker rm -f "$candidate" >/dev/null 2>&1 || true } -wait_for_candidate() { +wait_for_container() { + container="$1" + label="$2" elapsed=0 while [ "$elapsed" -lt "$HEALTH_TIMEOUT" ]; do - state="$(candidate_health)" - echo "候选槽 $target_slot 健康状态: $state(已等待 ${elapsed}s)" + state="$(container_health "$container")" + echo "$label 健康状态: $state(已等待 ${elapsed}s)" case "$state" in healthy) return 0 ;; unhealthy|exited|dead|missing) return 1 ;; @@ -137,6 +142,46 @@ wait_for_candidate() { return 1 } +needs_worker() { + case "$SERVICE" in + iam|firstleg|finance|order|event-bridge-service|lastleg-service) return 0 ;; + file) + [ "$(env_value FILE_EXPORT_CONSUMER_ENABLED)" = true ] \ + || [ "$(env_value FILE_EXPORT_PUBLISHER_ENABLED)" = true ] \ + || [ "$(env_value FILE_EXPORT_RECONCILER_ENABLED)" = true ] \ + || [ "$(env_value AUDIT_OUTBOX_PUBLISHER_ENABLED)" = true ] + ;; + audit-service) + [ "$(env_value AUDIT_MQ_CONSUMER_ENABLED)" = true ] \ + || [ "$(env_value AUDIT_DLQ_CONSUMER_ENABLED)" = true ] \ + || [ "$(env_value AUDIT_DLQ_COMPENSATION_ENABLED)" = true ] + ;; + auth|warehouse|warehouse-overseas-service) + [ "$(env_value AUDIT_OUTBOX_PUBLISHER_ENABLED)" = true ] + ;; + *) return 1 ;; + esac +} + +start_worker_candidate() { + docker rm -f "$worker_candidate" >/dev/null 2>&1 || true + echo "启动单例 Worker: $worker_candidate" + if ! compose run -d --no-deps --name "$worker_candidate" \ + -e "NACOS_REGISTER_ENABLED=false" \ + -e "BAIYUE_RUNTIME_SCHEDULING_ENABLED=true" \ + -e "BAIYUE_DEPLOY_SLOT=${target_slot}-worker" \ + -e "BAIYUE_RELEASE_ID=$IMAGE_TAG" "$SERVICE" >/dev/null; then + return 1 + fi + if ! wait_for_container "$worker_candidate" "候选 Worker"; then + docker logs --tail 200 "$worker_candidate" 2>&1 || true + docker rm -f "$worker_candidate" >/dev/null 2>&1 || true + return 1 + fi + worker_image="$(docker inspect --format '{{.Config.Image}}' "$worker_candidate")" + [ "$worker_image" = "$IMAGE" ] || return 1 +} + connect_routing_alias() { alias_name="$1" container="$2" @@ -160,14 +205,21 @@ bootstrap_legacy_routes() { connect_routing_alias "$alias_name" "$container" || true fi done + for container in firstleg-prod-admin-web firstleg-prod-client-web; do + if docker inspect "$container" >/dev/null 2>&1; then + connect_routing_alias "${container##*-}" "$container" || true + fi + done } switch_gateway_proxy() { [ "$SERVICE" = "gateway" ] || [ "$SERVICE" = "gateway-overseas" ] || return 0 if [ "$SERVICE" = "gateway" ]; then config="$(env_value GATEWAY_BLUE_GREEN_NGINX_CONFIG)" + config="${config:-/www/server/panel/vhost/nginx/api-cn.buggoglobal.com.conf}" else config="$(env_value GATEWAY_OVERSEAS_BLUE_GREEN_NGINX_CONFIG)" + config="${config:-/www/server/panel/vhost/nginx/api-global.buggoglobal.com.conf}" fi if [ -z "$config" ] || [ ! -f "$config" ]; then echo "$SERVICE 蓝绿切换要求环境文件配置有效的 Nginx 配置路径" >&2 @@ -195,12 +247,22 @@ export DEPLOY_ENV IMAGE_REPOSITORY IMAGE_TAG echo "启动候选槽: service=$SERVICE slot=$target_slot port=$target_port image=$IMAGE" if ! compose run -d --no-deps --name "$candidate" \ -e "BAIYUE_DEPLOY_SLOT=$target_slot" -e "BAIYUE_RELEASE_ID=$IMAGE_TAG" \ + -e "BAIYUE_RUNTIME_SCHEDULING_ENABLED=false" \ + -e "AUDIT_OUTBOX_PUBLISHER_ENABLED=false" \ + -e "NOTIFICATION_SCHEDULER_ENABLED=false" \ + -e "NOTIFICATION_MQ_CONSUMER_ENABLED=false" \ + -e "FILE_EXPORT_CONSUMER_ENABLED=false" \ + -e "FILE_EXPORT_PUBLISHER_ENABLED=false" \ + -e "FILE_EXPORT_RECONCILER_ENABLED=false" \ + -e "AUDIT_MQ_CONSUMER_ENABLED=false" \ + -e "AUDIT_DLQ_CONSUMER_ENABLED=false" \ + -e "AUDIT_DLQ_COMPENSATION_ENABLED=false" \ -p "${PUBLISHED_BIND_ADDRESS:-0.0.0.0}:$target_port:$INTERNAL_PORT" "$SERVICE" >/dev/null; then cleanup_candidate exit 1 fi -if ! wait_for_candidate; then +if ! wait_for_container "$candidate" "候选 Web 槽 $target_slot"; then echo "候选槽未通过健康检查,保留旧实例" >&2 docker logs --tail 200 "$candidate" 2>&1 || true cleanup_candidate @@ -214,13 +276,13 @@ if [ "$running_image" != "$IMAGE" ]; then exit 1 fi -connect_routing_alias "$SERVICE" "$candidate" +connect_routing_alias "$ROUTING_ALIAS" "$candidate" [ "$NACOS_SERVICE" = "$SERVICE" ] || connect_routing_alias "$NACOS_SERVICE" "$candidate" if [ "$STABILIZATION_SECONDS" -gt 0 ]; then echo "候选槽稳定观察 ${STABILIZATION_SECONDS}s" sleep "$STABILIZATION_SECONDS" - [ "$(candidate_health)" = "healthy" ] || { cleanup_candidate; exit 1; } + [ "$(container_health "$candidate")" = "healthy" ] || { cleanup_candidate; exit 1; } fi if ! switch_gateway_proxy; then diff --git a/deploy/scripts/deploy-built-service.sh b/deploy/scripts/deploy-built-service.sh index 2320435d8..680ab07a8 100644 --- a/deploy/scripts/deploy-built-service.sh +++ b/deploy/scripts/deploy-built-service.sh @@ -389,20 +389,28 @@ run_ssh install -d -m 750 "$REMOTE_DIR" SUFFIX="${IMAGE_TAG}.$$.${SERVICE}" REMOTE_ENV_NAME=".env.$PROJECT_NAME" REMOTE_COMPOSE_NAME="docker-compose.$PROJECT_NAME.yml" +REMOTE_BLUE_GREEN_NAME="deploy-blue-green-service.sh" REMOTE_ENV_TMP="$REMOTE_DIR/$REMOTE_ENV_NAME.$SUFFIX.tmp" REMOTE_COMPOSE_TMP="$REMOTE_DIR/$REMOTE_COMPOSE_NAME.$SUFFIX.tmp" +REMOTE_BLUE_GREEN_TMP="$REMOTE_DIR/$REMOTE_BLUE_GREEN_NAME.$SUFFIX.tmp" run_scp "$ENV_FILE" "$SSH_TARGET:$REMOTE_ENV_TMP" run_scp "$COMPOSE_FILE" "$SSH_TARGET:$REMOTE_COMPOSE_TMP" -run_ssh sh -s -- "$REMOTE_ENV_TMP" "$REMOTE_COMPOSE_TMP" "$REMOTE_DIR/$REMOTE_ENV_NAME" "$REMOTE_DIR/$REMOTE_COMPOSE_NAME" <<'REMOTE_PREPARE' +run_scp "deploy/scripts/deploy-blue-green-service.sh" "$SSH_TARGET:$REMOTE_BLUE_GREEN_TMP" +run_ssh sh -s -- "$REMOTE_ENV_TMP" "$REMOTE_COMPOSE_TMP" "$REMOTE_BLUE_GREEN_TMP" \ + "$REMOTE_DIR/$REMOTE_ENV_NAME" "$REMOTE_DIR/$REMOTE_COMPOSE_NAME" "$REMOTE_DIR/$REMOTE_BLUE_GREEN_NAME" <<'REMOTE_PREPARE' set -eu env_tmp="$1" compose_tmp="$2" -env_target="$3" -compose_target="$4" +blue_green_tmp="$3" +env_target="$4" +compose_target="$5" +blue_green_target="$6" chmod 600 "$env_tmp" chmod 644 "$compose_tmp" +chmod 750 "$blue_green_tmp" mv -f "$env_tmp" "$env_target" mv -f "$compose_tmp" "$compose_target" +mv -f "$blue_green_tmp" "$blue_green_target" REMOTE_PREPARE remote_registry_logout() { @@ -414,6 +422,16 @@ printf '%s' "$REGISTRY_PASSWORD" | run_ssh docker login -u "$REGISTRY_USER" --pa trap remote_registry_logout EXIT HUP INT TERM run_ssh docker pull "$IMAGE" +if [ "$DEPLOY_ENV" = "production" ]; then + echo "生产服务使用蓝绿执行器,旧实例在候选槽健康前保持运行" + run_ssh sh "$REMOTE_DIR/$REMOTE_BLUE_GREEN_NAME" \ + "$DEPLOY_ENV" "$IMAGE_REPOSITORY" "$IMAGE_TAG" "$SERVICE" \ + "$REMOTE_DIR/$REMOTE_ENV_NAME" "$REMOTE_DIR/$REMOTE_COMPOSE_NAME" "$PROJECT_NAME" + remote_registry_logout + trap - EXIT HUP INT TERM + exit 0 +fi + run_ssh sh -s -- "$REMOTE_DIR" "$DEPLOY_ENV" "$IMAGE_REPOSITORY" "$IMAGE_TAG" "$SERVICE" "$PROJECT_NAME" "$REMOTE_ENV_NAME" "$REMOTE_COMPOSE_NAME" "$HEALTH_TIMEOUT_SECONDS" "$HEALTH_POLL_SECONDS" <<'REMOTE_DEPLOY' set -eu remote_dir="$1" diff --git a/event-bridge-service/src/main/java/com/baiyue/eventbridge/EventBridgeApplication.java b/event-bridge-service/src/main/java/com/baiyue/eventbridge/EventBridgeApplication.java index de2dd96ba..04f9c3db7 100644 --- a/event-bridge-service/src/main/java/com/baiyue/eventbridge/EventBridgeApplication.java +++ b/event-bridge-service/src/main/java/com/baiyue/eventbridge/EventBridgeApplication.java @@ -6,14 +6,12 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 跨区域事件桥启动入口。 */ @MapperScan(basePackages = "com.baiyue.eventbridge", annotationClass = Mapper.class) @SpringBootApplication -@EnableScheduling @EnableConfigurationProperties(EventDispatcherProperties.class) public class EventBridgeApplication { public static void main(String[] args) { diff --git a/file/src/main/java/com/baiyue/file/FileServiceApplication.java b/file/src/main/java/com/baiyue/file/FileServiceApplication.java index 9bdb9a83d..17b255110 100644 --- a/file/src/main/java/com/baiyue/file/FileServiceApplication.java +++ b/file/src/main/java/com/baiyue/file/FileServiceApplication.java @@ -5,7 +5,6 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 文件中心服务启动入口。 @@ -13,7 +12,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication(scanBasePackages = "com.baiyue") @MapperScan(basePackages = "com.baiyue.file", annotationClass = Mapper.class) @EnableFeignClients(basePackages = "com.baiyue.file.client") -@EnableScheduling public class FileServiceApplication { public static void main(String[] args) { SpringApplication.run(FileServiceApplication.class, args); diff --git a/finance/src/main/java/com/baiyue/finance/BaiyueFinanceApplication.java b/finance/src/main/java/com/baiyue/finance/BaiyueFinanceApplication.java index b29f68e94..393a7791b 100644 --- a/finance/src/main/java/com/baiyue/finance/BaiyueFinanceApplication.java +++ b/finance/src/main/java/com/baiyue/finance/BaiyueFinanceApplication.java @@ -5,13 +5,11 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; /** Finance 独立服务启动入口。首期只承载人工账单、收款和成本台账。 */ @SpringBootApplication @MapperScan(basePackages = "com.baiyue.finance", annotationClass = Mapper.class) @EnableFeignClients(basePackages = "com.baiyue.finance.client") -@EnableScheduling public class BaiyueFinanceApplication { public static void main(String[] args) { diff --git a/finance/src/test/java/com/baiyue/finance/FinanceContractTest.java b/finance/src/test/java/com/baiyue/finance/FinanceContractTest.java index d3cbb730c..1c052ca3f 100644 --- a/finance/src/test/java/com/baiyue/finance/FinanceContractTest.java +++ b/finance/src/test/java/com/baiyue/finance/FinanceContractTest.java @@ -12,7 +12,9 @@ import static org.junit.jupiter.api.Assertions.*; class FinanceContractTest { @Test void applicationEnablesReliableOutboxScheduling() { - assertNotNull(BaiyueFinanceApplication.class.getAnnotation(org.springframework.scheduling.annotation.EnableScheduling.class)); + assertNull(BaiyueFinanceApplication.class.getAnnotation(org.springframework.scheduling.annotation.EnableScheduling.class)); + assertNotNull(com.baiyue.common.web.BaiyueSchedulingAutoConfiguration.class + .getAnnotation(org.springframework.scheduling.annotation.EnableScheduling.class)); } @Test diff --git a/firstleg/src/main/java/com/baiyue/firstleg/BaiyueFirstlegApplication.java b/firstleg/src/main/java/com/baiyue/firstleg/BaiyueFirstlegApplication.java index f3a095053..9f4ac0d8d 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/BaiyueFirstlegApplication.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/BaiyueFirstlegApplication.java @@ -5,14 +5,12 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 头程履约微服务启动入口,负责装配履约任务组件并扫描 MyBatis-Plus Mapper。 */ @MapperScan(basePackages = "com.baiyue.firstleg", annotationClass = Mapper.class) @EnableFeignClients(basePackages = "com.baiyue.firstleg") -@EnableScheduling @SpringBootApplication(scanBasePackages = "com.baiyue") public class BaiyueFirstlegApplication { public static void main(String[] args) { SpringApplication.run(BaiyueFirstlegApplication.class, args); } diff --git a/iam/src/main/java/com/baiyue/iam/BaiyueIamApplication.java b/iam/src/main/java/com/baiyue/iam/BaiyueIamApplication.java index 482eb26dc..20e028883 100644 --- a/iam/src/main/java/com/baiyue/iam/BaiyueIamApplication.java +++ b/iam/src/main/java/com/baiyue/iam/BaiyueIamApplication.java @@ -5,14 +5,12 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 身份与权限服务启动入口,负责装配租户、成员、双端 RBAC 和授权快照相关组件。 */ @MapperScan(basePackages = "com.baiyue.iam", annotationClass = Mapper.class) @EnableFeignClients(basePackages = "com.baiyue.iam.client") -@EnableScheduling @SpringBootApplication(scanBasePackages = "com.baiyue") public class BaiyueIamApplication { public static void main(String[] args) { SpringApplication.run(BaiyueIamApplication.class, args); } diff --git a/lastleg-service/src/main/java/com/baiyue/lastleg/BaiyueLastlegApplication.java b/lastleg-service/src/main/java/com/baiyue/lastleg/BaiyueLastlegApplication.java index fba80bf56..370703832 100644 --- a/lastleg-service/src/main/java/com/baiyue/lastleg/BaiyueLastlegApplication.java +++ b/lastleg-service/src/main/java/com/baiyue/lastleg/BaiyueLastlegApplication.java @@ -5,14 +5,12 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 尾程微服务预留模块启动入口,初始化 Spring Boot 应用并扫描尾程 Mapper。 */ @MapperScan(basePackages = "com.baiyue.lastleg", annotationClass = Mapper.class) @EnableFeignClients(basePackages = "com.baiyue.lastleg") -@EnableScheduling @SpringBootApplication(scanBasePackages = "com.baiyue") public class BaiyueLastlegApplication { public static void main(String[] args) { SpringApplication.run(BaiyueLastlegApplication.class, args); } diff --git a/order/src/main/java/com/baiyue/order/BaiyueOrderApplication.java b/order/src/main/java/com/baiyue/order/BaiyueOrderApplication.java index ebcd62383..98321985f 100644 --- a/order/src/main/java/com/baiyue/order/BaiyueOrderApplication.java +++ b/order/src/main/java/com/baiyue/order/BaiyueOrderApplication.java @@ -5,14 +5,12 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; /** * 订单微服务启动入口,负责装配订单领域组件并扫描 MyBatis-Plus Mapper。 */ @MapperScan(basePackages = "com.baiyue.order", annotationClass = Mapper.class) @EnableFeignClients(basePackages = "com.baiyue.order.client") -@EnableScheduling @SpringBootApplication(scanBasePackages = "com.baiyue") public class BaiyueOrderApplication { public static void main(String[] args) { diff --git a/scripts/blue-green-deployment-contract.test.mjs b/scripts/blue-green-deployment-contract.test.mjs new file mode 100644 index 000000000..27e657bd4 --- /dev/null +++ b/scripts/blue-green-deployment-contract.test.mjs @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import test from 'node:test' + +const read = async (path) => (await readFile(new URL(`../${path}`, import.meta.url), 'utf8')) + .replaceAll('\r\n', '\n') + +test('all backend business services have blue-green runtime contracts', async () => { + const script = await read('deploy/scripts/deploy-blue-green-service.sh') + for (const service of [ + 'gateway', 'auth', 'iam', 'firstleg', 'finance', 'order', 'warehouse', 'file', 'print', + 'integration-service', 'audit-service', 'gateway-overseas', 'lastleg-service', + 'warehouse-overseas-service', 'event-bridge-service' + ]) assert.match(script, new RegExp(`${service.replaceAll('-', '\\-')}:`)) + + assert.match(script, /target_slot="green"/) + assert.match(script, /target_port=\$\(\(BASE_PORT \+ 10000\)\)/) + assert.match(script, /compose run -d --no-deps --name "\$candidate"/) + assert.match(script, /wait_for_candidate/) + assert.match(script, /connect_routing_alias "\$ROUTING_ALIAS" "\$candidate"/) + assert.match(script, /docker stop --time "\$STOP_TIMEOUT" "\$active_container"/) + assert.match(script, /mv -f "\$STATE_FILE\.tmp" "\$STATE_FILE"/) +}) + +test('candidate failure keeps the active container and successful cutover stops it last', async () => { + const script = await read('deploy/scripts/deploy-blue-green-service.sh') + const start = script.indexOf('compose run -d') + const healthy = script.indexOf('if ! wait_for_candidate') + const route = script.indexOf('connect_routing_alias "$ROUTING_ALIAS" "$candidate"') + const gateway = script.indexOf('if ! switch_gateway_proxy') + const stop = script.indexOf('docker stop --time "$STOP_TIMEOUT" "$active_container"') + const state = script.indexOf('mv -f "$STATE_FILE.tmp" "$STATE_FILE"') + assert.ok(start >= 0 && start < healthy) + assert.ok(healthy < route && route < gateway && gateway < stop && stop < state) + assert.match(script.slice(healthy, route), /cleanup_candidate/) +}) + +test('gateway cutover is atomic and restores nginx config on validation failure', async () => { + const script = await read('deploy/scripts/deploy-blue-green-service.sh') + assert.match(script, /api-cn\.buggoglobal\.com\.conf/) + assert.match(script, /api-global\.buggoglobal\.com\.conf/) + assert.match(script, /cp -f "\$config" "\$backup"/) + assert.match(script, /nginx -t \|\| ! nginx -s reload/) + assert.match(script, /cp -f "\$backup" "\$config"/) +}) + +test('compose templates preserve rolling defaults and expose slot metadata', async () => { + const domestic = await read('deploy/docker-compose.yml') + const overseas = await read('deploy/docker-compose.overseas.yml') + for (const compose of [domestic, overseas]) { + assert.match(compose, /BAIYUE_DEPLOY_SLOT: \$\{DEPLOY_SLOT:-rolling\}/) + assert.match(compose, /BAIYUE_RELEASE_ID: \$\{RELEASE_ID:-local\}/) + assert.match(compose, /SERVER_SHUTDOWN: graceful/) + assert.match(compose, /stop_grace_period: \$\{STOP_GRACE_PERIOD:-45s\}/) + assert.match(compose, /\$\{DEPLOY_SLOT_SUFFIX:-\}/) + } +}) + +test('production single-service pipeline dispatches the blue-green executor', async () => { + const deploy = await read('deploy/scripts/deploy-built-service.sh') + assert.match(deploy, /run_scp "deploy\/scripts\/deploy-blue-green-service\.sh"/) + assert.match(deploy, /if \[ "\$DEPLOY_ENV" = "production" \]/) + assert.match(deploy, /run_ssh sh "\$REMOTE_DIR\/\$REMOTE_BLUE_GREEN_NAME"/) +}) diff --git a/scripts/blue-green-deployment-runtime.test.mjs b/scripts/blue-green-deployment-runtime.test.mjs new file mode 100644 index 000000000..c03b49776 --- /dev/null +++ b/scripts/blue-green-deployment-runtime.test.mjs @@ -0,0 +1,140 @@ +import assert from 'node:assert/strict' +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { delimiter, join, resolve } from 'node:path' +import { tmpdir } from 'node:os' +import { spawnSync } from 'node:child_process' +import test from 'node:test' + +const root = resolve(import.meta.dirname, '..') +const script = resolve(root, 'deploy/scripts/deploy-blue-green-service.sh') +const shell = process.platform === 'win32' ? 'C:/Program Files/Git/bin/bash.exe' : '/bin/sh' + +const dockerMock = `#!/usr/bin/env sh +set -eu +printf '%s\\n' "$*" >> "$MOCK_LOG" +command="$1" +shift +case "$command" in + network) + [ "$1" = inspect ] && { echo '{}'; exit 0; } + exit 0 + ;; + compose) + for argument in "$@"; do + if [ "$argument" = run ]; then + : > "$MOCK_CANDIDATE_EXISTS" + exit 0 + fi + done + exit 0 + ;; + inspect) + target='' + for argument in "$@"; do target="$argument"; done + case "$target" in + firstleg-production-file) + [ ! -f "$MOCK_LEGACY_REMOVED" ] + ;; + firstleg-production-file-green) + [ -f "$MOCK_CANDIDATE_EXISTS" ] || exit 1 + case "$*" in + *State.Health*) printf '%s\\n' "\${MOCK_CANDIDATE_HEALTH:-healthy}" ;; + *Config.Image*) printf '%s\\n' 'registry.local/group/file:newtag' ;; + esac + ;; + *) exit 1 ;; + esac + ;; + stop) + target='' + for argument in "$@"; do target="$argument"; done + [ "$target" = firstleg-production-file ] && : > "$MOCK_LEGACY_STOPPED" + ;; + rm) + target='' + for argument in "$@"; do target="$argument"; done + case "$target" in + firstleg-production-file) : > "$MOCK_LEGACY_REMOVED" ;; + firstleg-production-file-green) rm -f "$MOCK_CANDIDATE_EXISTS" ;; + esac + ;; + logs) echo 'candidate logs' ;; + *) echo "unexpected docker command: $command $*" >&2; exit 2 ;; +esac +` + +async function runBlueGreen(health) { + const temp = await mkdtemp(join(tmpdir(), 'blue-green-runtime-')) + const bin = join(temp, 'bin') + const docker = join(bin, 'docker') + const sleep = join(bin, 'sleep') + const envFile = join(temp, 'deployment.env') + const compose = join(temp, 'compose.yml') + const stateRoot = join(temp, 'state') + const log = join(temp, 'docker.log') + await mkdir(bin) + await mkdir(stateRoot) + await writeFile(docker, dockerMock, 'utf8') + await writeFile(sleep, '#!/usr/bin/env sh\nexit 0\n', 'utf8') + await chmod(docker, 0o755) + await chmod(sleep, 0o755) + await writeFile(envFile, 'PLACEHOLDER=true\n', 'utf8') + await writeFile(compose, 'services: {}\n', 'utf8') + await writeFile(log, '', 'utf8') + + const paths = { + candidate: join(temp, 'candidate'), stopped: join(temp, 'legacy-stopped'), + removed: join(temp, 'legacy-removed') + } + const result = spawnSync(shell, [ + script.replaceAll('\\', '/'), 'production', 'registry.local/group', 'newtag', 'file', + envFile.replaceAll('\\', '/'), compose.replaceAll('\\', '/'), 'firstleg-production' + ], { + cwd: root, encoding: 'utf8', env: { + ...process.env, + PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`, + BLUE_GREEN_STATE_ROOT: stateRoot, + BLUE_GREEN_STABILIZATION_SECONDS: '0', + DEPLOY_HEALTH_TIMEOUT_SECONDS: '2', + DEPLOY_HEALTH_POLL_SECONDS: '1', + MOCK_LOG: log, + MOCK_CANDIDATE_EXISTS: paths.candidate, + MOCK_LEGACY_STOPPED: paths.stopped, + MOCK_LEGACY_REMOVED: paths.removed, + MOCK_CANDIDATE_HEALTH: health + } + }) + const output = `${result.stdout}\n${result.stderr}` + const dockerLog = await readFile(log, 'utf8') + const stateFile = join(stateRoot, 'firstleg-production-file.active') + const state = existsSync(stateFile) ? await readFile(stateFile, 'utf8') : '' + const evidence = { + ...result, output, dockerLog, state, + stopped: existsSync(paths.stopped), removed: existsSync(paths.removed) + } + await rm(temp, { recursive: true, force: true }) + return evidence +} + +test('healthy candidate becomes active only after health and old instance drains', async (context) => { + if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`) + const result = await runBlueGreen('healthy') + assert.equal(result.status, 0, result.output) + assert.equal(result.stopped, true) + assert.equal(result.removed, true) + assert.match(result.state, /^green\|firstleg-production-file-green\|19206\|registry\.local\/group\/file:newtag/) + const run = result.dockerLog.indexOf('compose --project-name firstleg-production') + const stop = result.dockerLog.indexOf('stop --time 45 firstleg-production-file') + assert.ok(run >= 0 && run < stop) +}) + +test('unhealthy candidate is removed while old instance and state remain untouched', async (context) => { + if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`) + const result = await runBlueGreen('unhealthy') + assert.equal(result.status, 1, result.output) + assert.equal(result.stopped, false) + assert.equal(result.removed, false) + assert.equal(result.state, '') + assert.doesNotMatch(result.dockerLog, /stop --time .*firstleg-production-file/) +}) diff --git a/scripts/overseas-deployment-contract.test.mjs b/scripts/overseas-deployment-contract.test.mjs index aa85ff3e8..33ad829cf 100644 --- a/scripts/overseas-deployment-contract.test.mjs +++ b/scripts/overseas-deployment-contract.test.mjs @@ -76,7 +76,7 @@ test('overseas compose is isolated from CN defaults and disables implicit schema assert.match(compose, /^ lastleg-service:\s*$/m) assert.match(compose, /^ warehouse-overseas-service:\s*$/m) assert.match(compose, /^ event-bridge-service:\s*$/m) - assert.match(compose, /EVENT_BRIDGE_OVERSEAS_PORT:-9313}:9312/) + assert.match(compose, /EVENT_BRIDGE_OVERSEAS_PUBLISHED_PORT:-\$\{EVENT_BRIDGE_OVERSEAS_PORT:-9313\}}:9312/) assert.match(compose, /INTERNAL_SERVICE_TOKEN: \$\{INTERNAL_SERVICE_TOKEN\}/) assert.match(compose, /LASTLEG_DB_URL: \$\{LASTLEG_DB_URL\}/) assert.match(compose, /EVENT_BRIDGE_DB_URL: \$\{EVENT_BRIDGE_OVERSEAS_DB_URL\}/) diff --git a/scripts/test-environment-pipeline-contract.test.mjs b/scripts/test-environment-pipeline-contract.test.mjs index e51a32b24..875963bea 100644 --- a/scripts/test-environment-pipeline-contract.test.mjs +++ b/scripts/test-environment-pipeline-contract.test.mjs @@ -180,10 +180,12 @@ test('parallel remote deployments keep env and compose assets isolated by projec assert.match(directDeployScript, /REMOTE_COMPOSE_NAME="docker-compose\.\$PROJECT_NAME\.yml"/) assert.match(directDeployScript, /REMOTE_ENV_TMP="\$REMOTE_DIR\/\$REMOTE_ENV_NAME\.\$SUFFIX\.tmp"/) assert.match(directDeployScript, /REMOTE_COMPOSE_TMP="\$REMOTE_DIR\/\$REMOTE_COMPOSE_NAME\.\$SUFFIX\.tmp"/) - assert.match(directDeployScript, /env_target="\$3"/) - assert.match(directDeployScript, /compose_target="\$4"/) + assert.match(directDeployScript, /env_target="\$4"/) + assert.match(directDeployScript, /compose_target="\$5"/) + assert.match(directDeployScript, /blue_green_target="\$6"/) assert.match(directDeployScript, /mv -f "\$env_tmp" "\$env_target"/) assert.match(directDeployScript, /mv -f "\$compose_tmp" "\$compose_target"/) + assert.match(directDeployScript, /mv -f "\$blue_green_tmp" "\$blue_green_target"/) assert.match(directDeployScript, /env_file="\$7"/) assert.match(directDeployScript, /compose_file="\$8"/) assert.match(directDeployScript, /--env-file "\$env_file"/)