sh2/d2ypp2/tools/deploy_full_stream.py
2026-06-14 05:50:22 -05:00

197 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""Stream full deploy output and post-configure ShellCrash/Neko for proxycheap."""
from __future__ import annotations
import os
import select
import shlex
import sys
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools"))
import deploy_full_paramiko as deploy # noqa: E402
CONFIG_YAML = ROOT.parent / "config.yaml"
REMOTE_PATH = os.environ.get("LIVE_DEPLOY_PATH", "/opt/live/d2ypp").rstrip("/")
def stream_remote(ssh: paramiko.SSHClient, command: str, password: str, timeout: int = 3600) -> int:
stdin, stdout, stderr = ssh.exec_command(command, timeout=timeout, get_pty=True)
stdin.write(password + "\n")
stdin.flush()
try:
stdin.channel.shutdown_write()
except Exception:
pass
channel = stdout.channel
while True:
if channel.exit_status_ready() and not channel.recv_ready() and not channel.recv_stderr_ready():
break
r, _, _ = select.select([channel], [], [], 0.5)
if r:
data = channel.recv(4096)
if data:
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
if channel.recv_stderr_ready():
err = channel.recv_stderr(4096)
if err:
sys.stderr.buffer.write(err)
sys.stderr.buffer.flush()
return channel.recv_exit_status()
def run_post_config(ssh: paramiko.SSHClient, sftp: paramiko.SFTPClient, password: str) -> int:
print("\n[post] updating system-stack.env for proxycheap/neko proxy ports")
env_updates = {
"NEKO_SHELLCRASH_PROXY_PORT": "7894",
"SHELLCRASH_NEKO_PROXY_NODE": "proxycheap",
}
env_path = f"{REMOTE_PATH}/config/system-stack.env"
try:
existing = sftp.file(env_path, "r").read().decode("utf-8", "replace")
except OSError:
existing = ""
lines = existing.splitlines()
keys = set(env_updates)
kept = [line for line in lines if line.split("=", 1)[0].strip() not in keys]
for key, value in env_updates.items():
kept.append(f"{key}={value}")
payload = "\n".join(kept).rstrip() + "\n"
with sftp.file(env_path, "w") as fh:
fh.write(payload)
if CONFIG_YAML.is_file():
print(f"[post] uploading {CONFIG_YAML} to ShellCrash yamls")
tmp_yaml = f"/tmp/d2ypp-config-{int(time.time())}.yaml"
sftp.put(str(CONFIG_YAML), tmp_yaml)
sftp.chmod(tmp_yaml, 0o644)
install_cmd = (
f"sudo -S -p '' bash -lc "
f"'mkdir -p /etc/ShellCrash/yamls && install -m 0644 {shlex.quote(tmp_yaml)} /etc/ShellCrash/yamls/config.yaml'"
)
code = stream_remote(ssh, install_cmd, password, timeout=120)
if code != 0:
print(f"[post] install config.yaml exit={code}", file=sys.stderr)
return code
print("[post] applying ShellCrash profile via control_plane -> proxycheap")
apply_cmd = (
f"sudo -S -p '' bash -lc "
f"'cd {shlex.quote(REMOTE_PATH)} && "
f". scripts/linux/lib/common.sh && load_env && "
f"PY={shlex.quote(REMOTE_PATH)}/.venv/bin/python3; "
f"[ -x \"$PY\" ] || PY=python3; "
f"\"$PY\" - <<\"PY\"\n"
"import asyncio\n"
"from src.control_plane import apply_shellcrash_profile\n"
"result = asyncio.run(apply_shellcrash_profile(\"config.yaml\", \"proxycheap\"))\n"
"print(result)\n"
"PY'"
)
code = stream_remote(ssh, apply_cmd, password, timeout=600)
if code != 0:
print(f"[post] apply_shellcrash_profile exit={code}", file=sys.stderr)
return code
else:
print(f"[post] WARN: missing {CONFIG_YAML}, skip ShellCrash apply")
print("[post] restart Neko with ShellCrash proxy")
cmd = (
f"sudo -S -p '' bash -lc "
f"'cd {shlex.quote(REMOTE_PATH)} && "
f". scripts/linux/lib/common.sh && load_env && "
f"bash scripts/linux/service_ctl.sh neko reconfigure'"
)
code = stream_remote(ssh, cmd, password, timeout=300)
if code != 0:
print(f"[post] neko reconfigure exit={code}", file=sys.stderr)
print("[post] verify proxy listeners and neko containers")
verify = (
"set -e; "
"echo '--- system-stack env ---'; "
f"grep -E 'ENABLE_NEKO_BROWSER_PROXY|NEKO_SHELLCRASH|SHELLCRASH_NEKO' {shlex.quote(env_path)} || true; "
"echo '--- shellcrash listeners ---'; "
"grep -A6 'name: neko-mixed' /etc/ShellCrash/yamls/config.yaml 2>/dev/null || "
"grep -A6 'name: neko-mixed' /tmp/ShellCrash/config.yaml 2>/dev/null || true; "
"echo '--- neko proxy env ---'; "
f"cd {shlex.quote(REMOTE_PATH)} && . scripts/linux/lib/common.sh && load_env && "
"bash scripts/linux/service_ctl.sh neko status 2>/dev/null | head -30 || true; "
"echo '--- docker neko ---'; "
"docker ps -a --format '{{.Names}} {{.Status}}' | grep -i neko || true; "
"echo '--- health ---'; "
"curl -sf -m 5 http://127.0.0.1:8001/health && echo health_ok || echo health_fail"
)
stream_remote(ssh, verify, password, timeout=120)
return 0
def main() -> int:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
config = deploy.load_config()
if not config.password:
raise SystemExit("LIVE_DEPLOY_PASS is required")
stamp = time.strftime("%Y%m%d_%H%M%S")
revision = deploy._revision()
deploy.LOG_DIR.mkdir(parents=True, exist_ok=True)
local_log = deploy.LOG_DIR / f"full_deploy_stream_{stamp}.log"
print(f"==> full deploy {revision} -> {config.user}@{config.host}:{config.remote_path}")
archive = deploy.create_source_archive(stamp)
print(f"==> local archive: {archive} ({archive.stat().st_size} bytes)")
remote_archive = f"/tmp/d2ypp2-full-{stamp}.tar.gz"
remote_script = f"/tmp/d2ypp2-full-deploy-{stamp}.sh"
ssh = None
sftp = None
try:
ssh, sftp = deploy.connect(config)
print(f"==> uploading archive to {remote_archive}")
sftp.put(str(archive), remote_archive)
deploy._sftp_put_text(sftp, deploy.build_remote_script(), remote_script)
args = [
remote_script,
remote_archive,
config.remote_path,
stamp,
revision,
config.profile,
"1" if config.run_install else "0",
]
command = "sudo -S -p '' bash " + " ".join(shlex.quote(arg) for arg in args)
print("==> running remote full deployment (streaming)")
code = stream_remote(ssh, command, config.password, timeout=config.timeout)
print(f"\n==> deploy exit code: {code}")
if code != 0:
return code
post_code = run_post_config(ssh, sftp, config.password)
print(f"\n==> post-config exit code: {post_code}")
with local_log.open("a", encoding="utf-8") as fh:
fh.write(f"deploy={code} post={post_code} revision={revision}\n")
print(f"==> local log: {local_log}")
return post_code if post_code else code
finally:
if sftp is not None:
sftp.close()
if ssh is not None:
ssh.close()
if __name__ == "__main__":
raise SystemExit(main())