almeira-web/scripts/sync_container_code.py

73 lines
2.8 KiB
Python

import paramiko
import os
import tarfile
import tempfile
import sys
import io
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
HOST = "161.97.93.156"
USER = "carlos"
PASSWORD = "Innova1978+*?"
CONTAINER = "taykgoh4hhbeacsewdm2bscx-151936701262"
BACKEND_DIR = r"c:\Users\Carlos\dev\almeira-web\transporte-cali-buenaventura\backend"
def make_tar(source_dir, output_filename, arcname_prefix):
with tarfile.open(output_filename, "w:gz") as tar:
for root, dirs, files in os.walk(source_dir):
for file in files:
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, source_dir)
tar.add(full_path, arcname=os.path.join(arcname_prefix, rel_path).replace("\\", "/"))
def main():
print("[1/4] Creando archivos tar de dist y public...", flush=True)
temp_dir = tempfile.gettempdir()
dist_tar = os.path.join(temp_dir, "dist_update.tar.gz")
public_tar = os.path.join(temp_dir, "public_update.tar.gz")
make_tar(os.path.join(BACKEND_DIR, "dist"), dist_tar, "dist")
make_tar(os.path.join(BACKEND_DIR, "public"), public_tar, "public")
print(" -> Tarfiles creados exitosamente.", flush=True)
print("[2/4] Conectando por SSH y subiendo a VPS...", flush=True)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=HOST, username=USER, password=PASSWORD, timeout=30)
sftp = ssh.open_sftp()
sftp.put(dist_tar, "/tmp/dist_update.tar.gz")
sftp.put(public_tar, "/tmp/public_update.tar.gz")
sftp.close()
print("[3/4] Extrayendo y sincronizando en el contenedor Coolify...", flush=True)
cmds = [
"mkdir -p /tmp/dist_update && tar -xzf /tmp/dist_update.tar.gz -C /tmp/dist_update",
"mkdir -p /tmp/public_update && tar -xzf /tmp/public_update.tar.gz -C /tmp/public_update",
f"docker cp /tmp/dist_update/dist/. {CONTAINER}:/app/dist/",
f"docker cp /tmp/public_update/public/. {CONTAINER}:/app/public/",
f"docker restart {CONTAINER}",
"rm -rf /tmp/dist_update /tmp/public_update /tmp/dist_update.tar.gz /tmp/public_update.tar.gz"
]
for cmd in cmds:
stdin, stdout, stderr = ssh.exec_command(cmd)
stdout.channel.recv_exit_status()
import time
time.sleep(3)
stdin, stdout, stderr = ssh.exec_command(f"docker logs --tail 30 {CONTAINER}")
logs = stdout.read().decode('utf-8')
print("--- LOGS DEL CONTENEDOR TRAS REINICIO ---")
print(logs)
print("-----------------------------------------")
ssh.close()
print("[OK] Sincronización del contenedor completada.", flush=True)
if __name__ == "__main__":
main()