Explorar o código

新增旧生产全站复制到HXCS影子环境工具

实现旧生产 56 个网站、栏目、文章、模板、权限、流程及聚合统计到 HXCS 影子数据库的只读复制与合并流程。任务通过 HXCS 主机直连旧生产,使用 setsid 脱离会话运行,不依赖本机 VPN 保活。\n\n新增本地控制入口和 HXCS 端执行程序,支持预检、旧生产快照、影子库构建、引用资源暂存、双节点校验、临时 Tomcat HTTP 验证及后台状态查看。明确保护 HXCS 新建网站,不修改当前运行库、webapp、Redis、Tomcat、域名或 DNS。\n\nValidation:\n- bash -n local-run/bin/legacy-sites-to-hxcs.sh\n- python3 -m py_compile local-run/bin/legacy-sites-job.py\n- HXCS 预检通过:56 个旧站、5 个保护新站、磁盘可用 287.1GB\n- HXCS 后台任务已启动,旧生产 core/apps 快照均已完成
非繁 hai 3 semanas
pai
achega
987f5daf6f
Modificáronse 2 ficheiros con 1110 adicións e 0 borrados
  1. 927 0
      local-run/bin/legacy-sites-job.py
  2. 183 0
      local-run/bin/legacy-sites-to-hxcs.sh

+ 927 - 0
local-run/bin/legacy-sites-job.py

@@ -0,0 +1,927 @@
+#!/usr/bin/env python3
+"""Copy the legacy GZHX production sites into isolated HXCS shadow databases.
+
+Runs on HXCS 10.0.42.6.  The legacy server is only read through SSH and
+mysqldump --single-transaction.  Live HXCS databases, webapps, Tomcat, Redis,
+domains and DNS are never changed by this tool.
+"""
+from __future__ import annotations
+
+import fcntl
+import hashlib
+import json
+import os
+import re
+import shlex
+import shutil
+import socket
+import subprocess
+import sys
+import tarfile
+import time
+import traceback
+from datetime import datetime
+from pathlib import Path
+from urllib.parse import unquote, urlparse
+
+os.environ.setdefault("TZ", "Asia/Shanghai")
+try:
+    time.tzset()
+except AttributeError:
+    pass
+
+RUN_ROOT = Path(os.environ.get("LEGACY_RUN_ROOT", "/home/hxxy/zq/staging/legacy-sites-20261103"))
+TOOLS_DIR = RUN_ROOT / "tools"
+REPORT_DIR = RUN_ROOT / "reports"
+STAGE_WEBAPP = RUN_ROOT / "webapp"
+VERIFY_WEBAPP = RUN_ROOT / "verify-webapp"
+STATUS_FILE = RUN_ROOT / "status.json"
+LOG_FILE = REPORT_DIR / "job.log"
+LOCK_FILE = RUN_ROOT / ".job.lock"
+ENV_FILE = RUN_ROOT / ".runtime.env"
+
+MYSQL_CONTAINER = "mysql57"
+SOURCE_HOST = "root@10.0.42.49"
+SOURCE_APP = "/home/data/project/app"
+SOURCE_MYSQL = "/usr/local/mysql/mysql-5.7.26-linux-glibc2.12-x86_64/bin/mysql"
+SOURCE_DUMP = "/usr/local/mysql/mysql-5.7.26-linux-glibc2.12-x86_64/bin/mysqldump"
+SOURCE_CORE = "sp_gzhx_core"
+SOURCE_APPS = "sp_gzhx_apps"
+TARGET_CORE = "sp_gzhx_core_mig_next"
+TARGET_APPS = "sp_gzhx_apps_mig_next"
+LEGACY_CORE = "sp_gzhx_core_legacy_20261103"
+LEGACY_APPS = "sp_gzhx_apps_legacy_20261103"
+SWITCH_CORE = "sp_gzhx_core_switch_20261103"
+SWITCH_APPS = "sp_gzhx_apps_switch_20261103"
+VERIFY_CONTAINER = "zq-tomcat-legacy-verify"
+VERIFY_PORT = 18080
+PROTECTED_BEFORE = REPORT_DIR / "protected-before.json"
+ASSET_LIST = REPORT_DIR / "asset-files.txt"
+ASSET_MISSING = REPORT_DIR / "asset-missing.tsv"
+MERGE_REPORT = REPORT_DIR / "merge-report.json"
+VERIFY_REPORT = REPORT_DIR / "verify-report.json"
+
+
+class JobError(RuntimeError):
+    pass
+
+
+def now() -> str:
+    return datetime.now().astimezone().isoformat(timespec="seconds")
+
+
+def log(message: str) -> None:
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    line = f"[{now()}] {message}"
+    print(line, flush=True)
+    with LOG_FILE.open("a", encoding="utf-8") as fh:
+        fh.write(line + "\n")
+
+
+def load_env_file() -> None:
+    if not ENV_FILE.is_file():
+        return
+    for raw in ENV_FILE.read_text(encoding="utf-8").splitlines():
+        line = raw.strip()
+        if not line or line.startswith("#") or "=" not in line:
+            continue
+        key, value = line.split("=", 1)
+        if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
+            os.environ[key] = shlex.split(value)[0] if value else ""
+
+
+def require_env(name: str) -> str:
+    value = os.environ.get(name, "")
+    if not value:
+        raise JobError(f"缺少运行环境变量:{name}")
+    return value
+
+
+def atomic_json(path: Path, data: dict) -> None:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    temporary = path.with_suffix(path.suffix + ".tmp")
+    temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+    temporary.replace(path)
+
+
+def update_status(**changes) -> None:
+    current: dict = {}
+    if STATUS_FILE.is_file():
+        try:
+            current = json.loads(STATUS_FILE.read_text(encoding="utf-8"))
+        except Exception:
+            current = {}
+    current.update(changes)
+    current["updated_at"] = now()
+    current["pid"] = os.getpid()
+    atomic_json(STATUS_FILE, current)
+
+
+def run(command: list[str], *, input_data: bytes | None = None, stdout_path: Path | None = None,
+        stderr_path: Path | None = None, check: bool = True) -> subprocess.CompletedProcess:
+    log("执行:" + " ".join(shlex.quote(x) for x in command))
+    stdout = stdout_path.open("wb") if stdout_path else subprocess.PIPE
+    stderr = stderr_path.open("wb") if stderr_path else subprocess.PIPE
+    try:
+        proc = subprocess.run(command, input=input_data, stdout=stdout, stderr=stderr)
+    finally:
+        if stdout_path:
+            stdout.close()
+        if stderr_path:
+            stderr.close()
+    if check and proc.returncode != 0:
+        err = ""
+        if not stderr_path and proc.stderr:
+            err = proc.stderr.decode("utf-8", "replace")[-4000:]
+        raise JobError(f"命令失败({proc.returncode}):{' '.join(command[:4])}\n{err}")
+    return proc
+
+
+def docker_env() -> dict[str, str]:
+    env = os.environ.copy()
+    env["MYSQL_PWD"] = require_env("HXCS_MYSQL_PASS")
+    return env
+
+
+def mysql(sql: str, db: str | None = None, *, capture: bool = True) -> str:
+    command = ["docker", "exec", "-i", "-e", "MYSQL_PWD", MYSQL_CONTAINER,
+               "mysql", "-uroot", "--default-character-set=utf8mb4", "-N", "-B"]
+    if db:
+        command.append(db)
+    proc = subprocess.run(command, input=sql.encode(), stdout=subprocess.PIPE,
+                          stderr=subprocess.PIPE, env=docker_env())
+    if proc.returncode != 0:
+        raise JobError(proc.stderr.decode("utf-8", "replace")[-8000:])
+    return proc.stdout.decode("utf-8", "replace") if capture else ""
+
+
+def mysql_values(sql: str, db: str | None = None) -> list[str]:
+    return [line for line in mysql(sql, db).splitlines() if line != ""]
+
+
+def sql_string(value: str) -> str:
+    return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
+
+
+def database_exists(name: str) -> bool:
+    found = mysql(f"SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name={sql_string(name)};").strip()
+    return found == "1"
+
+
+def create_empty_database(name: str) -> None:
+    if database_exists(name):
+        raise JobError(f"目标数据库已存在,拒绝覆盖:{name}")
+    mysql(f"CREATE DATABASE `{name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;")
+    log(f"已创建空数据库:{name}")
+
+
+def mysql_printable_name(name: str) -> str:
+    if not re.fullmatch(r"[A-Za-z0-9_]+", name):
+        raise JobError(f"非法数据库名:{name}")
+    return f"`{name}`"
+
+
+def askpass_file(path: Path, password: str) -> None:
+    path.write_text("#!/bin/sh\nprintf '%s\\n' " + shlex.quote(password) + "\n", encoding="utf-8")
+    path.chmod(0o700)
+
+
+def ssh_env(askpass: Path) -> dict[str, str]:
+    env = os.environ.copy()
+    env["SSH_ASKPASS"] = str(askpass)
+    env["SSH_ASKPASS_REQUIRE"] = "force"
+    env["DISPLAY"] = env.get("DISPLAY", ":0")
+    return env
+
+
+def source_ssh(script: str, *, stdout_path: Path | None = None,
+               stderr_path: Path | None = None) -> subprocess.CompletedProcess:
+    askpass = RUN_ROOT / ".askpass-prod.sh"
+    askpass_file(askpass, require_env("PROD_SSH_PASS"))
+    command = ["setsid", "-w", "ssh", "-T", "-o", "StrictHostKeyChecking=no",
+               "-o", "ConnectTimeout=15", SOURCE_HOST, "bash -s"]
+    log("旧生产 SSH:只读脚本执行")
+    stdout = stdout_path.open("wb") if stdout_path else subprocess.PIPE
+    stderr = stderr_path.open("wb") if stderr_path else subprocess.PIPE
+    try:
+        proc = subprocess.run(command, input=script.encode(), stdout=stdout, stderr=stderr,
+                              env=ssh_env(askpass))
+    finally:
+        if stdout_path:
+            stdout.close()
+        if stderr_path:
+            stderr.close()
+    if proc.returncode != 0:
+        err = ""
+        if not stderr_path and proc.stderr:
+            err = proc.stderr.decode("utf-8", "replace")[-8000:]
+        raise JobError(f"旧生产 SSH 脚本失败({proc.returncode})\n{err}")
+    return proc
+
+
+def source_mysql_query(sql: str) -> list[str]:
+    script = f"""set -euo pipefail
+export LC_ALL=C
+MYSQL_PWD={shlex.quote(require_env('PROD_MYSQL_PASS'))} {SOURCE_MYSQL} -h127.0.0.1 -uroot --default-character-set=utf8mb4 -N -B -e {shlex.quote(sql)}
+"""
+    proc = source_ssh(script)
+    return [line for line in proc.stdout.decode("utf-8", "replace").splitlines() if line != ""]
+
+
+def source_dump_to_database(source_db: str, destination_db: str, ignore_table: str | None = None) -> None:
+    create_empty_database(destination_db)
+    ignore = f"--ignore-table={ignore_table} " if ignore_table else ""
+    script = f"""set -euo pipefail
+export LC_ALL=C
+MYSQL_PWD={shlex.quote(require_env('PROD_MYSQL_PASS'))} {SOURCE_DUMP} \
+ --single-transaction --quick --skip-lock-tables --default-character-set=utf8mb4 \
+ --no-create-db --routines --triggers {ignore}{source_db}
+"""
+    askpass = RUN_ROOT / ".askpass-prod.sh"
+    askpass_file(askpass, require_env("PROD_SSH_PASS"))
+    source_cmd = ["setsid", "-w", "ssh", "-T", "-o", "StrictHostKeyChecking=no",
+                  "-o", "ConnectTimeout=15", SOURCE_HOST, "bash -s"]
+    load_cmd = ["docker", "exec", "-i", "-e", "MYSQL_PWD", MYSQL_CONTAINER,
+                "mysql", "-uroot", "--binary-mode", "--default-character-set=utf8mb4", destination_db]
+    log(f"流式导出旧生产 {source_db} -> {destination_db}")
+    source = subprocess.Popen(source_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE, env=ssh_env(askpass))
+    loader = subprocess.Popen(load_cmd, stdin=source.stdout, stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE, env=docker_env())
+    assert source.stdin is not None and source.stdout is not None
+    source.stdin.write(script.encode())
+    source.stdin.close()
+    source.stdout.close()
+    load_out, load_err = loader.communicate()
+    source_err = source.stderr.read() if source.stderr else b""
+    source_rc = source.wait()
+    if source_rc != 0 or loader.returncode != 0:
+        raise JobError("旧生产数据库流式复制失败\n" + source_err.decode("utf-8", "replace")[-4000:] +
+                       "\n" + load_err.decode("utf-8", "replace")[-4000:])
+    log(f"旧生产 {source_db} 快照完成;导入输出 {len(load_out or b'')} 字节")
+
+
+def clone_database(source_db: str, destination_db: str) -> None:
+    create_empty_database(destination_db)
+    dump_cmd = ["docker", "exec", "-e", "MYSQL_PWD", MYSQL_CONTAINER, "mysqldump",
+                "-uroot", "--single-transaction", "--quick", "--skip-lock-tables",
+                "--default-character-set=utf8mb4", "--routines", "--triggers",
+                "--no-create-db", source_db]
+    load_cmd = ["docker", "exec", "-i", "-e", "MYSQL_PWD", MYSQL_CONTAINER,
+                "mysql", "-uroot", "--binary-mode", "--default-character-set=utf8mb4", destination_db]
+    log(f"本地复制 {source_db} -> {destination_db}")
+    dump = subprocess.Popen(dump_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=docker_env())
+    loader = subprocess.Popen(load_cmd, stdin=dump.stdout, stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE, env=docker_env())
+    assert dump.stdout is not None
+    dump.stdout.close()
+    load_out, load_err = loader.communicate()
+    dump_err = dump.stderr.read() if dump.stderr else b""
+    dump_rc = dump.wait()
+    if dump_rc != 0 or loader.returncode != 0:
+        raise JobError("HXCS 数据库复制失败\n" + dump_err.decode("utf-8", "replace")[-4000:] +
+                       "\n" + load_err.decode("utf-8", "replace")[-4000:])
+    log(f"本地复制完成:{destination_db}")
+
+
+def query_source_websites() -> list[dict]:
+    rows = source_mysql_query(
+        "SELECT websiteid,dcode,name,domains,protocol,port,catalog_uri,IFNULL(id_code,'') "
+        f"FROM {SOURCE_APPS}.website ORDER BY websiteid;")
+    result = []
+    for line in rows:
+        fields = line.split("\t")
+        if len(fields) != 8:
+            raise JobError(f"无法解析旧生产网站记录:{line[:200]}")
+        result.append({
+            "websiteid": int(fields[0]), "dcode": int(fields[1]), "name": fields[2],
+            "domains": fields[3], "protocol": fields[4], "port": int(fields[5]),
+            "catalog_uri": fields[6], "id_code": fields[7],
+        })
+    return result
+
+
+def preflight() -> dict:
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    TOOLS_DIR.mkdir(parents=True, exist_ok=True)
+    STAGE_WEBAPP.mkdir(parents=True, exist_ok=True)
+    require_env("HXCS_MYSQL_PASS")
+    require_env("PROD_SSH_PASS")
+    require_env("PROD_MYSQL_PASS")
+    require_env("HXCS_WEB2_SSH_PASS")
+    for db in (LEGACY_CORE, LEGACY_APPS, SWITCH_CORE, SWITCH_APPS):
+        if database_exists(db):
+            raise JobError(f"预检发现目标数据库已存在,不能开始新任务:{db}")
+    if not shutil.which("rsync") or not shutil.which("tar"):
+        raise JobError("HXCS 缺少 rsync 或 tar")
+    free_kb = int(subprocess.check_output(["df", "-Pk", str(RUN_ROOT)], text=True).splitlines()[-1].split()[3])
+    if free_kb < 60 * 1024 * 1024:
+        raise JobError(f"HXCS 可用磁盘不足 60GB:{free_kb // 1024}MB")
+    websites = query_source_websites()
+    if not websites:
+        raise JobError("旧生产未读取到网站记录")
+    source_ids = {w["websiteid"] for w in websites}
+    all_target = mysql_values("SELECT websiteid FROM website ORDER BY websiteid;", TARGET_APPS)
+    protected = [int(x) for x in all_target if int(x) not in source_ids]
+    if not protected:
+        raise JobError("未识别到 hxcs 新建网站,拒绝覆盖式合并")
+    dup_hosts: dict[str, list[int]] = {}
+    for w in websites:
+        for host in (x.strip().lower() for x in w["domains"].split(";") if x.strip()):
+            dup_hosts.setdefault(host, []).append(w["websiteid"])
+    duplicates = {h: ids for h, ids in dup_hosts.items() if len(ids) > 1}
+    result = {
+        "source_websites": len(websites), "source_active": sum(w["dcode"] == 61 for w in websites),
+        "source_disabled": sum(w["dcode"] != 61 for w in websites),
+        "protected_websites": protected, "duplicate_domains": duplicates,
+        "free_gb": round(free_kb / 1024 / 1024, 1), "source_websites_data": websites,
+    }
+    atomic_json(REPORT_DIR / "preflight.json", result)
+    log(f"预检通过:旧站 {len(websites)},新站保护 {protected},磁盘可用 {result['free_gb']}GB")
+    return result
+
+
+def snapshot() -> None:
+    source_dump_to_database(SOURCE_CORE, LEGACY_CORE)
+    source_dump_to_database(SOURCE_APPS, LEGACY_APPS,
+                            ignore_table=f"{SOURCE_APPS}.website_visit_log")
+    counts = mysql_values(
+        "SELECT 'website',COUNT(*) FROM website UNION ALL "
+        "SELECT 'article',COUNT(*) FROM article UNION ALL "
+        "SELECT 'website_navigation',COUNT(*) FROM website_navigation UNION ALL "
+        "SELECT 'website_statistics',COUNT(*) FROM website_statistics;", LEGACY_APPS)
+    (REPORT_DIR / "snapshot-counts.txt").write_text("\n".join(counts) + "\n", encoding="utf-8")
+
+
+def source_columns(schema: str, table: str) -> list[str]:
+    return mysql_values(
+        "SELECT column_name FROM information_schema.columns "
+        f"WHERE table_schema={sql_string(schema)} AND table_name={sql_string(table)} "
+        "ORDER BY ordinal_position;")
+
+
+def target_table_columns(table: str, schema: str = SWITCH_APPS) -> list[str]:
+    return source_columns(schema, table)
+
+
+def primary_columns(schema: str, table: str) -> list[str]:
+    return mysql_values(
+        "SELECT column_name FROM information_schema.key_column_usage "
+        f"WHERE table_schema={sql_string(schema)} AND table_name={sql_string(table)} "
+        "AND constraint_name='PRIMARY' ORDER BY ordinal_position;")
+
+
+def unique_index_columns(schema: str, table: str) -> list[str]:
+    rows = mysql_values(
+        "SELECT index_name,column_name,seq_in_index FROM information_schema.statistics "
+        f"WHERE table_schema={sql_string(schema)} AND table_name={sql_string(table)} "
+        "AND non_unique=0 AND index_name<>'PRIMARY' ORDER BY index_name,seq_in_index;")
+    grouped: dict[str, list[str]] = {}
+    for row in rows:
+        index, col, _ = row.split("\t")
+        grouped.setdefault(index, []).append(col)
+    return next(iter(grouped.values()), [])
+
+
+def all_base_tables(schema: str) -> list[str]:
+    return mysql_values(
+        "SELECT table_name FROM information_schema.tables "
+        f"WHERE table_schema={sql_string(schema)} AND table_type='BASE TABLE' "
+        "ORDER BY table_name;")
+
+
+def build_scope_tables() -> None:
+    for table in ("_legacy_scope_website", "_legacy_scope_nav", "_legacy_scope_article", "_legacy_scope_template"):
+        mysql(f"DROP TABLE IF EXISTS `{table}`;", SWITCH_APPS)
+    mysql(
+        "CREATE TABLE _legacy_scope_website (id INT PRIMARY KEY);"
+        "CREATE TABLE _legacy_scope_nav (id INT PRIMARY KEY);"
+        "CREATE TABLE _legacy_scope_article (id INT PRIMARY KEY);"
+        "CREATE TABLE _legacy_scope_template (id INT PRIMARY KEY);", SWITCH_APPS)
+    mysql(f"INSERT INTO _legacy_scope_website SELECT websiteid FROM {LEGACY_APPS}.website;", SWITCH_APPS)
+    mysql(f"INSERT INTO _legacy_scope_nav SELECT navigationid FROM {LEGACY_APPS}.website_navigation;", SWITCH_APPS)
+    mysql(f"INSERT INTO _legacy_scope_article SELECT articleid FROM {LEGACY_APPS}.article;", SWITCH_APPS)
+    mysql(f"INSERT INTO _legacy_scope_template SELECT wtid FROM {LEGACY_APPS}.website_template;", SWITCH_APPS)
+
+
+def table_is_scoped(table: str, cols: set[str]) -> bool:
+    return bool(cols & {"websiteid", "wtid", "navigationid", "articleid"})
+
+
+def scoped_delete_sql(table: str, cols: set[str], schema: str) -> str:
+    qtable = f"`{schema}`.`{table}`"
+    if "websiteid" in cols:
+        return f"DELETE FROM {qtable} WHERE websiteid IN (SELECT id FROM `{schema}`._legacy_scope_website);"
+    if "wtid" in cols:
+        return f"DELETE FROM {qtable} WHERE wtid IN (SELECT id FROM `{schema}`._legacy_scope_template);"
+    if "navigationid" in cols:
+        return (f"DELETE t FROM {qtable} t LEFT JOIN `{schema}`.website_navigation n "
+                f"ON n.navigationid=t.navigationid WHERE t.navigationid IN "
+                f"(SELECT id FROM `{schema}`._legacy_scope_nav) OR n.websiteid IN "
+                f"(SELECT id FROM `{schema}`._legacy_scope_website) OR n.wtid IN "
+                f"(SELECT id FROM `{schema}`._legacy_scope_template);")
+    if "articleid" in cols:
+        return (f"DELETE t FROM {qtable} t LEFT JOIN `{schema}`.article a "
+                f"ON a.articleid=t.articleid WHERE t.articleid IN "
+                f"(SELECT id FROM `{schema}`._legacy_scope_article) OR a.websiteid IN "
+                f"(SELECT id FROM `{schema}`._legacy_scope_website);")
+    return ""
+
+
+def merge_legacy_into_shadow() -> dict:
+    source_tables = [t for t in all_base_tables(LEGACY_APPS) if t != "website_visit_log"]
+    target_tables = set(all_base_tables(SWITCH_APPS))
+    missing_tables = sorted(set(source_tables) - target_tables)
+    if missing_tables:
+        raise JobError("HXCS 影子库缺少旧生产表:" + ",".join(missing_tables))
+    global_upserts: list[str] = []
+    scoped_inserts: list[str] = []
+    report: dict[str, dict] = {}
+    special = {"website", "website_template", "website_navigation", "article"}
+    direct = []
+    for table in source_tables:
+        src_cols = source_columns(LEGACY_APPS, table)
+        dst_cols = target_table_columns(table)
+        common = [c for c in src_cols if c in set(dst_cols)]
+        if not common:
+            raise JobError(f"表 {table} 无同名字段")
+        keys = primary_columns(LEGACY_APPS, table) or unique_index_columns(LEGACY_APPS, table)
+        if table_is_scoped(table, set(common)):
+            direct.append(table)
+        else:
+            if not keys:
+                raise JobError(f"全局表 {table} 无主键或唯一键,不能安全合并")
+            update = ",".join(f"`{c}`=VALUES(`{c}`)" for c in common)
+            cols_sql = ",".join(f"`{c}`" for c in common)
+            global_upserts.append(
+                f"INSERT INTO `{SWITCH_APPS}`.`{table}` ({cols_sql}) SELECT {cols_sql} "
+                f"FROM `{LEGACY_APPS}`.`{table}` ON DUPLICATE KEY UPDATE {update};")
+        cols_sql = ",".join(f"`{c}`" for c in common)
+        scoped_inserts.append(
+            f"INSERT INTO `{SWITCH_APPS}`.`{table}` ({cols_sql}) SELECT {cols_sql} "
+            f"FROM `{LEGACY_APPS}`.`{table}`;")
+        report[table] = {"columns": len(common), "scoped": table_is_scoped(table, set(common))}
+    statements = ["SET NAMES utf8mb4;", "SET FOREIGN_KEY_CHECKS=0;", "START TRANSACTION;"]
+    for table in direct:
+        if table not in special:
+            sql = scoped_delete_sql(table, set(source_columns(LEGACY_APPS, table)), SWITCH_APPS)
+            if sql:
+                statements.append(sql)
+    statements.append("DELETE FROM `" + SWITCH_APPS + "`.article WHERE websiteid IN "
+                      f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_website);")
+    statements.append("DELETE FROM `" + SWITCH_APPS + "`.website_navigation WHERE websiteid IN "
+                      f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_website) OR wtid IN "
+                      f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_template);")
+    statements.append("DELETE FROM `" + SWITCH_APPS + "`.website_template WHERE wtid IN "
+                      f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_template);")
+    statements.append("DELETE FROM `" + SWITCH_APPS + "`.website WHERE websiteid IN "
+                      f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_website);")
+    statements.extend(global_upserts)
+    statements.extend(scoped_inserts)
+    statements.extend(["COMMIT;", "SET FOREIGN_KEY_CHECKS=1;"])
+    sql_path = REPORT_DIR / "merge.sql"
+    sql_path.write_text("\n".join(statements) + "\n", encoding="utf-8")
+    log(f"开始合并 {len(source_tables)} 张旧生产表(直接范围 {len(direct)} 张)")
+    mysql(sql_path.read_text(encoding="utf-8"), SWITCH_APPS, capture=False)
+    atomic_json(MERGE_REPORT, report)
+    log("影子库合并完成")
+    return report
+
+
+def merge_core_tables() -> dict:
+    source_tables = all_base_tables(LEGACY_CORE)
+    target_tables = set(all_base_tables(SWITCH_CORE))
+    missing = sorted(set(source_tables) - target_tables)
+    if missing:
+        raise JobError("HXCS 核心影子库缺少旧生产表:" + ",".join(missing))
+    statements = ["SET NAMES utf8mb4;", "SET FOREIGN_KEY_CHECKS=0;", "START TRANSACTION;"]
+    report: dict[str, dict] = {}
+    for table in source_tables:
+        src_cols = source_columns(LEGACY_CORE, table)
+        dst_cols = source_columns(SWITCH_CORE, table)
+        common = [c for c in src_cols if c in set(dst_cols)]
+        if not common:
+            raise JobError(f"核心表 {table} 无同名字段")
+        keys = primary_columns(LEGACY_CORE, table) or unique_index_columns(LEGACY_CORE, table)
+        if not keys:
+            raise JobError(f"核心表 {table} 无主键或唯一键,不能安全合并")
+        cols_sql = ",".join(f"`{c}`" for c in common)
+        update = ",".join(f"`{c}`=VALUES(`{c}`)" for c in common)
+        statements.append(
+            f"INSERT INTO `{SWITCH_CORE}`.`{table}` ({cols_sql}) SELECT {cols_sql} "
+            f"FROM `{LEGACY_CORE}`.`{table}` ON DUPLICATE KEY UPDATE {update};")
+        report[table] = {"columns": len(common), "keys": keys}
+    statements.extend(["COMMIT;", "SET FOREIGN_KEY_CHECKS=1;"])
+    mysql("\n".join(statements), SWITCH_CORE, capture=False)
+    atomic_json(REPORT_DIR / "core-merge-report.json", report)
+    return report
+
+
+def protected_fingerprint(db: str, protected_ids: list[int]) -> dict:
+    if not protected_ids:
+        return {}
+    ids = ",".join(str(int(x)) for x in protected_ids)
+    data = {
+        "website": mysql_values(f"SELECT * FROM website WHERE websiteid IN ({ids}) ORDER BY websiteid;", db),
+        "navigation": mysql_values(f"SELECT * FROM website_navigation WHERE websiteid IN ({ids}) ORDER BY navigationid;", db),
+        "article": mysql_values(f"SELECT * FROM article WHERE websiteid IN ({ids}) ORDER BY articleid;", db),
+        "website_manage": mysql_values(f"SELECT * FROM website_manage WHERE websiteid IN ({ids}) ORDER BY wmid;", db),
+        "article_copy": mysql_values(
+            "SELECT ac.* FROM article_copy ac JOIN article a ON a.articleid=ac.articleid "
+            f"WHERE a.websiteid IN ({ids}) ORDER BY ac.article_copyid;", db),
+        "navigation_manage": mysql_values(
+            "SELECT nm.* FROM website_navigation_manage nm JOIN website_navigation n "
+            f"ON n.navigationid=nm.navigationid WHERE n.websiteid IN ({ids}) ORDER BY nm.wncmanageid;", db),
+        "website_statistics": mysql_values(
+            f"SELECT * FROM website_statistics WHERE websiteid IN ({ids}) ORDER BY wtatisticsid;", db),
+    }
+    encoded = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
+    return {"ids": protected_ids, "sha256": hashlib.sha256(encoded).hexdigest(),
+            "row_counts": {k: len(v) for k, v in data.items()}}
+
+
+def build_shadow() -> None:
+    clone_database(TARGET_CORE, SWITCH_CORE)
+    clone_database(TARGET_APPS, SWITCH_APPS)
+    pre = json.loads((REPORT_DIR / "preflight.json").read_text(encoding="utf-8"))
+    atomic_json(PROTECTED_BEFORE, protected_fingerprint(TARGET_APPS, pre["protected_websites"]))
+    build_scope_tables()
+    merge_legacy_into_shadow()
+    merge_core_tables()
+    after = protected_fingerprint(SWITCH_APPS, pre["protected_websites"])
+    atomic_json(REPORT_DIR / "protected-after.json", after)
+    before = json.loads(PROTECTED_BEFORE.read_text(encoding="utf-8"))
+    if before.get("sha256") != after.get("sha256"):
+        raise JobError("HXCS 新建网站数据指纹发生变化,停止")
+
+
+def normalize_path(value: str) -> str | None:
+    value = unquote(value.strip())
+    if not value or value.startswith(("#", "javascript:", "mailto:", "data:")):
+        return None
+    if value.startswith("//"):
+        value = "http:" + value
+    parsed = urlparse(value)
+    if parsed.scheme in ("http", "https"):
+        host = (parsed.hostname or "").lower()
+        if host.endswith("gzhxtc.edu.cn") or host.endswith("gzhxtc.cn"):
+            return parsed.path or "/"
+        return None
+    if parsed.scheme:
+        return None
+    path = parsed.path
+    if not path:
+        return None
+    if not path.startswith("/"):
+        path = "/" + path
+    return path
+
+
+def quote_paths(paths: set[str]) -> list[str]:
+    return sorted(p for p in paths if p and not any(ch in p for ch in "\r\n\x00"))
+
+
+def collect_direct_asset_paths() -> set[str]:
+    sql = f"""
+SELECT DISTINCT value FROM (
+ SELECT content AS value FROM {LEGACY_APPS}.article
+ UNION ALL SELECT edit_content FROM {LEGACY_APPS}.article
+ UNION ALL SELECT thumbnail FROM {LEGACY_APPS}.article
+ UNION ALL SELECT logo FROM {LEGACY_APPS}.website
+ UNION ALL SELECT white_logo_file FROM {LEGACY_APPS}.website
+ UNION ALL SELECT seo_icon FROM {LEGACY_APPS}.website
+ UNION ALL SELECT background_image FROM {LEGACY_APPS}.website_navigation
+ UNION ALL SELECT thumbnail FROM {LEGACY_APPS}.website_template
+ UNION ALL SELECT preview_url FROM {LEGACY_APPS}.website_template
+ UNION ALL SELECT icon_path FROM {LEGACY_APPS}.person
+) x WHERE value IS NOT NULL AND value<>'';
+"""
+    paths = set()
+    for raw in mysql_values(sql):
+        normalized = normalize_path(raw)
+        if normalized and (normalized.startswith("/web/") or normalized.startswith("/main/")):
+            paths.add(normalized)
+    return paths
+
+
+def extract_asset_refs(staging: Path) -> set[str]:
+    paths: set[str] = set()
+    attr = re.compile(r'(?:src|href|data-src|poster|action)\s*=\s*["\']([^"\']+)', re.I)
+    css = re.compile(r'url\(\s*["\']?([^"\')]+)', re.I)
+    for file in staging.rglob("*"):
+        if not file.is_file() or file.suffix.lower() not in {".html", ".htm", ".css"}:
+            continue
+        try:
+            text = file.read_text(encoding="utf-8", errors="ignore")
+        except Exception:
+            continue
+        rel = "/" + file.relative_to(staging).as_posix()
+        base = rel.rsplit("/", 1)[0]
+        for match in list(attr.finditer(text)) + list(css.finditer(text)):
+            value = match.group(1).strip()
+            parsed = urlparse(value)
+            if parsed.scheme in ("http", "https") or value.startswith("//"):
+                normalized = normalize_path(value)
+            elif value.startswith("/"):
+                normalized = normalize_path(value)
+            else:
+                normalized = normalize_path(base + "/" + value)
+            if normalized and (normalized.startswith("/web/") or normalized.startswith("/main/")):
+                paths.add(normalized)
+    return paths
+
+
+def tar_paths_from_source(paths: set[str], extraction_root: Path) -> None:
+    extraction_root.mkdir(parents=True, exist_ok=True)
+    file_list = "\n".join(p.lstrip("/") for p in quote_paths(paths)) + "\n"
+    askpass = RUN_ROOT / ".askpass-prod.sh"
+    askpass_file(askpass, require_env("PROD_SSH_PASS"))
+    remote_cmd = f"tar -C {shlex.quote(SOURCE_APP)} -cf - --ignore-failed-read -T -"
+    ssh_cmd = ["setsid", "-w", "ssh", "-T", "-o", "StrictHostKeyChecking=no",
+               "-o", "ConnectTimeout=15", SOURCE_HOST, remote_cmd]
+    tar_cmd = ["tar", "-xf", "-", "-C", str(extraction_root), "--no-same-owner"]
+    log(f"从旧生产复制 {len(paths)} 个资源路径")
+    source = subprocess.Popen(ssh_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE, env=ssh_env(askpass))
+    extractor = subprocess.Popen(tar_cmd, stdin=source.stdout, stdout=subprocess.PIPE,
+                                 stderr=subprocess.PIPE)
+    assert source.stdin is not None and source.stdout is not None
+    source.stdin.write(file_list.encode())
+    source.stdin.close()
+    source.stdout.close()
+    _, tar_err = extractor.communicate()
+    source_err = source.stderr.read() if source.stderr else b""
+    source_rc = source.wait()
+    if source_rc != 0 or extractor.returncode != 0:
+        raise JobError("资源复制失败\n" + source_err.decode("utf-8", "replace")[-4000:] +
+                       "\n" + tar_err.decode("utf-8", "replace")[-4000:])
+
+
+def mirror_to_web2() -> str:
+    askpass = RUN_ROOT / ".askpass-web2.sh"
+    askpass_file(askpass, require_env("HXCS_WEB2_SSH_PASS"))
+    destination = f"hxxy@10.0.42.5:{RUN_ROOT}/webapp/"
+    command = ["setsid", "-w", "rsync", "-a", "-e",
+               "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=15",
+               str(STAGE_WEBAPP) + "/", destination]
+    env = ssh_env(askpass)
+    env["RSYNC_RSH"] = "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=15"
+    proc = subprocess.run(command, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    if proc.returncode != 0:
+        raise JobError("暂存资源同步到 10.0.42.5 失败:" + proc.stderr.decode("utf-8", "replace")[-4000:])
+    return remote_tree_hash("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"))
+
+
+def remote_tree_hash(host: str, user: str, password: str) -> str:
+    askpass = RUN_ROOT / f".askpass-{host.replace('.', '-')}.sh"
+    askpass_file(askpass, password)
+    script = (f"cd {shlex.quote(str(RUN_ROOT / 'webapp'))} && "
+              "find . -type f -print0 | sort -z | xargs -0 -r sha256sum | sha256sum")
+    cmd = ["setsid", "-w", "ssh", "-T", "-o", "StrictHostKeyChecking=no",
+           "-o", "ConnectTimeout=15", f"{user}@{host}", script]
+    proc = subprocess.run(cmd, env=ssh_env(askpass), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    if proc.returncode != 0:
+        raise JobError(f"{host} 资源哈希失败:" + proc.stderr.decode("utf-8", "replace")[-4000:])
+    return proc.stdout.decode().split()[0]
+
+
+def stage_assets() -> None:
+    STAGE_WEBAPP.mkdir(parents=True, exist_ok=True)
+    direct = collect_direct_asset_paths()
+    direct.add("/main")
+    ASSET_LIST.write_text("\n".join(quote_paths(direct)) + "\n", encoding="utf-8")
+    tar_paths_from_source(direct, STAGE_WEBAPP)
+    derived = extract_asset_refs(STAGE_WEBAPP)
+    missing = sorted(p for p in derived if not (STAGE_WEBAPP / p.lstrip("/")).exists())
+    remaining = {p for p in derived if (STAGE_WEBAPP / p.lstrip("/")).exists() is False}
+    if remaining:
+        tar_paths_from_source(remaining, STAGE_WEBAPP)
+    missing = sorted(p for p in derived if not (STAGE_WEBAPP / p.lstrip("/")).exists())
+    ASSET_MISSING.write_text("\n".join(missing) + "\n", encoding="utf-8")
+    local_hash = subprocess.run(
+        f"cd {shlex.quote(str(STAGE_WEBAPP))} && find . -type f -print0 | sort -z | xargs -0 -r sha256sum | sha256sum",
+        shell=True, check=True, stdout=subprocess.PIPE, text=True).stdout.split()[0]
+    remote_hash = mirror_to_web2()
+    if local_hash != remote_hash:
+        raise JobError(f"双节点资源哈希不一致:{local_hash} / {remote_hash}")
+    atomic_json(REPORT_DIR / "asset-report.json", {
+        "direct_paths": len(direct), "derived_paths": len(derived),
+        "missing": len(missing), "sha256": local_hash,
+    })
+    log(f"资源暂存完成:清单 {len(direct) + len(derived)},缺失 {len(missing)},双节点哈希一致")
+
+
+def verify_database() -> dict:
+    pre = json.loads((REPORT_DIR / "preflight.json").read_text(encoding="utf-8"))
+    protected_ids = pre["protected_websites"]
+    before = json.loads(PROTECTED_BEFORE.read_text(encoding="utf-8"))
+    after = protected_fingerprint(SWITCH_APPS, protected_ids)
+    if after.get("sha256") != before.get("sha256"):
+        raise JobError("保护网站数据在最终复核时发生变化")
+    counts = {}
+    for table in ("website", "website_navigation", "article", "article_copy", "website_manage",
+                  "website_navigation_manage", "website_statistics"):
+        legacy = mysql(f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}`;").strip()
+        shadow = mysql(f"SELECT COUNT(*) FROM `{SWITCH_APPS}`.`{table}`;").strip()
+        counts[table] = {"legacy": int(legacy), "shadow": int(shadow)}
+    source_tables = [t for t in all_base_tables(LEGACY_APPS) if t != "website_visit_log"]
+    mismatches = []
+    for table in source_tables:
+        src_cols = source_columns(LEGACY_APPS, table)
+        dst_cols = set(source_columns(SWITCH_APPS, table))
+        common = [c for c in src_cols if c in dst_cols]
+        keys = primary_columns(LEGACY_APPS, table) or unique_index_columns(LEGACY_APPS, table)
+        if not keys:
+            continue
+        join = " AND ".join(f"d.`{k}`=s.`{k}`" for k in keys)
+        compare = " OR ".join(f"NOT (d.`{c}` <=> s.`{c}`)" for c in common)
+        missing = int(mysql(
+            f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}` s LEFT JOIN `{SWITCH_APPS}`.`{table}` d "
+            f"ON {join} WHERE d.`{keys[0]}` IS NULL;").strip() or "0")
+        different = int(mysql(
+            f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}` s JOIN `{SWITCH_APPS}`.`{table}` d "
+            f"ON {join} WHERE {compare};").strip() or "0")
+        if missing or different:
+            mismatches.append({"table": table, "missing": missing, "different": different})
+    orphan_article_nav = int(mysql(
+        "SELECT COUNT(*) FROM article a LEFT JOIN website_navigation n ON n.navigationid=a.navigationid "
+        "WHERE a.websiteid IN (SELECT id FROM _legacy_scope_website) "
+        "AND (n.navigationid IS NULL OR n.websiteid<>a.websiteid);", SWITCH_APPS).strip())
+    orphan_nav_parent = int(mysql(
+        "SELECT COUNT(*) FROM website_navigation n LEFT JOIN website_navigation p "
+        "ON p.navigationid=n.parent_nid WHERE n.parent_nid IS NOT NULL "
+        "AND (n.websiteid IN (SELECT id FROM _legacy_scope_website) "
+        "OR n.wtid IN (SELECT id FROM _legacy_scope_template)) "
+        "AND p.navigationid IS NULL;", SWITCH_APPS).strip())
+    result = {"table_counts": counts, "mismatches": mismatches,
+              "orphan_article_nav": orphan_article_nav, "orphan_nav_parent": orphan_nav_parent,
+              "protected": after}
+    atomic_json(VERIFY_REPORT, result)
+    if mismatches or orphan_article_nav or orphan_nav_parent:
+        raise JobError("数据库复核失败,详见 verify-report.json")
+    return result
+
+
+def prepare_verify_webapp() -> None:
+    live = Path("/home/hxxy/zq/apps/internal/webapp")
+    if not live.is_dir():
+        raise JobError("找不到 hxcs 内网 webapp")
+    if VERIFY_WEBAPP.exists():
+        shutil.rmtree(VERIFY_WEBAPP)
+    log("复制临时验证 webapp")
+    subprocess.run(["cp", "-a", str(live), str(VERIFY_WEBAPP)], check=True)
+    subprocess.run(["cp", "-a", str(STAGE_WEBAPP) + "/.", str(VERIFY_WEBAPP)], check=True)
+    replacements = {
+        "WEB-INF/config/druid/base.jdbc.properties": TARGET_CORE,
+        "WEB-INF/config/druid/apps.jdbc.properties": TARGET_APPS,
+        "WEB-INF/config/app/bpm/cfg/jbpm.hibernate.cfg.xml": TARGET_APPS,
+    }
+    for rel, old in replacements.items():
+        file = VERIFY_WEBAPP / rel
+        if not file.is_file():
+            raise JobError(f"验证 webapp 缺少配置:{rel}")
+        text = file.read_text(encoding="utf-8")
+        target = SWITCH_CORE if old == TARGET_CORE else SWITCH_APPS
+        file.write_text(text.replace(old, target), encoding="utf-8")
+
+
+def run_verify_tomcat(pre: dict) -> list[dict]:
+    prepare_verify_webapp()
+    subprocess.run(["docker", "rm", "-f", VERIFY_CONTAINER], stdout=subprocess.DEVNULL,
+                   stderr=subprocess.DEVNULL)
+    command = ["docker", "run", "-d", "--name", VERIFY_CONTAINER, "--network", "internal_default",
+               "-p", f"127.0.0.1:{VERIFY_PORT}:8080",
+               "-v", f"{VERIFY_WEBAPP}:/usr/local/tomcat/webapps/ROOT:ro", "tomcat:8.5-jdk8"]
+    subprocess.run(command, check=True, stdout=subprocess.PIPE)
+    deadline = time.time() + 180
+    while time.time() < deadline:
+        probe = subprocess.run(["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}",
+                                f"http://127.0.0.1:{VERIFY_PORT}/"], stdout=subprocess.PIPE, text=True)
+        if probe.stdout.strip() not in ("000", ""):
+            break
+        time.sleep(3)
+    results = []
+    for site in pre["source_websites_data"]:
+        if site["dcode"] != 61:
+            continue
+        host = next((x.strip() for x in site["domains"].split(";") if x.strip()), "")
+        if not host:
+            results.append({"websiteid": site["websiteid"], "host": "", "status": "no_domain"})
+            continue
+        urls = ["/"]
+        for url in mysql_values(
+                f"SELECT url FROM `{LEGACY_APPS}`.article WHERE websiteid={site['websiteid']} "
+                "AND dcode=61 ORDER BY release_time DESC LIMIT 8;"):
+            path = normalize_path(url)
+            if path:
+                urls.append(path)
+        site_ok = True
+        statuses = []
+        for path in urls:
+            target = f"http://127.0.0.1:{VERIFY_PORT}{path}"
+            proc = subprocess.run(["curl", "-sS", "--max-time", "30", "-o", "/dev/null",
+                                   "-w", "%{http_code}", "-H", f"Host: {host}", target],
+                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+            code = proc.stdout.strip()
+            statuses.append({"path": path, "status": code})
+            if code not in {"200", "301", "302"}:
+                site_ok = False
+        results.append({"websiteid": site["websiteid"], "host": host, "ok": site_ok, "checks": statuses})
+    atomic_json(REPORT_DIR / "http-verify.json", results)
+    if any(not r.get("ok", False) for r in results):
+        raise JobError("临时 Tomcat HTTP 验证失败,详见 http-verify.json")
+    subprocess.run(["docker", "rm", "-f", VERIFY_CONTAINER], stdout=subprocess.DEVNULL,
+                   stderr=subprocess.DEVNULL)
+    return results
+
+
+def verify() -> None:
+    database = verify_database()
+    pre = json.loads((REPORT_DIR / "preflight.json").read_text(encoding="utf-8"))
+    http_results = run_verify_tomcat(pre)
+    atomic_json(REPORT_DIR / "final-report.json", {
+        "status": "ok", "database": database, "http": http_results,
+        "runtime_changed": False, "domain_or_dns_changed": False,
+    })
+
+
+def cleanup_sensitive_files() -> None:
+    for pattern in (".askpass-*.sh", ".runtime.env"):
+        for path in RUN_ROOT.glob(pattern):
+            try:
+                path.unlink()
+            except FileNotFoundError:
+                pass
+
+
+def run_mode(mode: str) -> None:
+    RUN_ROOT.mkdir(parents=True, exist_ok=True)
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    TOOLS_DIR.mkdir(parents=True, exist_ok=True)
+    os.chmod(RUN_ROOT, 0o700)
+    update_status(state="running", mode=mode, stage="starting", started_at=now())
+    try:
+        if mode == "preflight":
+            preflight()
+        elif mode == "snapshot":
+            snapshot()
+        elif mode == "build-shadow":
+            build_shadow()
+        elif mode == "stage-assets":
+            stage_assets()
+        elif mode == "verify":
+            verify()
+        elif mode == "all":
+            update_status(stage="preflight")
+            pre = preflight()
+            update_status(stage="snapshot", source_websites=pre["source_websites"])
+            snapshot()
+            update_status(stage="build-shadow")
+            build_shadow()
+            update_status(stage="stage-assets")
+            stage_assets()
+            update_status(stage="verify")
+            verify()
+            update_status(stage="complete", state="complete", finished_at=now())
+        elif mode == "refresh-delta":
+            raise JobError("refresh-delta 需要在正式切换前的停写窗口另行授权后实现/执行")
+        else:
+            raise JobError(f"未知模式:{mode}")
+        if mode != "all":
+            update_status(state="complete", stage=mode, finished_at=now())
+    except Exception as exc:
+        log("任务失败:" + str(exc))
+        with LOG_FILE.open("a", encoding="utf-8") as fh:
+            fh.write(traceback.format_exc() + "\n")
+        update_status(state="failed", stage="failed", error=str(exc), finished_at=now())
+        raise
+
+
+def main() -> int:
+    load_env_file()
+    mode = sys.argv[1] if len(sys.argv) > 1 else "status"
+    RUN_ROOT.mkdir(parents=True, exist_ok=True)
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    if mode == "status":
+        print(STATUS_FILE.read_text(encoding="utf-8") if STATUS_FILE.is_file() else "not_started")
+        return 0
+    LOCK_FILE.touch(exist_ok=True)
+    with LOCK_FILE.open("r+") as lock:
+        try:
+            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+        except BlockingIOError:
+            print("another legacy-sites job is already running", file=sys.stderr)
+            return 3
+        try:
+            run_mode(mode)
+            return 0
+        finally:
+            cleanup_sensitive_files()
+
+
+if __name__ == "__main__":
+    try:
+        raise SystemExit(main())
+    except JobError as exc:
+        print(str(exc), file=sys.stderr)
+        raise SystemExit(1)

+ 183 - 0
local-run/bin/legacy-sites-to-hxcs.sh

@@ -0,0 +1,183 @@
+#!/usr/bin/env bash
+# 旧生产全站复制到 HXCS 影子环境的控制入口。
+# 实际任务在 10.0.42.6 上运行;本机只负责一次性部署和启动。
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
+HXCS_HOST="${HXCS_HOST:-10.0.42.6}"
+HXCS_USER="${HXCS_USER:-hxxy}"
+RUN_ROOT="${LEGACY_RUN_ROOT:-/home/hxxy/zq/staging/legacy-sites-20261103}"
+TOOLS_DIR="${RUN_ROOT}/tools"
+REPORT_DIR="${RUN_ROOT}/reports"
+LOG_FILE="${REPORT_DIR}/job.log"
+STATUS_FILE="${RUN_ROOT}/status.json"
+REMOTE_ENV="${RUN_ROOT}/.runtime.env"
+REMOTE_PID="${RUN_ROOT}/run.pid"
+LOCAL_JOB="${SCRIPT_DIR}/legacy-sites-job.py"
+HXCS_PRIVATE_DOC="${HXCS_PRIVATE_ACCESS_DOC:-${PROJECT_ROOT}/hxcs试运行环境访问资料-本地私密.md}"
+PROD_PRIVATE_DOC="${PROD_PRIVATE_ACCESS_DOC:-${PROJECT_ROOT}/docs/华夏迁移交接资料/服务器与数据库信息.md}"
+MODE="${1:-status}"
+
+die() { printf '失败:%s\n' "$*" >&2; exit 1; }
+usage() {
+	cat <<'EOF'
+用法:legacy-sites-to-hxcs.sh <preflight|snapshot|build-shadow|stage-assets|verify|run-detached|status|wait|refresh-delta>
+  run-detached  在 10.0.42.6 脱离 SSH 会话执行完整复制流程
+  status        查看后台任务状态和最后日志
+  wait         等待后台任务结束(本机 VPN 中断不影响任务)
+EOF
+}
+
+[[ -x /opt/homebrew/bin/sshpass ]] || die "缺少本机 sshpass"
+[[ -r "${HXCS_PRIVATE_DOC}" ]] || die "缺少 HXCS 私密资料:${HXCS_PRIVATE_DOC}"
+[[ -r "${PROD_PRIVATE_DOC}" ]] || die "缺少旧生产访问资料:${PROD_PRIVATE_DOC}"
+[[ -r "${LOCAL_JOB}" ]] || die "缺少迁移程序:${LOCAL_JOB}"
+
+source "${SCRIPT_DIR}/hxcs-private-config.sh"
+hxcs_load_private_config "${PROJECT_ROOT}" || die "读取 HXCS 私密配置失败"
+HXCS_SSH_PASS_WEB="${HXCS_SSH_PASS_WEB:?缺少 10.0.42.6 SSH 密码}"
+HXCS_SSH_PASS_WEB2="${HXCS_SSH_PASS_WEB2:?缺少 10.0.42.5 SSH 密码}"
+HXCS_MYSQL_PASS="${HXCS_MYSQL_PASS:?缺少 HXCS MySQL 密码}"
+
+PROD_SSH_PASS="$(awk -F'|' '
+	/职院站群内门户/ { value=$5; gsub(/^[[:space:]]+|[[:space:]]+$/, "", value); gsub(/`/, "", value); print value; exit }
+' "${PROD_PRIVATE_DOC}")"
+[[ -n "${PROD_SSH_PASS}" ]] || die "未从旧生产资料读取内门户密码"
+
+SSH=(/opt/homebrew/bin/sshpass -p "${HXCS_SSH_PASS_WEB}" ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=12 "${HXCS_USER}@${HXCS_HOST}")
+SCP=(/opt/homebrew/bin/sshpass -p "${HXCS_SSH_PASS_WEB}" scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=12)
+
+remote() { "${SSH[@]}" "$@"; }
+
+show_status() {
+	remote "printf '%s\n' '--- status.json ---'; cat '${STATUS_FILE}' 2>/dev/null || echo not_started; printf '%s\n' '--- log tail ---'; tail -n 60 '${LOG_FILE}' 2>/dev/null || true"
+}
+
+deploy_tools() {
+	remote "mkdir -p '${TOOLS_DIR}' '${REPORT_DIR}' && chmod 700 '${RUN_ROOT}' '${TOOLS_DIR}' '${REPORT_DIR}'"
+	"${SCP[@]}" "${LOCAL_JOB}" "${HXCS_USER}@${HXCS_HOST}:${TOOLS_DIR}/legacy-sites-job.py"
+	remote "chmod 700 '${TOOLS_DIR}/legacy-sites-job.py'; sha256sum '${TOOLS_DIR}/legacy-sites-job.py'"
+	printf '本地提交:%s\n' "$(git -C "${PROJECT_ROOT}" rev-parse HEAD 2>/dev/null || echo unknown)"
+	printf '本地 SHA-256:'
+	shasum -a 256 "${LOCAL_JOB}" | awk '{print $1}'
+}
+
+write_remote_env() {
+	local temp
+	temp="$(mktemp /private/tmp/legacy-sites-env.XXXXXX)"
+	chmod 600 "${temp}"
+	HXCS_MYSQL_PASS="${HXCS_MYSQL_PASS}" \
+	PROD_SSH_PASS="${PROD_SSH_PASS}" \
+	PROD_MYSQL_PASS="${PROD_SSH_PASS}" \
+	HXCS_WEB2_SSH_PASS="${HXCS_SSH_PASS_WEB2}" \
+	python3 - "${temp}" <<'PY'
+import os, shlex, sys
+keys = ("HXCS_MYSQL_PASS", "PROD_SSH_PASS", "PROD_MYSQL_PASS", "HXCS_WEB2_SSH_PASS")
+with open(sys.argv[1], "w", encoding="utf-8") as fh:
+    for key in keys:
+        fh.write(f"{key}={shlex.quote(os.environ[key])}\n")
+PY
+	"${SCP[@]}" "${temp}" "${HXCS_USER}@${HXCS_HOST}:${REMOTE_ENV}"
+	rm -f "${temp}"
+	remote "chmod 600 '${REMOTE_ENV}'"
+}
+
+run_sync_mode() {
+	write_remote_env
+	remote "bash -s" <<EOF
+set -euo pipefail
+cd '${TOOLS_DIR}'
+set -a
+. '${REMOTE_ENV}'
+set +a
+export LEGACY_RUN_ROOT='${RUN_ROOT}'
+export LEGACY_ENV_FILE='${REMOTE_ENV}'
+set +e
+python3 '${TOOLS_DIR}/legacy-sites-job.py' '${MODE}'
+rc=\$?
+set -e
+rm -f '${REMOTE_ENV}'
+exit \$rc
+EOF
+}
+
+start_detached() {
+	write_remote_env
+	remote "bash -s" <<EOF
+set -euo pipefail
+mkdir -p '${REPORT_DIR}'
+if [[ -f '${REMOTE_PID}' ]] && kill -0 "\$(cat '${REMOTE_PID}')" 2>/dev/null; then
+  echo '已有迁移任务正在运行'
+  cat '${REMOTE_PID}'
+  exit 0
+fi
+rm -f '${STATUS_FILE}' '${REMOTE_PID}'
+set -a
+. '${REMOTE_ENV}'
+set +a
+export LEGACY_RUN_ROOT='${RUN_ROOT}'
+export LEGACY_ENV_FILE='${REMOTE_ENV}'
+cd '${TOOLS_DIR}'
+setsid python3 '${TOOLS_DIR}/legacy-sites-job.py' all >> '${LOG_FILE}' 2>&1 < /dev/null &
+pid=\$!
+echo "\$pid" > '${REMOTE_PID}'
+sleep 3
+if ! kill -0 "\$pid" 2>/dev/null; then
+  echo '后台任务启动失败'
+  tail -n 80 '${LOG_FILE}' 2>/dev/null || true
+  exit 1
+fi
+echo '后台任务已启动'
+echo "pid=\$pid"
+cat '${STATUS_FILE}' 2>/dev/null || true
+EOF
+	show_status
+}
+
+wait_for_job() {
+	local timeout="${LEGACY_WAIT_SECONDS:-0}"
+	local started
+	started="$(date +%s)"
+	while true; do
+		local state
+		state="$(remote "python3 -c 'import json; print(json.load(open(\"${STATUS_FILE}\"))[\"state\"])' 2>/dev/null" || true)"
+		show_status
+		case "${state}" in
+			complete) return 0 ;;
+			failed) return 1 ;;
+		esac
+		if [[ "${timeout}" -gt 0 ]] && (( $(date +%s) - started >= timeout )); then
+			printf '等待超时,后台任务继续运行。\n' >&2
+			return 2
+		fi
+		sleep "${LEGACY_POLL_SECONDS:-30}"
+	done
+}
+
+case "${MODE}" in
+	preflight|snapshot|build-shadow|stage-assets|verify)
+		deploy_tools
+		run_sync_mode
+		;;
+	run-detached)
+		deploy_tools
+		start_detached
+		;;
+	status)
+		show_status
+		;;
+	wait)
+		wait_for_job
+		;;
+	refresh-delta)
+		die "refresh-delta 需要正式切换前的停写窗口并再次授权,本次不执行"
+		;;
+	help|-h|--help)
+		usage
+		;;
+	*)
+		usage
+		die "未知模式:${MODE}"
+		;;
+esac