remote_reset_and_ingest.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. import paramiko
  3. import dotenv
  4. import time
  5. repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  6. dotenv.load_dotenv(dotenv_path=os.path.join(repo_root, ".env"))
  7. host = os.environ.get('SERVER_HOST')
  8. user = os.environ.get('SERVER_USER')
  9. password = os.environ.get('SERVER_PASS')
  10. if password == "your_db_password_here" or not password:
  11. password = None
  12. ssh = paramiko.SSHClient()
  13. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  14. try:
  15. ssh.connect(host, username=user, password=password, timeout=10)
  16. print("SSH Connected!")
  17. # 1. Kill the hung ingest run container
  18. print("Cleaning up hung ingest container...")
  19. ssh.exec_command("docker rm -f food_project-ingest-run-0c5b52a70d2d")
  20. # 2. Restart MySQL and Streamlit App to release metadata locks
  21. print("Restarting MySQL to release table locks...")
  22. stdin, stdout, stderr = ssh.exec_command("cd food_project && docker-compose restart mysql")
  23. stdout.read()
  24. print("Restarting Streamlit App to reset connection pool...")
  25. stdin, stdout, stderr = ssh.exec_command("cd food_project && docker-compose restart app")
  26. stdout.read()
  27. print("Waiting 10 seconds for database health...")
  28. time.sleep(10)
  29. # 3. Run the ingestion pipeline
  30. print("Re-running database ingestion...")
  31. cmd = "cd food_project && docker-compose run --rm -e PYTHONIOENCODING=utf-8 ingest python -X utf8 /app/ingest_csv.py"
  32. stdin, stdout, stderr = ssh.exec_command(cmd)
  33. # Capture outputs
  34. out_ing = stdout.read().decode('utf-8', errors='ignore')
  35. err_ing = stderr.read().decode('utf-8', errors='ignore')
  36. print("STDOUT:\n", out_ing.encode('ascii', 'replace').decode('ascii'))
  37. print("STDERR:\n", err_ing.encode('ascii', 'replace').decode('ascii'))
  38. except Exception as e:
  39. print(f"Error: {e}")
  40. finally:
  41. ssh.close()