|
|
@@ -53,6 +53,9 @@ 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"
|
|
|
+BASELINE_CORE = "sp_gzhx_core_baseline_20261103"
|
|
|
+BASELINE_APPS = "sp_gzhx_apps_baseline_20261103"
|
|
|
+CUTOVER_BACKUP = RUN_ROOT / "rollback-configs"
|
|
|
VERIFY_CONTAINER = "zq-tomcat-legacy-verify"
|
|
|
VERIFY_PORT = 18080
|
|
|
PROTECTED_BEFORE = REPORT_DIR / "protected-before.json"
|
|
|
@@ -603,6 +606,300 @@ def build_shadow(*, replace: bool = False) -> None:
|
|
|
raise JobError("HXCS 新建网站数据指纹发生变化,停止")
|
|
|
|
|
|
|
|
|
+def source_global_value(name: str) -> str:
|
|
|
+ rows = source_mysql_query(f"SELECT @@GLOBAL.{name};")
|
|
|
+ return rows[0].strip() if rows else ""
|
|
|
+
|
|
|
+
|
|
|
+def source_set_read_only(enabled: bool) -> None:
|
|
|
+ value = "ON" if enabled else "OFF"
|
|
|
+ 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 -N -B -e "SET GLOBAL read_only={value}; SELECT @@GLOBAL.read_only;"
|
|
|
+"""
|
|
|
+ source_ssh(script)
|
|
|
+ log(f"旧生产 MySQL read_only={value}")
|
|
|
+
|
|
|
+
|
|
|
+def changed_ids(table: str, pk: str) -> list[int]:
|
|
|
+ new_cols = source_columns(LEGACY_APPS, table)
|
|
|
+ old_cols = set(source_columns(BASELINE_APPS, table))
|
|
|
+ common = [c for c in new_cols if c in old_cols]
|
|
|
+ diff = " OR ".join(f"NOT (n.`{c}` <=> o.`{c}`)" for c in common)
|
|
|
+ sql = (f"SELECT n.`{pk}` FROM `{LEGACY_APPS}`.`{table}` n LEFT JOIN `{BASELINE_APPS}`.`{table}` o "
|
|
|
+ f"ON o.`{pk}`=n.`{pk}` WHERE o.`{pk}` IS NULL OR {diff};")
|
|
|
+ return [int(x) for x in mysql_values(sql)]
|
|
|
+
|
|
|
+
|
|
|
+def extract_asset_refs_from_paths(paths: set[str], staging: Path) -> set[str]:
|
|
|
+ refs: 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 raw in paths:
|
|
|
+ file = staging / raw.lstrip("/")
|
|
|
+ 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
|
|
|
+ base = "/" + file.relative_to(staging).as_posix()
|
|
|
+ base = base.rsplit("/", 1)[0]
|
|
|
+ for match in list(attr.finditer(text)) + list(css.finditer(text)):
|
|
|
+ value = match.group(1).strip()
|
|
|
+ lowered = value.lower()
|
|
|
+ if (lowered.startswith(("mailto:", "tel:", "javascript:", "data:", "file:", "qq:", "#"))
|
|
|
+ or """ in lowered or "data:image" in lowered):
|
|
|
+ continue
|
|
|
+ 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/")):
|
|
|
+ refs.add(normalized)
|
|
|
+ return refs
|
|
|
+
|
|
|
+
|
|
|
+def sync_selected_paths_to_web2(paths: set[str]) -> dict:
|
|
|
+ paths = {p for p in paths if staged_path_exists(p)}
|
|
|
+ if not paths:
|
|
|
+ return {"count": 0, "sha256": []}
|
|
|
+ password = require_env("HXCS_WEB2_SSH_PASS")
|
|
|
+ remote_ssh_command("10.0.42.5", "hxxy", password,
|
|
|
+ f"mkdir -p {shlex.quote(str(RUN_ROOT / 'webapp'))}\n")
|
|
|
+ askpass = RUN_ROOT / ".askpass-web2.sh"
|
|
|
+ askpass_file(askpass, password)
|
|
|
+ payload = b"\0".join(p.lstrip("/").encode() for p in sorted(paths)) + b"\0"
|
|
|
+ command = ["setsid", "-w", "rsync", "-a", "--from0", "--files-from=-", "-e",
|
|
|
+ "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=15",
|
|
|
+ str(STAGE_WEBAPP) + "/", f"hxxy@10.0.42.5:{RUN_ROOT}/webapp/"]
|
|
|
+ proc = subprocess.run(command, input=payload, env=ssh_env(askpass),
|
|
|
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
|
+ if proc.returncode != 0:
|
|
|
+ raise JobError("增量资源同步失败:" + proc.stderr.decode("utf-8", "replace")[-4000:])
|
|
|
+ local = []
|
|
|
+ for rel in sorted(paths):
|
|
|
+ file = STAGE_WEBAPP / rel.lstrip("/")
|
|
|
+ if file.is_file():
|
|
|
+ local.append((rel.lstrip("/"), hashlib.sha256(file.read_bytes()).hexdigest()))
|
|
|
+ quoted = " ".join(shlex.quote(rel) for rel, _ in local)
|
|
|
+ remote_script = f"cd {shlex.quote(str(RUN_ROOT / 'webapp'))} && sha256sum -- {quoted}\n"
|
|
|
+ remote_out = remote_ssh_command("10.0.42.5", "hxxy", password, remote_script)
|
|
|
+ remote = {}
|
|
|
+ for line in remote_out.splitlines():
|
|
|
+ if " " in line:
|
|
|
+ sha, rel = line.split(" ", 1)
|
|
|
+ remote[rel] = sha
|
|
|
+ for rel, sha in local:
|
|
|
+ if remote.get(rel) != sha:
|
|
|
+ raise JobError(f"增量资源双节点哈希不一致:{rel}")
|
|
|
+ return {"count": len(local), "password_hidden": True}
|
|
|
+
|
|
|
+
|
|
|
+def refresh_source_snapshot_and_assets() -> dict:
|
|
|
+ clone_database(LEGACY_CORE, BASELINE_CORE, replace=True)
|
|
|
+ clone_database(LEGACY_APPS, BASELINE_APPS, replace=True)
|
|
|
+ drop_database(LEGACY_CORE)
|
|
|
+ drop_database(LEGACY_APPS)
|
|
|
+ source_dump_to_database(SOURCE_CORE, LEGACY_CORE)
|
|
|
+ source_dump_to_database(SOURCE_APPS, LEGACY_APPS,
|
|
|
+ ignore_table=f"{SOURCE_APPS}.website_visit_log")
|
|
|
+ changed = {
|
|
|
+ "website": changed_ids("website", "websiteid"),
|
|
|
+ "website_navigation": changed_ids("website_navigation", "navigationid"),
|
|
|
+ "website_template": changed_ids("website_template", "wtid"),
|
|
|
+ "article": changed_ids("article", "articleid"),
|
|
|
+ }
|
|
|
+ paths: set[str] = set()
|
|
|
+ for table, field_list in (
|
|
|
+ ("article", ("content", "edit_content", "thumbnail")),
|
|
|
+ ("website_navigation", ("background_image",)),
|
|
|
+ ("website", ("logo", "white_logo_file", "seo_icon")),
|
|
|
+ ("website_template", ("thumbnail", "preview_url")),
|
|
|
+ ):
|
|
|
+ ids = changed[table]
|
|
|
+ if not ids:
|
|
|
+ continue
|
|
|
+ id_col = {"article": "articleid", "website_navigation": "navigationid",
|
|
|
+ "website": "websiteid", "website_template": "wtid"}[table]
|
|
|
+ id_sql = ",".join(str(x) for x in ids)
|
|
|
+ for col in field_list:
|
|
|
+ for raw in mysql_values(f"SELECT `{col}` FROM `{LEGACY_APPS}`.`{table}` WHERE `{id_col}` IN ({id_sql});"):
|
|
|
+ normalized = normalize_path(raw)
|
|
|
+ if normalized and normalized.startswith(("/web/", "/main/")):
|
|
|
+ paths.add(normalized)
|
|
|
+ tar_paths_from_source(paths, STAGE_WEBAPP)
|
|
|
+ refs = extract_asset_refs_from_paths(paths, STAGE_WEBAPP)
|
|
|
+ refs = {p for p in refs if not staged_path_exists(p)}
|
|
|
+ if refs:
|
|
|
+ tar_paths_from_source(refs, STAGE_WEBAPP)
|
|
|
+ changed_paths = {p for p in paths | refs if staged_path_exists(p)}
|
|
|
+ sync_selected_paths_to_web2(changed_paths)
|
|
|
+ result = {"changed_rows": {k: len(v) for k, v in changed.items()},
|
|
|
+ "changed_paths": len(changed_paths)}
|
|
|
+ atomic_json(REPORT_DIR / "delta-assets.json", result)
|
|
|
+ log(f"最终增量:文章 {len(changed['article'])},栏目 {len(changed['website_navigation'])},"
|
|
|
+ f"网站 {len(changed['website'])},模板 {len(changed['website_template'])},"
|
|
|
+ f"资源 {len(changed_paths)}")
|
|
|
+ return result
|
|
|
+
|
|
|
+
|
|
|
+def docker_running(name: str) -> bool:
|
|
|
+ proc = subprocess.run(["docker", "inspect", "-f", "{{.State.Running}}", name],
|
|
|
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
|
|
+ return proc.returncode == 0 and proc.stdout.strip() == "true"
|
|
|
+
|
|
|
+
|
|
|
+def remote_docker_running(name: str) -> bool:
|
|
|
+ out = remote_ssh_command("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"),
|
|
|
+ f"docker inspect -f '{{{{.State.Running}}}}' {shlex.quote(name)}\n")
|
|
|
+ return out.strip() == "true"
|
|
|
+
|
|
|
+
|
|
|
+def stop_hxcs_tomcats() -> dict:
|
|
|
+ state = {"internal": docker_running("zq-tomcat-internal"),
|
|
|
+ "external": remote_docker_running("zq-tomcat-external")}
|
|
|
+ if state["internal"]:
|
|
|
+ subprocess.run(["docker", "stop", "zq-tomcat-internal"], check=True, stdout=subprocess.DEVNULL)
|
|
|
+ if state["external"]:
|
|
|
+ remote_ssh_command("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"),
|
|
|
+ "docker stop zq-tomcat-external\n")
|
|
|
+ log("HXCS 双 Tomcat 已暂停写入")
|
|
|
+ return state
|
|
|
+
|
|
|
+
|
|
|
+def start_hxcs_tomcats() -> None:
|
|
|
+ if docker_running("zq-tomcat-internal"):
|
|
|
+ subprocess.run(["docker", "restart", "zq-tomcat-internal"], check=True, stdout=subprocess.DEVNULL)
|
|
|
+ else:
|
|
|
+ subprocess.run(["docker", "start", "zq-tomcat-internal"], check=True, stdout=subprocess.DEVNULL)
|
|
|
+ remote_ssh_command("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"),
|
|
|
+ "docker restart zq-tomcat-external\n")
|
|
|
+ log("HXCS 双 Tomcat 已恢复")
|
|
|
+
|
|
|
+
|
|
|
+def switch_hxcs_jdbc() -> Path:
|
|
|
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
|
+ backup = CUTOVER_BACKUP / stamp
|
|
|
+ backup.mkdir(parents=True, exist_ok=True)
|
|
|
+ internal = Path("/home/hxxy/zq/apps/internal/webapp")
|
|
|
+ external = "/home/hxxy/zq/apps/external/webapp"
|
|
|
+ rels = [
|
|
|
+ "WEB-INF/config/druid/base.jdbc.properties",
|
|
|
+ "WEB-INF/config/druid/apps.jdbc.properties",
|
|
|
+ "WEB-INF/config/app/bpm/cfg/jbpm.hibernate.cfg.xml",
|
|
|
+ ]
|
|
|
+ internal_backup = backup / "internal"
|
|
|
+ for rel in rels:
|
|
|
+ target = backup / "internal" / rel
|
|
|
+ target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ shutil.copy2(internal / rel, target)
|
|
|
+ file = internal / rel
|
|
|
+ text = file.read_text(encoding="utf-8").replace(TARGET_CORE, SWITCH_CORE).replace(TARGET_APPS, SWITCH_APPS)
|
|
|
+ file.write_text(text, encoding="utf-8")
|
|
|
+ remote_script = [f"set -e; mkdir -p {shlex.quote(str(backup / 'external'))}"]
|
|
|
+ for rel in rels:
|
|
|
+ remote_script.append(f"mkdir -p {shlex.quote(str(backup / 'external' / rel.rsplit('/', 1)[0]))}")
|
|
|
+ remote_script.append(f"cp -a {shlex.quote(external + '/' + rel)} {shlex.quote(str(backup / 'external' / rel))}")
|
|
|
+ remote_script.append(
|
|
|
+ f"sed -i 's/{TARGET_CORE}/{SWITCH_CORE}/g; s/{TARGET_APPS}/{SWITCH_APPS}/g' "
|
|
|
+ f"{shlex.quote(external + '/' + rel)}")
|
|
|
+ remote_ssh_command("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"),
|
|
|
+ "\n".join(remote_script) + "\n")
|
|
|
+ log(f"HXCS JDBC 已切到影子库,配置备份:{backup}")
|
|
|
+ return backup
|
|
|
+
|
|
|
+
|
|
|
+def restore_hxcs_jdbc(backup: Path) -> None:
|
|
|
+ internal = Path("/home/hxxy/zq/apps/internal/webapp")
|
|
|
+ external = "/home/hxxy/zq/apps/external/webapp"
|
|
|
+ rels = ["WEB-INF/config/druid/base.jdbc.properties",
|
|
|
+ "WEB-INF/config/druid/apps.jdbc.properties",
|
|
|
+ "WEB-INF/config/app/bpm/cfg/jbpm.hibernate.cfg.xml"]
|
|
|
+ for rel in rels:
|
|
|
+ shutil.copy2(backup / "internal" / rel, internal / rel)
|
|
|
+ lines = ["set -e"]
|
|
|
+ for rel in rels:
|
|
|
+ lines.append(f"cp -a {shlex.quote(str(backup / 'external' / rel))} {shlex.quote(external + '/' + rel)}")
|
|
|
+ remote_ssh_command("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"),
|
|
|
+ "\n".join(lines) + "\n")
|
|
|
+ log("已恢复 HXCS 原 JDBC 配置")
|
|
|
+
|
|
|
+
|
|
|
+def verify_hxcs_runtime() -> list[dict]:
|
|
|
+ results = []
|
|
|
+ hosts = ["hxcs.feifan.net", "xinwen.hxcs.feifan.net",
|
|
|
+ "ffkj-xingong-2026.hxcs.feifan.net", "ffkj-dept-red.hxcs.feifan.net"]
|
|
|
+ for host in hosts:
|
|
|
+ ok = False
|
|
|
+ code = "000"
|
|
|
+ for _ in range(30):
|
|
|
+ proc = subprocess.run(["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}",
|
|
|
+ "-H", f"Host: {host}", "http://127.0.0.1/"],
|
|
|
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
|
|
+ code = proc.stdout.strip()
|
|
|
+ if code in {"200", "301", "302"}:
|
|
|
+ ok = True
|
|
|
+ break
|
|
|
+ time.sleep(2)
|
|
|
+ results.append({"host": host, "status": code, "ok": ok})
|
|
|
+ workbench = subprocess.run(["curl", "-k", "-sS", "-o", "/dev/null", "-w", "%{http_code}",
|
|
|
+ "https://hxcs.feifan.net/apps/workbench/"],
|
|
|
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout.strip()
|
|
|
+ results.append({"host": "hxcs.feifan.net/apps/workbench/", "status": workbench,
|
|
|
+ "ok": workbench in {"200", "302"}})
|
|
|
+ atomic_json(REPORT_DIR / "runtime-verify.json", results)
|
|
|
+ if any(not x["ok"] for x in results):
|
|
|
+ raise JobError("HXCS 切库后运行验收失败,详见 runtime-verify.json")
|
|
|
+ return results
|
|
|
+
|
|
|
+
|
|
|
+def final_cutover() -> None:
|
|
|
+ previous_read_only = source_global_value("read_only").lower() in {"1", "on", "true"}
|
|
|
+ tomcat_state = {"internal": False, "external": False}
|
|
|
+ switched = False
|
|
|
+ backup: Path | None = None
|
|
|
+ try:
|
|
|
+ if not previous_read_only:
|
|
|
+ source_set_read_only(True)
|
|
|
+ tomcat_state = stop_hxcs_tomcats()
|
|
|
+ update_status(stage="delta-refresh")
|
|
|
+ delta = refresh_source_snapshot_and_assets()
|
|
|
+ update_status(stage="rebuild-shadow")
|
|
|
+ build_shadow(replace=True)
|
|
|
+ update_status(stage="verify-shadow")
|
|
|
+ verify()
|
|
|
+ update_status(stage="switch-jdbc")
|
|
|
+ backup = switch_hxcs_jdbc()
|
|
|
+ switched = True
|
|
|
+ start_hxcs_tomcats()
|
|
|
+ runtime = verify_hxcs_runtime()
|
|
|
+ atomic_json(REPORT_DIR / "cutover-report.json", {
|
|
|
+ "status": "complete", "delta": delta, "runtime": runtime,
|
|
|
+ "dns_changed": False, "old_prod_kept_running": True,
|
|
|
+ })
|
|
|
+ update_status(stage="complete", state="complete", finished_at=now())
|
|
|
+ except Exception:
|
|
|
+ if switched and backup is not None:
|
|
|
+ try:
|
|
|
+ if docker_running("zq-tomcat-internal"):
|
|
|
+ subprocess.run(["docker", "stop", "zq-tomcat-internal"], check=False, stdout=subprocess.DEVNULL)
|
|
|
+ remote_ssh_command("10.0.42.5", "hxxy", require_env("HXCS_WEB2_SSH_PASS"),
|
|
|
+ "docker stop zq-tomcat-external\n")
|
|
|
+ restore_hxcs_jdbc(backup)
|
|
|
+ finally:
|
|
|
+ start_hxcs_tomcats()
|
|
|
+ else:
|
|
|
+ start_hxcs_tomcats()
|
|
|
+ raise
|
|
|
+ finally:
|
|
|
+ if not previous_read_only:
|
|
|
+ source_set_read_only(False)
|
|
|
+
|
|
|
+
|
|
|
def merge_shadow_existing() -> None:
|
|
|
pre = json.loads((REPORT_DIR / "preflight.json").read_text(encoding="utf-8"))
|
|
|
if not database_exists(SWITCH_CORE) or not database_exists(SWITCH_APPS):
|
|
|
@@ -682,7 +979,9 @@ def extract_asset_refs(staging: Path) -> set[str]:
|
|
|
base = rel.rsplit("/", 1)[0]
|
|
|
for match in list(attr.finditer(text)) + list(css.finditer(text)):
|
|
|
value = match.group(1).strip()
|
|
|
- if value.lower().startswith(("mailto:", "tel:", "javascript:", "data:", "#")):
|
|
|
+ lowered = value.lower()
|
|
|
+ if (lowered.startswith(("mailto:", "tel:", "javascript:", "data:", "file:", "qq:", "#"))
|
|
|
+ or """ in lowered or "data:image" in lowered):
|
|
|
continue
|
|
|
parsed = urlparse(value)
|
|
|
if parsed.scheme in ("http", "https") or value.startswith("//"):
|
|
|
@@ -1100,11 +1399,13 @@ def run_mode(mode: str) -> None:
|
|
|
update_status(stage="verify")
|
|
|
verify()
|
|
|
update_status(stage="complete", state="complete", finished_at=now())
|
|
|
+ elif mode == "final-cutover":
|
|
|
+ final_cutover()
|
|
|
elif mode == "refresh-delta":
|
|
|
raise JobError("refresh-delta 需要在正式切换前的停写窗口另行授权后实现/执行")
|
|
|
else:
|
|
|
raise JobError(f"未知模式:{mode}")
|
|
|
- if mode not in {"all", "resume", "continue-merge", "continue-assets", "continue-mirror", "stage-code"}:
|
|
|
+ if mode not in {"all", "resume", "continue-merge", "continue-assets", "continue-mirror", "stage-code", "final-cutover"}:
|
|
|
update_status(state="complete", stage=mode, finished_at=now())
|
|
|
except Exception as exc:
|
|
|
log("任务失败:" + str(exc))
|