File size: 6,020 Bytes
9ada852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#!/usr/bin/env python3
"""
scripts/deploy_altare.py
Automated SFTP Deployment & Verification Pipeline for Altare Pterodactyl Container.
Transfers updated worker engine to kg-bsz01.altare.global:2022 (/home/container/).
"""

import os
import sys
import argparse
import socket
import py_compile
import getpass
from pathlib import Path

# Canonical Altare Pterodactyl SFTP Parameters
SFTP_HOST = os.environ.get("ALTARE_SFTP_HOST", "kg-bsz01.altare.global")
SFTP_PORT = int(os.environ.get("ALTARE_SFTP_PORT", "2022"))
SFTP_USER = os.environ.get("ALTARE_SFTP_USER", "tenant_b33850c9.a1a67ef9")
SFTP_PASS = os.environ.get("ALTARE_SFTP_PASSWORD", "")

WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
LOCAL_MAIN = WORKSPACE_ROOT / "altare_worker" / "main.py"
LOCAL_REQS = WORKSPACE_ROOT / "altare_worker" / "requirements.txt"

REMOTE_FILES = [
    (LOCAL_MAIN, "/home/container/app.py"),
    (LOCAL_MAIN, "/home/container/main.py"),
    (LOCAL_REQS, "/home/container/requirements.txt"),
]


def validate_syntax():
    """Pre-flight AST & bytecode compilation validation."""
    print("πŸ” [1/3] Running pre-flight syntax validation...")
    if not LOCAL_MAIN.exists():
        raise FileNotFoundError(f"Local worker script not found: {LOCAL_MAIN}")
    try:
        py_compile.compile(str(LOCAL_MAIN), doraise=True)
        print("βœ… Pre-flight syntax validation passed (zero syntax errors).")
    except Exception as exc:
        print(f"❌ Syntax validation failed: {exc}", file=sys.stderr)
        raise


def check_network_reachability(host: str, port: int, timeout: float = 5.0) -> bool:
    """Verifies TCP socket reachability to SFTP endpoint."""
    print(f"πŸ“‘ Checking network reachability to {host}:{port}...")
    try:
        with socket.create_connection((host, port), timeout=timeout):
            print(f"βœ… Network reachability verified: {host}:{port} is open.")
            return True
    except (socket.timeout, socket.error) as err:
        print(f"⚠️ Network warning: Could not connect to {host}:{port}: {err}", file=sys.stderr)
        return False


def deploy_sftp(host: str, port: int, user: str, password: str, dry_run: bool = False):
    """Executes authenticated SFTP transfer to remote container."""
    if dry_run:
        print("⚑ [DRY RUN] Simulating deployment steps without transferring files:")
        for local_p, remote_p in REMOTE_FILES:
            print(f"   Would upload: {local_p} -> {remote_p}")
        print("βœ… Dry run completed successfully.")
        return

    if not password:
        password = getpass.getpass(f"Enter SFTP password for {user}@{host}:{port}: ")
        if not password:
            raise ValueError("SFTP password is required for deployment.")

    try:
        import paramiko
        _PARAMIKO = True
    except ImportError:
        _PARAMIKO = False

    if _PARAMIKO:
        print(f"πŸš€ [2/3] Connecting to SFTP: {user}@{host}:{port} via Paramiko...")
        transport = paramiko.Transport((host, port))
        transport.connect(username=user, password=password)
        sftp = paramiko.SFTPClient.from_transport(transport)
        try:
            print("πŸ“¦ [3/3] Uploading worker files to /home/container/...")
            for local_p, remote_p in REMOTE_FILES:
                if not local_p.exists():
                    print(f"⚠️ Warning: Skipping missing file {local_p}")
                    continue
                print(f"   Uploading {local_p.name} -> {remote_p} ...")
                sftp.put(str(local_p), remote_p)
                print(f"   βœ… Transferred {remote_p}")
            print("πŸŽ‰ Altare container files successfully deployed via Paramiko SFTP.")
        finally:
            sftp.close()
            transport.close()
    else:
        # Fallback to subprocess scp/sftp if paramiko is not installed
        import subprocess
        print(f"πŸš€ [2/3] Connecting via system SFTP fallback...")
        sftp_batch = []
        for local_p, remote_p in REMOTE_FILES:
            if local_p.exists():
                sftp_batch.append(f"put {local_p} {remote_p}")
        sftp_batch.append("bye\n")
        sftp_cmds = "\n".join(sftp_batch)

        cmd = ["sftp", "-P", str(port), f"{user}@{host}"]
        proc = subprocess.run(cmd, input=sftp_cmds, text=True, capture_output=True)
        if proc.returncode != 0:
            raise RuntimeError(f"System SFTP failed: {proc.stderr}")
        print("πŸŽ‰ Altare container files successfully deployed via System SFTP.")


def main():
    parser = argparse.ArgumentParser(description="Automated SFTP Deployment for Altare Pterodactyl Container")
    parser.add_argument("--host", default=SFTP_HOST, help="Altare SFTP Host (default: kg-bsz01.altare.global)")
    parser.add_argument("--port", type=int, default=SFTP_PORT, help="Altare SFTP Port (default: 2022)")
    parser.add_argument("--user", default=SFTP_USER, help="Altare SFTP User (default: tenant_b33850c9.a1a67ef9)")
    parser.add_argument("--password", default=SFTP_PASS, help="Altare SFTP Password (or ALTARE_SFTP_PASSWORD env var)")
    parser.add_argument("--verify", action="store_true", help="Verify syntax and network reachability without uploading")
    parser.add_argument("--dry-run", action="store_true", help="Simulate deployment steps without modifying remote files")

    args = parser.parse_args()

    # Step 1: Pre-flight syntax validation
    validate_syntax()

    # Step 2: Verification mode
    if args.verify:
        reach = check_network_reachability(args.host, args.port)
        if reach:
            print("βœ… Verification passed: Syntax valid and Altare SFTP host reachable.")
            sys.exit(0)
        else:
            print("⚠️ Verification warning: Host unreachable or connection timed out.")
            sys.exit(1)

    # Step 3: Deploy or Dry Run
    deploy_sftp(
        host=args.host,
        port=args.port,
        user=args.user,
        password=args.password,
        dry_run=args.dry_run
    )


if __name__ == "__main__":
    main()