import os
import dotenv
import asyncio
import aiofiles
import asyncssh
from log_parser.nextjs import parse_nextjs_logs
async def execute_ssh_command(deployment_id, command, deployment):
dotenv.load_dotenv()
host = os.getenv('XLX_SSH_HOST')
username = os.getenv('XLX_SSH_USER')
password = os.getenv('XLX_SSH_PASS')
if not all([host, username, password]):
raise ValueError("Missing SSH credentials in environment variables")
log_dir = f"./logs/deployment_{deployment_id}"
os.makedirs(log_dir, exist_ok=True)
output_file_path = os.path.join(log_dir, f"{deployment_id}.txt")
print(f"Output file path: {output_file_path}")
try:
async with asyncssh.connect(host, username=username,
password=password) as conn:
print(f"Executing command: {command}")
process = await conn.create_process(command)
async with aiofiles.open(output_file_path, 'w',
encoding='utf-8') as file:
async for line in process.stdout:
result = await parse_nextjs_logs(
line, deployment_data=deployment)
if result:
print("Deployment completed. Terminating process.")
process.terminate()
break
line = line.strip()
print(line)
await file.write(line + '\n')
async for line in process.stderr:
result = await parse_nextjs_logs(
line, deployment_data=deployment)
if result:
print("Deployment completed. Terminating process.")
process.terminate()
break
line = line.strip()
print(line)
await file.write(line + '\n')
print(f"Output saved to: {output_file_path}")
except Exception as e:
print(
f"SSH connection or command execution failed: {str(e).encode('utf-8', errors='replace').decode('utf-8')}"
)