import os import sys import paramiko from dotenv import load_dotenv sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') def main(): repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env_path = os.path.join(repo_root, ".env") load_dotenv(dotenv_path=env_path) host = os.environ.get('SERVER_HOST') user = os.environ.get('SERVER_USER') password = os.environ.get('SERVER_PASS') if not all([host, user]): print("Error: Server credentials not found in .env file.") return if password == "your_db_password_here" or password == "your_password_here" or not password: password = None print(f"Connecting to {user}@{host} via SSH...") ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host, username=user, password=password, timeout=15) print("Connected successfully!") # 1. Bring down and purge old deployment (Uninstall) print("\n--- [1/3] Purging existing stack (Docker Compose Down -v) ---") stdin, stdout, stderr = ssh.exec_command("cd food_project && docker-compose down -v") print("Output:", stdout.read().decode('utf-8')) print("Errors/Warnings:", stderr.read().decode('utf-8')) # 2. Fetch and pull latest code print("\n--- [2/3] Pulling latest version from Git ---") stdin, stdout, stderr = ssh.exec_command("cd food_project && git fetch origin main && git reset --hard origin/main && git clean -fd") print("Output:", stdout.read().decode('utf-8')) print("Errors/Warnings:", stderr.read().decode('utf-8')) # 3. Start up the new stack local_model = os.environ.get('LLM_MODEL', 'llama3.2:3b') print(f"\n--- [3/3] Launching new stack with model {local_model} ---") command = f"cd food_project && sed -i 's/^LLM_MODEL=.*/LLM_MODEL={local_model}/' .env && docker-compose up -d --build" stdin, stdout, stderr = ssh.exec_command(command) print("Output:", stdout.read().decode('utf-8')) print("Errors/Warnings:", stderr.read().decode('utf-8')) print("\nAll remote operations completed.") except Exception as e: print(f"Error executing remote commands: {e}") finally: ssh.close() print("SSH connection closed.") if __name__ == "__main__": main()