uninstall_reinstall_server.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import os
  2. import sys
  3. import paramiko
  4. from dotenv import load_dotenv
  5. sys.stdout.reconfigure(encoding='utf-8')
  6. sys.stderr.reconfigure(encoding='utf-8')
  7. def main():
  8. repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9. env_path = os.path.join(repo_root, ".env")
  10. load_dotenv(dotenv_path=env_path)
  11. host = os.environ.get('SERVER_HOST')
  12. user = os.environ.get('SERVER_USER')
  13. password = os.environ.get('SERVER_PASS')
  14. if not all([host, user]):
  15. print("Error: Server credentials not found in .env file.")
  16. return
  17. if password == "your_db_password_here" or password == "your_password_here" or not password:
  18. password = None
  19. print(f"Connecting to {user}@{host} via SSH...")
  20. ssh = paramiko.SSHClient()
  21. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  22. try:
  23. ssh.connect(host, username=user, password=password, timeout=15)
  24. print("Connected successfully!")
  25. # 1. Bring down and purge old deployment (Uninstall)
  26. print("\n--- [1/3] Purging existing stack (Docker Compose Down -v) ---")
  27. stdin, stdout, stderr = ssh.exec_command("cd food_project && docker-compose down -v")
  28. print("Output:", stdout.read().decode('utf-8'))
  29. print("Errors/Warnings:", stderr.read().decode('utf-8'))
  30. # 2. Fetch and pull latest code
  31. print("\n--- [2/3] Pulling latest version from Git ---")
  32. stdin, stdout, stderr = ssh.exec_command("cd food_project && git fetch origin main && git reset --hard origin/main && git clean -fd")
  33. print("Output:", stdout.read().decode('utf-8'))
  34. print("Errors/Warnings:", stderr.read().decode('utf-8'))
  35. # 3. Start up the new stack
  36. local_model = os.environ.get('LLM_MODEL', 'llama3.2:3b')
  37. print(f"\n--- [3/3] Launching new stack with model {local_model} ---")
  38. command = f"cd food_project && sed -i 's/^LLM_MODEL=.*/LLM_MODEL={local_model}/' .env && docker-compose up -d --build"
  39. stdin, stdout, stderr = ssh.exec_command(command)
  40. print("Output:", stdout.read().decode('utf-8'))
  41. print("Errors/Warnings:", stderr.read().decode('utf-8'))
  42. print("\nAll remote operations completed.")
  43. except Exception as e:
  44. print(f"Error executing remote commands: {e}")
  45. finally:
  46. ssh.close()
  47. print("SSH connection closed.")
  48. if __name__ == "__main__":
  49. main()