533 lines
17 KiB
Python
533 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Full source deployment over SSH/SFTP.
|
|
|
|
This tool is for updating an existing live stack from the local checkout.
|
|
It replaces source files with rsync --delete while preserving machine-local
|
|
runtime state such as config, logs, databases, browser profiles, and service
|
|
data directories.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import fnmatch
|
|
import io
|
|
import os
|
|
import posixpath
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
from dataclasses import dataclass
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
LOG_DIR = REPO_ROOT / ".deploy_logs"
|
|
|
|
SOURCE_ARCHIVE_EXCLUDES = (
|
|
".git",
|
|
".deploy_logs",
|
|
".venv",
|
|
"__pycache__",
|
|
"*/__pycache__",
|
|
".pytest_cache",
|
|
"node_modules",
|
|
"web-console/node_modules",
|
|
"web-console/.next",
|
|
"web-console/.turbo",
|
|
"logs",
|
|
"downloads",
|
|
"backup_config",
|
|
"tmp",
|
|
"temp",
|
|
".pm2",
|
|
".process_runner",
|
|
"services/neko/data",
|
|
"services/filebrowser/database",
|
|
"services/filebrowser/config",
|
|
"services/uptime-kuma/data",
|
|
"services/mitmproxy/data",
|
|
"services/vscode-server/config",
|
|
"services/homepage/config/logs",
|
|
"services/homepage/config/kubernetes.yaml",
|
|
"services/frigate/media",
|
|
"vendor/scrcpy-server.jar",
|
|
"*.tar",
|
|
"*.tar.gz",
|
|
"*.tgz",
|
|
"*.zip",
|
|
"*.7z",
|
|
"*.log",
|
|
"*.pid",
|
|
"*.sock",
|
|
)
|
|
|
|
CONFIG_ARCHIVE_INCLUDES = (
|
|
"config/*.example",
|
|
"config/*.conf",
|
|
)
|
|
|
|
REMOTE_RSYNC_EXCLUDES = (
|
|
"/.git/",
|
|
"/.deploy_logs/",
|
|
"/.venv/",
|
|
"/node_modules/",
|
|
"/web-console/node_modules/",
|
|
"/web-console/.next/",
|
|
"/logs/",
|
|
"/downloads/",
|
|
"/backup_config/",
|
|
"/.pm2/",
|
|
"/.process_runner/",
|
|
"/config/",
|
|
"/backup/",
|
|
"/services/neko/data/",
|
|
"/services/filebrowser/database/",
|
|
"/services/filebrowser/config/",
|
|
"/services/uptime-kuma/data/",
|
|
"/services/mitmproxy/data/",
|
|
"/services/vscode-server/config/",
|
|
"/services/homepage/config/logs/",
|
|
"/services/homepage/config/kubernetes.yaml",
|
|
"/services/frigate/media/",
|
|
"/vendor/scrcpy-server.jar",
|
|
"/codex-live-stack.tgz",
|
|
)
|
|
|
|
OBSOLETE_SOURCE_RUNTIME_FILES = (
|
|
"config/URL_config.youtube.ini",
|
|
"config/URL_config.youtube2__ch_mp9mm36r_2wn0r.ini",
|
|
"config/URL_config.youtube2__ch_mp9n7yu2_83vci.ini",
|
|
"config/youtube.youtube.ini",
|
|
"config/youtube.youtube2__ch_mp9mm36r_2wn0r.ini",
|
|
"config/youtube.youtube2__ch_mp9mm9lz_a6jfx.ini",
|
|
"config/youtube.youtube2__ch_mp9n7yu2_83vci.ini",
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DeployConfig:
|
|
host: str
|
|
user: str
|
|
password: str
|
|
port: int
|
|
remote_path: str
|
|
profile: str
|
|
run_install: bool
|
|
timeout: int
|
|
jump_host: str = ""
|
|
jump_port: int = 22
|
|
jump_user: str = ""
|
|
jump_pass: str = ""
|
|
|
|
|
|
def _env_bool(name: str, default: bool) -> bool:
|
|
value = os.environ.get(name)
|
|
if value is None:
|
|
return default
|
|
return value.strip().lower() in {"1", "true", "yes", "on"}
|
|
|
|
|
|
def load_config() -> DeployConfig:
|
|
profile = os.environ.get("LIVE_DEPLOY_PROFILE", "all").strip() or "all"
|
|
if profile in {"full"}:
|
|
profile = "all"
|
|
if profile not in {"all", "hub", "business"}:
|
|
raise SystemExit(f"LIVE_DEPLOY_PROFILE must be all, hub, or business; got {profile!r}")
|
|
return DeployConfig(
|
|
host=os.environ.get("LIVE_DEPLOY_HOST", "192.168.2.101"),
|
|
user=os.environ.get("LIVE_DEPLOY_USER", "eric"),
|
|
password=os.environ.get("LIVE_DEPLOY_PASS", ""),
|
|
port=int(os.environ.get("LIVE_DEPLOY_PORT", os.environ.get("LIVE_SSH_PORT", "22"))),
|
|
remote_path=os.environ.get("LIVE_DEPLOY_PATH", "/opt/live/d2ypp").rstrip("/"),
|
|
profile=profile,
|
|
run_install=_env_bool("LIVE_DEPLOY_RUN_INSTALL", True),
|
|
timeout=int(os.environ.get("LIVE_DEPLOY_TIMEOUT", "3600")),
|
|
jump_host=os.environ.get("LIVE_DEPLOY_JUMP_HOST", ""),
|
|
jump_port=int(os.environ.get("LIVE_DEPLOY_JUMP_PORT", "22")),
|
|
jump_user=os.environ.get("LIVE_DEPLOY_JUMP_USER", ""),
|
|
jump_pass=os.environ.get("LIVE_DEPLOY_JUMP_PASS", ""),
|
|
)
|
|
|
|
|
|
def _safe_print(text: str) -> None:
|
|
try:
|
|
print(text)
|
|
except UnicodeEncodeError:
|
|
enc = getattr(sys.stdout, "encoding", None) or "utf-8"
|
|
sys.stdout.buffer.write(text.encode(enc, errors="replace") + b"\n")
|
|
|
|
|
|
def _decode(data: bytes) -> str:
|
|
return data.decode("utf-8", errors="replace") if data else ""
|
|
|
|
|
|
def _redact(text: str, secret: str) -> str:
|
|
return text.replace(secret, "<redacted>") if secret else text
|
|
|
|
|
|
def _revision() -> str:
|
|
try:
|
|
return subprocess.check_output(
|
|
["git", "rev-parse", "--short", "HEAD"],
|
|
cwd=REPO_ROOT.parent,
|
|
text=True,
|
|
stderr=subprocess.DEVNULL,
|
|
).strip()
|
|
except Exception:
|
|
return "unknown"
|
|
|
|
|
|
def _matches_exclude(rel: str, pattern: str) -> bool:
|
|
rel = rel.strip("/")
|
|
pattern = pattern.strip("/")
|
|
if not rel or not pattern:
|
|
return False
|
|
if rel == pattern or rel.startswith(pattern + "/"):
|
|
return True
|
|
return fnmatch.fnmatch(rel, pattern)
|
|
|
|
|
|
def _tar_filter(info: tarfile.TarInfo) -> tarfile.TarInfo | None:
|
|
rel = info.name.replace("\\", "/").removeprefix("./").strip("/")
|
|
if not rel:
|
|
return info
|
|
if rel == "config" or rel.startswith("config/"):
|
|
if rel == "config" or info.isdir() or any(fnmatch.fnmatch(rel, pattern) for pattern in CONFIG_ARCHIVE_INCLUDES):
|
|
return info
|
|
return None
|
|
for pattern in SOURCE_ARCHIVE_EXCLUDES:
|
|
if _matches_exclude(rel, pattern):
|
|
return None
|
|
return info
|
|
|
|
|
|
def create_source_archive(stamp: str) -> Path:
|
|
archive = Path(tempfile.gettempdir()) / f"d2ypp2-full-{stamp}.tar.gz"
|
|
with tarfile.open(archive, "w:gz") as tf:
|
|
tf.add(REPO_ROOT, arcname=".", filter=_tar_filter)
|
|
return archive
|
|
|
|
|
|
def _mkdir_p(sftp, remote_dir: str) -> None:
|
|
remote_dir = remote_dir.replace("\\", "/").rstrip("/")
|
|
if not remote_dir or remote_dir == "/":
|
|
return
|
|
cur = ""
|
|
for part in [p for p in remote_dir.split("/") if p]:
|
|
cur = f"{cur}/{part}" if cur else f"/{part}"
|
|
try:
|
|
sftp.stat(cur)
|
|
except OSError:
|
|
try:
|
|
sftp.mkdir(cur)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _sftp_put_text(sftp, text: str, remote_path: str) -> None:
|
|
_mkdir_p(sftp, posixpath.dirname(remote_path))
|
|
data = text.replace("\r\n", "\n").replace("\r", "\n").encode("utf-8")
|
|
sftp.putfo(io.BytesIO(data), remote_path)
|
|
sftp.chmod(remote_path, 0o755)
|
|
|
|
|
|
def connect(config: DeployConfig):
|
|
try:
|
|
import paramiko
|
|
except ImportError as exc:
|
|
raise SystemExit("Install paramiko first: python -m pip install paramiko") from exc
|
|
|
|
sock = None
|
|
jump = None
|
|
if config.jump_host:
|
|
jump = paramiko.SSHClient()
|
|
jump.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
jump.connect(
|
|
config.jump_host,
|
|
port=config.jump_port,
|
|
username=config.jump_user or config.user,
|
|
password=config.jump_pass or config.password,
|
|
timeout=30,
|
|
banner_timeout=40,
|
|
auth_timeout=30,
|
|
)
|
|
sock = jump.get_transport().open_channel(
|
|
"direct-tcpip",
|
|
(config.host, config.port),
|
|
("127.0.0.1", 0),
|
|
timeout=30,
|
|
)
|
|
|
|
client = paramiko.SSHClient()
|
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
if jump is not None:
|
|
client._live_jump_client = jump
|
|
client.connect(
|
|
config.host,
|
|
port=config.port,
|
|
username=config.user,
|
|
password=config.password,
|
|
sock=sock,
|
|
timeout=30,
|
|
banner_timeout=40,
|
|
auth_timeout=30,
|
|
)
|
|
return client, client.open_sftp()
|
|
|
|
|
|
def build_remote_script() -> str:
|
|
rsync_excludes = " \\\n".join(f" --exclude={shlex.quote(value)}" for value in REMOTE_RSYNC_EXCLUDES)
|
|
obsolete_files = " ".join(shlex.quote(value) for value in OBSOLETE_SOURCE_RUNTIME_FILES)
|
|
return f"""#!/usr/bin/env bash
|
|
set -Eeuo pipefail
|
|
|
|
ARCHIVE="$1"
|
|
TARGET="$2"
|
|
STAMP="$3"
|
|
REVISION="$4"
|
|
PROFILE="$5"
|
|
RUN_INSTALL="$6"
|
|
|
|
case "$TARGET" in
|
|
""|"/"|"/opt"|"/home"|"/var"|"/usr"|"/etc")
|
|
echo "[full-deploy] unsafe target: $TARGET" >&2
|
|
exit 2
|
|
;;
|
|
esac
|
|
|
|
STAGE="/tmp/d2ypp2-full-stage-${{STAMP}}"
|
|
LOG_DIR="${{TARGET}}/.deploy_logs"
|
|
FULL_LOG="${{LOG_DIR}}/full_deploy_${{STAMP}}.log"
|
|
mkdir -p "$(dirname "$TARGET")" "$TARGET" "$LOG_DIR" /opt/live/deploy_backups
|
|
exec > >(tee -a "$FULL_LOG") 2>&1
|
|
|
|
echo "[full-deploy] stamp=$STAMP revision=$REVISION target=$TARGET profile=$PROFILE run_install=$RUN_INSTALL"
|
|
|
|
for cmd in tar rsync sed systemctl curl; do
|
|
if ! command -v "$cmd" >/dev/null 2>&1; then
|
|
echo "[full-deploy] missing required command: $cmd" >&2
|
|
exit 3
|
|
fi
|
|
done
|
|
|
|
echo "[full-deploy] stopping control-plane services"
|
|
pkill -TERM -f "${{TARGET}}/web-console/node_modules/.bin/next build" 2>/dev/null || true
|
|
pkill -TERM -f "npm run build" 2>/dev/null || true
|
|
sleep 2
|
|
pkill -KILL -f "${{TARGET}}/web-console/node_modules/.bin/next build" 2>/dev/null || true
|
|
systemctl stop live-edge-watch.service live-edge.service live-console.service 2>/dev/null || true
|
|
|
|
BACKUP="/opt/live/deploy_backups/d2ypp-before-${{STAMP}}.tar.gz"
|
|
echo "[full-deploy] backup current tree to $BACKUP"
|
|
if [ -d "$TARGET" ]; then
|
|
tar -czf "$BACKUP" \\
|
|
--exclude='./.venv' \\
|
|
--exclude='./web-console/node_modules' \\
|
|
--exclude='./web-console/.next' \\
|
|
--exclude='./logs' \\
|
|
--exclude='./downloads' \\
|
|
--exclude='./backup_config' \\
|
|
--exclude='./.pm2' \\
|
|
--exclude='./.process_runner' \\
|
|
--exclude='./services/neko/data' \\
|
|
--exclude='./codex-live-stack.tgz' \\
|
|
-C "$TARGET" . || true
|
|
fi
|
|
|
|
echo "[full-deploy] extracting source archive"
|
|
rm -rf "$STAGE"
|
|
mkdir -p "$STAGE"
|
|
tar -xzf "$ARCHIVE" -C "$STAGE"
|
|
|
|
echo "[full-deploy] normalizing Linux text files"
|
|
find "$STAGE" -type f \\( \\
|
|
-name '*.sh' -o -name '*.py' -o -name 'Dockerfile' -o -name '*.cjs' -o -name '*.mjs' -o \\
|
|
-name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.json' -o -name '*.yml' -o -name '*.yaml' -o \\
|
|
-name '*.ini' -o -name '*.conf' \\
|
|
\\) -exec sed -i 's/\\r$//' {{}} +
|
|
|
|
echo "[full-deploy] syncing source with runtime-state protection"
|
|
rsync -a --delete \\
|
|
{rsync_excludes} \\
|
|
"$STAGE"/ "$TARGET"/ | tee "${{LOG_DIR}}/rsync_items_${{STAMP}}.log"
|
|
|
|
echo "[full-deploy] syncing config templates and missing default config only"
|
|
mkdir -p "$TARGET/config" "$TARGET/backup"
|
|
if [ -d "$STAGE/config" ]; then
|
|
rsync -a "$STAGE/config/" "$TARGET/config/" --include='*/' --include='*.example' --include='*.conf' --exclude='*' || true
|
|
fi
|
|
write_missing_config() {{
|
|
local rel="$1"
|
|
local dest="$TARGET/config/$rel"
|
|
if [ -e "$dest" ]; then
|
|
cat >/dev/null
|
|
return 0
|
|
fi
|
|
mkdir -p "$(dirname "$dest")"
|
|
cat >"$dest"
|
|
chmod 0666 "$dest" 2>/dev/null || true
|
|
}}
|
|
write_missing_config config.ini <<'EOF_CONFIG_INI'
|
|
EOF_CONFIG_INI
|
|
write_missing_config URL_config.ini <<'EOF_URL_CONFIG'
|
|
EOF_URL_CONFIG
|
|
write_missing_config youtube.ini <<'EOF_YOUTUBE_INI'
|
|
[youtube]
|
|
key =
|
|
rtmps = yes
|
|
bitrate = 4500
|
|
fast_audio = 1
|
|
EOF_YOUTUBE_INI
|
|
write_missing_config web2_bind_host.txt <<'EOF_WEB2_HOST'
|
|
0.0.0.0
|
|
EOF_WEB2_HOST
|
|
write_missing_config web2_api_token.txt <<'EOF_WEB2_TOKEN'
|
|
EOF_WEB2_TOKEN
|
|
write_missing_config easytier_network.json <<'EOF_EASYTIER'
|
|
{{"networkName":"","networkSecret":"","peerUrls":[]}}
|
|
EOF_EASYTIER
|
|
if [ -d "$STAGE/backup" ]; then
|
|
rsync -a "$STAGE/backup/" "$TARGET/backup/" --include='*/' --include='*.py' --exclude='*' || true
|
|
fi
|
|
|
|
cd "$TARGET"
|
|
rm -f {obsolete_files} 2>/dev/null || true
|
|
rm -rf src/__pycache__ backup/__pycache__ tests/__pycache__ __pycache__ 2>/dev/null || true
|
|
chmod +x install*.sh upgrade*.sh uninstall.sh doctor.sh web.sh dev.sh start.sh obs.sh probe-live.sh refresh-live-unit.sh 2>/dev/null || true
|
|
find scripts live-platform/scripts services/neko -type f -name '*.sh' -exec chmod +x {{}} + 2>/dev/null || true
|
|
find tools scripts live-platform/tools -type f -name '*.py' -exec chmod +x {{}} + 2>/dev/null || true
|
|
|
|
echo "[full-deploy] preparing runtime permissions before install"
|
|
if id live >/dev/null 2>&1; then
|
|
chown -R live:live "$TARGET" 2>/dev/null || true
|
|
fi
|
|
chmod -R a+rwX "$TARGET" 2>/dev/null || true
|
|
if [ -f scripts/linux/lib/common.sh ]; then
|
|
bash -lc "cd '$TARGET'; . scripts/linux/lib/common.sh; ensure_live_user; load_env; ensure_runtime_dirs_owned_by_live"
|
|
fi
|
|
|
|
printf 'stamp=%s\\nrevision=%s\\nprofile=%s\\narchive=%s\\n' "$STAMP" "$REVISION" "$PROFILE" "$ARCHIVE" > "${{LOG_DIR}}/deployed_${{STAMP}}.txt"
|
|
|
|
if [ "$RUN_INSTALL" = "1" ]; then
|
|
echo "[full-deploy] running full stack installer"
|
|
LIVE_STACK_REPO_ROOT="$TARGET" bash scripts/linux/install_stack.sh "$PROFILE"
|
|
else
|
|
echo "[full-deploy] LIVE_DEPLOY_RUN_INSTALL=0; skipping installer"
|
|
fi
|
|
|
|
echo "[full-deploy] final service refresh"
|
|
systemctl reset-failed dnsmasq.service 2>/dev/null || true
|
|
systemctl daemon-reload
|
|
systemctl try-restart live-console.service live-edge.service live-edge-watch.service live-neko-ip-watch.service live-webtty.service live-android-panel.service live-pulseaudio.service 2>/dev/null || true
|
|
systemctl start live-console.service 2>/dev/null || true
|
|
systemctl start live-edge.service live-edge-watch.service 2>/dev/null || true
|
|
|
|
echo "[full-deploy] waiting for control plane health"
|
|
ok=0
|
|
for _ in $(seq 1 75); do
|
|
if curl -sf -m 4 http://127.0.0.1:8001/health >/dev/null 2>&1; then
|
|
ok=1
|
|
break
|
|
fi
|
|
sleep 2
|
|
done
|
|
if [ "$ok" != "1" ]; then
|
|
echo "[full-deploy] ERROR: control plane did not become healthy" >&2
|
|
journalctl -u live-console.service -n 120 --no-pager 2>/dev/null || true
|
|
exit 4
|
|
fi
|
|
echo "[full-deploy] health_ok_8001"
|
|
|
|
echo "[full-deploy] HTTP checks"
|
|
curl -sS -m 10 -o /dev/null -w 'root_http=%{{http_code}}\\n' http://127.0.0.1/ || true
|
|
curl -sS -m 10 -o /dev/null -w 'health_http=%{{http_code}}\\n' http://127.0.0.1:8001/health || true
|
|
curl -sS -m 10 http://127.0.0.1:8001/server_info | head -c 1200 || true
|
|
echo
|
|
|
|
echo "[full-deploy] systemd state"
|
|
systemctl --no-pager --plain is-active live-console.service live-edge.service live-edge-watch.service live-neko-ip-watch.service live-webtty.service live-android-panel.service live-pulseaudio.service 2>/dev/null || true
|
|
|
|
echo "[full-deploy] docker state"
|
|
docker ps -a --format '{{{{.Names}}}} {{{{.Status}}}}' 2>/dev/null | grep -E 'live-|redroid' | sort || true
|
|
|
|
echo "[full-deploy] done"
|
|
"""
|
|
|
|
|
|
def execute_remote(ssh, config: DeployConfig, remote_script: str, remote_archive: str, stamp: str, revision: str) -> tuple[int, str]:
|
|
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)
|
|
stdin, stdout, stderr = ssh.exec_command(command, timeout=config.timeout, get_pty=False)
|
|
stdin.write(config.password + "\n")
|
|
stdin.flush()
|
|
try:
|
|
stdin.channel.shutdown_write()
|
|
except Exception:
|
|
pass
|
|
out = _decode(stdout.read())
|
|
err = _decode(stderr.read())
|
|
code = stdout.channel.recv_exit_status()
|
|
return code, f"--- stdout ---\n{out}\n--- stderr ---\n{err}\n"
|
|
|
|
|
|
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 = load_config()
|
|
if not config.password:
|
|
raise SystemExit("LIVE_DEPLOY_PASS is required for password and sudo authentication")
|
|
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
revision = _revision()
|
|
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
local_log = LOG_DIR / f"full_deploy_{stamp}.log"
|
|
local_log.write_text(
|
|
f"full deploy {stamp} revision={revision} -> {config.user}@{config.host}:{config.port}:{config.remote_path}\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
archive = create_source_archive(stamp)
|
|
_safe_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 = connect(config)
|
|
_safe_print(f"uploading archive to {remote_archive}")
|
|
sftp.put(str(archive), remote_archive)
|
|
_sftp_put_text(sftp, build_remote_script(), remote_script)
|
|
sftp.close()
|
|
sftp = None
|
|
|
|
_safe_print("running remote full deployment")
|
|
code, output = execute_remote(ssh, config, remote_script, remote_archive, stamp, revision)
|
|
output = _redact(output, config.password)
|
|
with local_log.open("a", encoding="utf-8", errors="replace") as fh:
|
|
fh.write(output)
|
|
tail = "\n".join(output.splitlines()[-140:])
|
|
_safe_print(tail)
|
|
_safe_print(f"local log: {local_log}")
|
|
return code
|
|
finally:
|
|
if sftp is not None:
|
|
sftp.close()
|
|
if ssh is not None:
|
|
ssh.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|