import paramiko

host = '8.140.221.49'
username = 'root'
private_key_path = r'C:\Users\FZX\.ssh\FzxBdsh-ECS.pem'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, key_filename=private_key_path, timeout=30)

print('='*80)
print('使用podman-compose重启用户服务')
print('='*80)

# 1. 检查podman-compose文件
print('\n1. 检查podman-compose文件...')
cmd = 'ls -la /opt/Fzxpodman/infrastructure/compose/'
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read().decode()
print(f'compose目录内容: {result}')

# 2. 查看aliyun-dev配置中的用户服务部分
print('\n2. 查看用户服务配置...')
cmd = 'grep -A 20 "user-service:" /opt/Fzxpodman/infrastructure/compose/podman-compose.aliyun-dev.yml'
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read().decode()
print(f'用户服务配置: {result}')

# 3. 使用podman-compose重启用户服务
print('\n3. 使用podman-compose重启用户服务...')
cmd = 'cd /opt/Fzxpodman/infrastructure/compose && podman-compose -f podman-compose.aliyun-dev.yml up -d user-service'
stdin, stdout, stderr = ssh.exec_command(cmd, timeout=120)
result = stdout.read().decode()[-3000:]
print(f'启动输出: {result}')

# 4. 等待服务启动
print('\n4. 等待服务启动...')
import time
time.sleep(90)

# 5. 检查容器状态
print('\n5. 检查容器状态...')
cmd = 'podman ps -a | grep fzx-aliyun-user'
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read().decode()
print(f'容器状态: {result}')

# 6. 测试健康检查
print('\n6. 测试健康检查...')
cmd = 'podman exec fzx-aliyun-user curl -s http://localhost:8091/health'
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read().decode()
print(f'/health: {result}')

# 7. 测试API健康检查
print('\n7. 测试API健康检查...')
cmd = 'podman exec fzx-aliyun-user curl -s http://localhost:8091/api/user/health'
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read().decode()
print(f'/api/user/health: {result}')

# 8. 测试通过网关访问
print('\n8. 测试通过网关访问...')
cmd = 'curl -s http://8.140.221.49:8089/api/user/health'
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read().decode()
print(f'通过网关访问: {result}')

ssh.close()

print('\n' + '='*80)
print('操作完成!')
print('='*80)