# -*- coding: utf-8 -*-
"""
check_service.py - 检查服务器上的服务状态
"""

import paramiko

HOST = '192.168.5.60'
USER = 'ubains'
PASSWORD = 'Ubains@123'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HOST, username=USER, password=PASSWORD)

print("="*60)
print("  Service Status Check")
print("="*60)

# 检查进程
print("\n[1] Process status:")
stdin, stdout, stderr = ssh.exec_command('ps aux | grep server.py | grep -v grep')
print(stdout.read().decode())

# 检查端口
print("\n[2] Port status:")
stdin, stdout, stderr = ssh.exec_command('ss -tlnp | grep 8088 || echo "Port 8088 not listening"')
print(stdout.read().decode())

# 检查日志
print("\n[3] Recent logs:")
stdin, stdout, stderr = ssh.exec_command('tail -30 /tmp/troubleshoot.log 2>/dev/null || echo "No log file"')
print(stdout.read().decode())

# 尝试启动服务
print("\n[4] Starting service...")
stdin, stdout, stderr = ssh.exec_command('cd /opt/troubleshoot/web && nohup python3 server.py > /tmp/troubleshoot.log 2>&1 &')
stdout.read()

import time
time.sleep(3)

# 再次检查
print("\n[5] After restart:")
stdin, stdout, stderr = ssh.exec_command('ps aux | grep server.py | grep -v grep')
print(stdout.read().decode())

# 健康检查
print("\n[6] Health check:")
stdin, stdout, stderr = ssh.exec_command('curl -s http://localhost:8088/api/health')
result = stdout.read().decode()
print(result[:500] if result else "No response")

ssh.close()