-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
117 lines (98 loc) · 3.35 KB
/
main.py
File metadata and controls
117 lines (98 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""FastAPI 应用入口 - Uvicorn 启动点"""
import logging
import signal
import sys
import subprocess
import platform
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s] %(levelname)s - %(name)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def is_port_in_use(port: int) -> bool:
"""检查端口是否被占用
Args:
port: 端口号
Returns:
True 如果端口已被占用,False 如果端口空闲
"""
try:
if platform.system() == 'Windows':
result = subprocess.run(
['netstat', '-ano'],
capture_output=True,
text=True,
encoding='gbk',
errors='ignore'
)
for line in result.stdout.splitlines():
parts = line.split()
# 只检查 LISTENING 状态,忽略 TIME_WAIT 等
if len(parts) >= 6 and f':{port}' in parts[1] and 'LISTENING' in parts[5]:
return True
else:
result = subprocess.run(
['lsof', '-ti', f':{port}'],
capture_output=True,
text=True
)
if result.returncode == 0:
return True
return False
except Exception:
return False
def get_config_port() -> int:
"""从配置文件读取端口号,不初始化 app"""
try:
import yaml
import os
from app.config import ConfigDefaults
defaults = ConfigDefaults()
config_path = os.getenv('GETCHAT_CONFIG', 'config.yaml')
# 检查本地配置覆盖
local_config_path = config_path.replace('.yaml', '.local.yaml')
if os.path.exists(local_config_path):
config_path = local_config_path
with open(config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
return config.get('app', {}).get('port', defaults.app_port)
except Exception:
from app.config import ConfigDefaults
defaults = ConfigDefaults()
return defaults.app_port
if __name__ == '__main__':
# 在创建 app 之前先检查端口
port = get_config_port()
if is_port_in_use(port):
logger.warning(f'[Port] 端口 {port} 已被占用,服务可能已在运行')
sys.exit(1)
# 导入 FastAPI 应用
import uvicorn
from app import create_fastapi_app
# 创建 FastAPI 应用
app = create_fastapi_app()
# 从配置读取启动参数
import os
from config import load_config
config, _ = load_config()
host = config.get_str('app.host', '0.0.0.0')
port = config.get_int('app.port', 7333)
debug_mode = config.get_bool('app.debug_mode', False)
logger.info(f"[FastAPI] 启动服务 | host: {host} | port: {port} | debug_mode: {debug_mode}")
# 注册信号处理
def signal_handler(sig, frame):
logger.info(f"[Shutdown] 收到信号 {sig},关闭服务...")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# 启动 Uvicorn(禁用 reload 以支持直接运行 app 对象)
uvicorn.run(
app,
host=host,
port=port,
reload=False, # 禁用 reload,支持直接运行 app 对象
log_level="info",
access_log=True
)