save code
This commit is contained in:
+59
-25
@@ -506,6 +506,33 @@ def pushStr2Queue(key, data_str):
|
||||
else:
|
||||
logger.error(f"pushStr2Queue get lock error {data_str}")
|
||||
|
||||
def queueCall(data):
|
||||
key = str(uuid.uuid4())
|
||||
redis_conn = get_redis_conn()
|
||||
|
||||
task_data = {}
|
||||
task_data['key'] = key
|
||||
task_data['api'] = "/do_change_cloth"
|
||||
task_data['request'] = data
|
||||
logger.info(f"request do_change_cloth img:{data['human_url'][:64]}, output_format:{data['output_format']}")
|
||||
task_data_str = json.dumps(task_data)
|
||||
pushStr2Queue(key, task_data_str)
|
||||
start_time = datetime.now()
|
||||
result_key = f"result_{key}"
|
||||
result_status_key = f"result_status_code_{key}"
|
||||
while (datetime.now() - start_time).seconds < DEFAULT_TIMEOUT:
|
||||
if redis_conn.exists(result_key):
|
||||
result_str = redis_conn.get(result_key)
|
||||
return result_str, int(redis_conn.get(result_status_key)), {'Content-Type': 'application/json'}
|
||||
time.sleep(0.1)
|
||||
|
||||
logger.error(f"request hairColor time out ")
|
||||
return jsonify({
|
||||
'msg': f'Timeout after time out'
|
||||
, "state":-1, "data":""
|
||||
}), 408
|
||||
|
||||
|
||||
@app.route('/change_cloth', methods=['POST'])
|
||||
def change_cloth():
|
||||
"""从 URL 下载图片"""
|
||||
@@ -521,35 +548,42 @@ def change_cloth():
|
||||
|
||||
output_format = data.get('output_format')
|
||||
if not output_format:
|
||||
return jsonify({"state":-1, "error": "Missing 'cloth_url' parameter"}), 500
|
||||
return jsonify({"state":-1, "error": "Missing 'output_format' parameter"}), 500
|
||||
|
||||
return queueCall(data)
|
||||
|
||||
@app.route('/change_cloth_base64', methods=['POST'])
|
||||
def change_cloth_base64():
|
||||
# 获取参数
|
||||
data = request.get_json()
|
||||
if not data:
|
||||
return jsonify({"ret":-1, "state":-1, 'msg': 'No JSON data provided'}), 400
|
||||
|
||||
human_img = data.get('human_img')
|
||||
cloth_img = data.get('cloth_img')
|
||||
output_format = data.get('output_format')
|
||||
if not output_format:
|
||||
return jsonify({"state":-1, "error": "Missing 'output_format' parameter"}), 500
|
||||
|
||||
key = str(uuid.uuid4())
|
||||
redis_conn = get_redis_conn()
|
||||
if not human_img or not cloth_img:
|
||||
return jsonify({"ret":-1, 'msg': 'Both human_img and cloth_img are required'}), 400
|
||||
|
||||
human_filename = save_base64_image(human_img, 'human')
|
||||
if not human_filename:
|
||||
return jsonify({"ret":-1, 'msg': 'Failed to save human image'}), 500
|
||||
|
||||
human_url = f"http://112.126.94.241:18888/static/imgs/{human_filename}"
|
||||
|
||||
task_data = {}
|
||||
task_data['key'] = key
|
||||
task_data['api'] = "/do_change_cloth"
|
||||
task_data['request'] = data
|
||||
logger.info(f"request do_change_cloth img:{data['human_url'][:64]}, output_format:{data['output_format']}")
|
||||
task_data_str = json.dumps(task_data)
|
||||
pushStr2Queue(key, task_data_str)
|
||||
timeout = DEFAULT_TIMEOUT
|
||||
start_time = datetime.now()
|
||||
result_key = f"result_{key}"
|
||||
result_status_key = f"result_status_code_{key}"
|
||||
while (datetime.now() - start_time).seconds < timeout:
|
||||
if redis_conn.exists(result_key):
|
||||
result_str = redis_conn.get(result_key)
|
||||
return result_str, int(redis_conn.get(result_status_key)), {'Content-Type': 'application/json'}
|
||||
time.sleep(0.1)
|
||||
|
||||
logger.error(f"request hairColor time out ")
|
||||
return jsonify({
|
||||
'msg': f'Timeout after {timeout} seconds, http time out'
|
||||
, "state":-1, "data":""
|
||||
}), 408
|
||||
# 保存服装图片
|
||||
cloth_filename = save_base64_image(cloth_img, 'cloth')
|
||||
if not cloth_filename:
|
||||
return jsonify({"ret":-1, 'msg': 'Failed to save cloth image'}), 500
|
||||
|
||||
cloth_url = f"http://112.126.94.241:18888/static/imgs/{cloth_filename}"
|
||||
|
||||
data["human_url"] = human_url
|
||||
data["cloth_url"] = cloth_url
|
||||
return queueCall(data)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -16,6 +16,7 @@ KEY_QUEUE_LOCK_NAME = 'KEY_QUEUE_LOCK_NAME'
|
||||
SERVER_LIST_LOCK_NAME = 'SERVER_LIST_LOCK_NAME'
|
||||
SERVER_LIST_LOG_LOCK_NAME = 'SERVER_LIST_LOG_LOCK_NAME'
|
||||
|
||||
|
||||
# 创建 logger
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO) # 设置 logger 的级别
|
||||
|
||||
+3
-3
@@ -72,13 +72,13 @@ def get_server_state():
|
||||
|
||||
@monitor.route('/')
|
||||
def serve_index():
|
||||
return send_from_directory('static', 'index.html')
|
||||
return send_from_directory('static', 'monitor.html')
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 启动Flask应用,启用多线程处理
|
||||
monitor.run(
|
||||
host='0.0.0.0',
|
||||
port=5001,
|
||||
threaded=True, # 启用多线程处理并发请求
|
||||
port=8018,
|
||||
threaded=False, # 启用多线程处理并发请求
|
||||
debug=False # 生产环境应设置为False
|
||||
)
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>服务器状态监控</title>
|
||||
<style>
|
||||
:root {
|
||||
--color-busy: #f39c12;
|
||||
--color-idle: #2ecc71;
|
||||
--color-normal: #2ecc71;
|
||||
--color-error: #e74c3c;
|
||||
--color-action: #3498db;
|
||||
--color-text: #333;
|
||||
--color-light-text: #7f8c8d;
|
||||
--color-bg: #f5f5f5;
|
||||
--color-card-bg: white;
|
||||
--color-event-bg: #fafafa;
|
||||
--color-event-item: white;
|
||||
}
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background-color: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
}
|
||||
h1 {
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.dashboard {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.controls {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 20px;
|
||||
gap: 10px;
|
||||
}
|
||||
.refresh-btn {
|
||||
padding: 8px 16px;
|
||||
background-color: #3498db;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
.refresh-btn:hover {
|
||||
background-color: #2980b9;
|
||||
}
|
||||
.refresh-btn:active {
|
||||
background-color: #1c6da8;
|
||||
}
|
||||
.refresh-info {
|
||||
text-align: center;
|
||||
margin: 0 auto 20px;
|
||||
padding: 10px;
|
||||
background-color: var(--color-card-bg);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
||||
max-width: 500px;
|
||||
}
|
||||
.server-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
.server-card {
|
||||
background-color: var(--color-card-bg);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 500px; /* 固定高度 */
|
||||
}
|
||||
.server-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
.server-name {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.server-status {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
.status-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
.status-indicator {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
margin-right: 8px;
|
||||
}
|
||||
.status-busy { background-color: var(--color-busy); }
|
||||
.status-idle { background-color: var(--color-idle); }
|
||||
.status-normal { background-color: var(--color-normal); }
|
||||
.status-error { background-color: var(--color-error); }
|
||||
.status-text {
|
||||
font-weight: bold;
|
||||
}
|
||||
.last-update {
|
||||
font-size: 12px;
|
||||
color: var(--color-light-text);
|
||||
}
|
||||
.events-section {
|
||||
margin-top: 10px;
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0; /* 重要:允许内部滚动 */
|
||||
}
|
||||
.events-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.events-title {
|
||||
font-weight: bold;
|
||||
}
|
||||
.event-count {
|
||||
background-color: var(--color-action);
|
||||
color: white;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.event-list {
|
||||
flex-grow: 1;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
background-color: var(--color-event-bg);
|
||||
}
|
||||
.event-item {
|
||||
margin-bottom: 10px;
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
background-color: var(--color-event-item);
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
||||
}
|
||||
.event-time {
|
||||
font-size: 12px;
|
||||
color: var(--color-light-text);
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.event-action {
|
||||
font-weight: bold;
|
||||
margin: 5px 0;
|
||||
color: var(--color-action);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.action-tag {
|
||||
background-color: #e1f5fe;
|
||||
color: #0288d1;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.event-data {
|
||||
font-size: 13px;
|
||||
word-break: break-all;
|
||||
white-space: pre-wrap;
|
||||
background-color: #f9f9f9;
|
||||
padding: 8px;
|
||||
border-radius: 3px;
|
||||
margin-top: 5px;
|
||||
font-family: monospace;
|
||||
max-height: 150px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.badge-busy {
|
||||
background-color: rgba(243, 156, 18, 0.1);
|
||||
color: var(--color-busy);
|
||||
}
|
||||
.badge-idle {
|
||||
background-color: rgba(46, 204, 113, 0.1);
|
||||
color: var(--color-idle);
|
||||
}
|
||||
.badge-normal {
|
||||
background-color: rgba(46, 204, 113, 0.1);
|
||||
color: var(--color-normal);
|
||||
}
|
||||
.badge-error {
|
||||
background-color: rgba(231, 76, 60, 0.1);
|
||||
color: var(--color-error);
|
||||
}
|
||||
.badge-success {
|
||||
background-color: rgba(46, 204, 113, 0.1);
|
||||
color: var(--color-normal);
|
||||
}
|
||||
.badge-failure {
|
||||
background-color: rgba(231, 76, 60, 0.1);
|
||||
color: var(--color-error);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="dashboard">
|
||||
<h1>服务器状态监控</h1>
|
||||
<div class="controls">
|
||||
<button class="refresh-btn" id="refreshBtn">手动刷新数据</button>
|
||||
</div>
|
||||
<div class="refresh-info">
|
||||
最后更新时间: <strong id="lastUpdateTime">-</strong>
|
||||
</div>
|
||||
<div class="server-grid" id="serverContainer">
|
||||
<!-- 服务器卡片将在这里动态生成 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 获取DOM元素
|
||||
const refreshBtn = document.getElementById('refreshBtn');
|
||||
const lastUpdateTime = document.getElementById('lastUpdateTime');
|
||||
const serverContainer = document.getElementById('serverContainer');
|
||||
|
||||
// 获取服务器状态数据
|
||||
async function fetchServerStatus() {
|
||||
try {
|
||||
const response = await fetch('http://112.126.94.241:18018/get_server_state');
|
||||
if (!response.ok) throw new Error('网络响应不正常');
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('获取服务器状态失败:', error);
|
||||
alert('获取数据失败: ' + error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化JSON数据
|
||||
function formatData(data) {
|
||||
if (typeof data === 'string') return data;
|
||||
try {
|
||||
return JSON.stringify(data, null, 2);
|
||||
} catch {
|
||||
return String(data);
|
||||
}
|
||||
}
|
||||
|
||||
// 判断服务器状态
|
||||
function getServerStatus(server) {
|
||||
const now = Date.now() / 1000;
|
||||
const lastEventTime = server.last_event?.time || 0;
|
||||
|
||||
// 忙碌状态
|
||||
const busyStatus = {
|
||||
status: server.busy ? 'busy' : 'idle',
|
||||
text: server.busy ? '忙碌' : '空闲',
|
||||
indicatorClass: server.busy ? 'status-busy' : 'status-idle',
|
||||
badgeClass: server.busy ? 'badge-busy' : 'badge-idle'
|
||||
};
|
||||
|
||||
// 连接状态 (5分钟判断)
|
||||
const isNormal = (now - lastEventTime) < (5*60 + 10);
|
||||
const connectStatus = {
|
||||
status: isNormal ? 'normal' : 'error',
|
||||
text: isNormal ? '活跃' : '不活跃',
|
||||
indicatorClass: isNormal ? 'status-normal' : 'status-error',
|
||||
badgeClass: isNormal ? 'badge-normal' : 'badge-error'
|
||||
};
|
||||
|
||||
// 上次运行状态
|
||||
const hasLastCall = server.hasOwnProperty('last_call');
|
||||
const lastCallStatus = {
|
||||
status: hasLastCall && server.last_call === 'success' ? 'success' : 'failure',
|
||||
text: hasLastCall && server.last_call === 'success' ? '成功' : '失败',
|
||||
indicatorClass: hasLastCall && server.last_call === 'success' ? 'status-normal' : 'status-error',
|
||||
badgeClass: hasLastCall && server.last_call === 'success' ? 'badge-success' : 'badge-failure'
|
||||
};
|
||||
|
||||
return { busyStatus, connectStatus, lastCallStatus };
|
||||
}
|
||||
|
||||
// 创建服务器卡片
|
||||
function createServerCard(server) {
|
||||
const status = getServerStatus(server);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'server-card';
|
||||
card.innerHTML = `
|
||||
<div class="server-header">
|
||||
<div class="server-name">${server.name}</div>
|
||||
</div>
|
||||
<div class="server-status">
|
||||
<div class="status-item">
|
||||
<span class="status-indicator ${status.busyStatus.indicatorClass}"></span>
|
||||
<span class="status-text">运行状态: <span class="status-badge ${status.busyStatus.badgeClass}">${status.busyStatus.text}</span></span>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<span class="status-indicator ${status.connectStatus.indicatorClass}"></span>
|
||||
<span class="status-text">活跃状态: <span class="status-badge ${status.connectStatus.badgeClass}">${status.connectStatus.text}</span></span>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<span class="status-indicator ${status.lastCallStatus.indicatorClass}"></span>
|
||||
<span class="status-text">上次运行: <span class="status-badge ${status.lastCallStatus.badgeClass}">${status.lastCallStatus.text}</span></span>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<span class="last-update">最后活动: ${server.last_event?.time_str || '无记录'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="events-section">
|
||||
<div class="events-header">
|
||||
<div class="events-title">事件记录</div>
|
||||
<div class="event-count">${server.events.length}条</div>
|
||||
</div>
|
||||
<div class="event-list">
|
||||
${server.events.map(event => `
|
||||
<div class="event-item">
|
||||
<div class="event-time">${event.time_str}</div>
|
||||
<div class="event-action">
|
||||
<span>${event.action}</span>
|
||||
<span class="action-tag">${event.action}</span>
|
||||
</div>
|
||||
<div class="event-data">${formatData(event.data)}</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
// 更新整个UI
|
||||
async function updateUI() {
|
||||
refreshBtn.disabled = true;
|
||||
refreshBtn.textContent = '加载中...';
|
||||
|
||||
const servers = await fetchServerStatus();
|
||||
|
||||
if (servers && servers.length > 0) {
|
||||
serverContainer.innerHTML = '';
|
||||
servers.forEach(server => {
|
||||
const card = createServerCard(server);
|
||||
serverContainer.appendChild(card);
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
lastUpdateTime.textContent = now.toLocaleString();
|
||||
}
|
||||
|
||||
refreshBtn.disabled = false;
|
||||
refreshBtn.textContent = '手动刷新数据';
|
||||
}
|
||||
|
||||
// 添加事件监听
|
||||
refreshBtn.addEventListener('click', updateUI);
|
||||
|
||||
// 初始加载
|
||||
updateUI();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -8,7 +8,7 @@ import threading
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from config import REDIS_HOST
|
||||
from config import REDIS_HOST, DEFAULT_TIMEOUT
|
||||
from config import REDIS_PORT
|
||||
from config import REDIS_DB
|
||||
from config import QUEUE_NAME
|
||||
@@ -201,7 +201,7 @@ def call_remote_gpu_server(task_data_str, server=None):
|
||||
if data['output_format'] == 'base64':
|
||||
base64 = True
|
||||
|
||||
response = requests.post(url, headers=headers, json=data, timeout=30)
|
||||
response = requests.post(url, headers=headers, json=data, timeout=DEFAULT_TIMEOUT)
|
||||
|
||||
logger.info(f"call finshed {response.status_code} {response.headers} {response.text[:128]}")
|
||||
if response.status_code == 200:
|
||||
@@ -260,9 +260,9 @@ def call_remote_gpu_server(task_data_str, server=None):
|
||||
result_status_code = '500'
|
||||
|
||||
result_key = f"result_{key}"
|
||||
redis_conn.set(result_key, result_str, ex=60)
|
||||
redis_conn.set(result_key, result_str, ex=DEFAULT_TIMEOUT)
|
||||
result_status_key = f"result_status_code_{key}"
|
||||
redis_conn.set(result_status_key, result_status_code, ex=60)
|
||||
redis_conn.set(result_status_key, result_status_code, ex=DEFAULT_TIMEOUT)
|
||||
|
||||
|
||||
def get_task_queue_key():
|
||||
@@ -315,7 +315,6 @@ if __name__ == '__main__':
|
||||
print(f"[Worker] Starting with PID: {os.getpid()}")
|
||||
redis_conn.set(GPU_SERVER_LIST, "[]")
|
||||
|
||||
servers = regServer("localhost")
|
||||
for s in servers:
|
||||
regServer(s)
|
||||
regServer("localhost")
|
||||
|
||||
main_worker()
|
||||
Reference in New Issue
Block a user