Files
SimpleFarm/farm/server/daemon.py
T
snowy-yang f8e093c98f feat: 实时通道改 SSE、服务器换 uvicorn+zttp、节奏改 40 分钟一天,并重建测试与优化热路径
三件事凑成一次不兼容变更:WebSocket 通道、Hypercorn 服务器、「手动推进一天」都消失了。

实时通道:WebSocket -> SSE
- hub 改为 SSE 订阅池,GET /api/stream 单向推送 welcome/state/day/notice/bye,
  250ms 节流 + 15s 心跳注释;写操作一律走 HTTP POST /api/actions,不再有 WS 回执。
- 停机三处一起修才干净:close_all() 发 bye + timeout_graceful_shutdown 兜底 +
  客户端 stop() 直接 shutdown 底层 socket(光 close() 会等读线程的锁,最长卡到下次心跳)。
- 网页版改 EventSource + fetch;tools/ws_demo.py 换成 tools/sse_demo.py。

服务器:Hypercorn -> uvicorn + zttp 的 HTTP/2
- 同一端口同时说 HTTP/1.1 与 HTTP/2。uvicorn 0.53 不再内置 h2,必须装 zttp 并显式
  http="zttp",否则 Config.load() 直接 raise。
- 信号接管改成子类覆盖 Server.handle_exit(0.53 没有 install_signal_handlers 可覆盖),
  不调 super()、不写 _captured_signals,退出时不重放信号;第二次信号强制退出。
- 入口启动前用 daemon.port_busy() 自检端口:Windows 上 SO_REUSEADDR 会让第二个实例
  「绑上」已监听端口并抢走新连接,所以判断「能不能连上」而不是「能不能 bind」。
- 修掉 clear_pid_file 的 Windows 真 bug:文件还开着就 os.remove 会失败且被
  except OSError 吞掉,导致每次正常退出都留 stale pid 文件。

节奏:一天 15 秒 -> 40 分钟,并整体移除「休息」
- DEFAULT_TICK_SECONDS=2400,MAX_TICK_SECONDS 放宽到 86400(旧上限会把 40 分钟夹回去)。
- engine.sleep / SLEEP_COOLDOWN / /api/sleep / TUI 的 [N]休息 / 网页版按钮全部删掉,
  时间只能自然流动;机器人改为 wait_for_next_day(timeout),CLI 加 bot --wait。
- 时长显示统一走 models.format_duration(),不再出现 2399.6s 这种写法。

键盘:修复方向键/空格/Tab/ESC 全部静默失效
- keys.py 的具名键统一小写并成为唯一来源,tui.py 一律引用 keys.XXX 而不手写字符串
  (历史 bug 就是 Windows 侧产大写 UP、TUI 里写小写 up,字母键正常所以很难发现)。
- 顺带修 POSIX 路径一次 os.read 只取首字节、其余按键静默丢弃的老毛病。

测试:重建 500 项
- test_engine 110 / test_actions 35 / test_server 131(skip 35) / test_tui_keys 75 /
  test_bot 36 / test_client 113。未安装的第三方依赖用 skipUnless 自动跳过,其余照跑,
  所以是全绿而不是靠跳过伪装。
- 被测试逼出两处真隐患并修掉:RemoteFarm._normalize() 必须「先补 scheme 再削尾斜杠」
  (顺序反了畸形端点会溜到系统代理、报一个和真实原因无关的 502);StateView 空视图要
  预置 plots/animals,否则连不上服务器时读 state.plots 直接 AttributeError。

优化:先量后改,依据与前后数字都在 tools/bench.py
- 新增 engine.brief_source():brief/summary/动作回执只要十几个标量,不再为它们序列化
  整局;to_dict 里 net_worth 只算一次。brief -76%、summary -77%、leaderboard(32) -78%、
  GET /api/world -31%、POST /api/actions?full=1 -16%。
- 拆掉三个巨型函数:create_app 475->32 行(_Services + _register_*)、
  build_parser 与 available_actions 分组、__main__.main 160->7 行。
- 消除重复:等级门槛 5 处 -> _is_locked/_require_level/_newly_unlocked;hub 的
  broadcast/broadcast_all/close_all -> _push_many;daemon.probe/world -> _get_json;
  main.py 的 _add_endpoint_args/_leaderboard_lines。
- tools/bench.py 作为长期性能守卫(含调用计数器),谁把轻量路径改回 snapshot() 会立刻报警。

门禁:ruff format/check 全绿、pyright 0 错误、500 项测试 OK(skip 35)。
2026-09-19 12:55:45 +08:00

381 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""守护进程管理:把服务器丢到后台跑,然后像服务一样 start / stop / status。
为什么不用 nohup 或 systemd
---------------------------
需求是"允许后台运行",而这个项目要能在 Windows / macOS / Linux 上都直接跑,
不能依赖某个平台的服务管理器。所以这里用最朴素也最通用的办法:
* ``subprocess.Popen`` 拉起一个**脱离父进程**的子进程(POSIX 用新会话,
Windows 用 DETACHED_PROCESS),父进程退出后它继续活着;
* 用 ``run/server.pid`` 记住它的 pid,用 ``run/server.log`` 收走它的输出;
* 停的时候先试着走 HTTP 优雅停机(能落盘),失败再发信号。
这套做法不依赖任何第三方库,也不需要管理员权限。
"""
from __future__ import annotations
import contextlib
import json
import os
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
from .. import net
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
RUN_DIR = os.path.join(PROJECT_ROOT, "run")
DEFAULT_PID_FILE = os.path.join(RUN_DIR, "server.pid")
DEFAULT_LOG_FILE = os.path.join(RUN_DIR, "server.log")
_STILL_ACTIVE = 259
def pid_alive(pid: int) -> bool:
"""跨平台地判断一个 pid 是否还活着。
注意:Windows 上 ``os.kill(pid, 0)`` 会**真的**把进程杀掉
(CPython 用 TerminateProcess 实现),所以这里必须走 Win32 API。
"""
if pid <= 0:
return False
if os.name == "nt":
import ctypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(0x1000, False, pid) # QUERY_LIMITED_INFORMATION
if not handle:
return False
try:
code = ctypes.c_ulong()
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
return False
return code.value == _STILL_ACTIVE
finally:
kernel32.CloseHandle(handle)
try:
os.kill(pid, 0)
except (OSError, ProcessLookupError):
return False
return True
def port_busy(host: str, port: int, timeout: float = 0.6) -> bool:
"""端口上已经有程序在监听了吗。
用"能不能连上"判断,而不是"能不能 bind":Windows 上只要两边都设了
``SO_REUSEADDR``(uvicorn 会设),第二个进程也能绑上同一个
端口、然后抢走新连接——于是 bind 探测会给出一个自信的错误答案。
"""
if host in ("0.0.0.0", ""):
target = "127.0.0.1"
elif host == "::":
target = "::1"
else:
target = host
try:
with socket.create_connection((target, port), timeout=timeout):
return True
except OSError:
return False
class DaemonManager:
"""负责在后台拉起/停止 ``farm.server`` 进程。"""
def __init__(
self,
host: str = "127.0.0.1",
port: int = 8765,
token: str | None = None,
tick: float = 15.0,
save_dir: str = "",
pid_file: str = DEFAULT_PID_FILE,
log_file: str = DEFAULT_LOG_FILE,
python: str | None = None,
) -> None:
self.host = host
self.port = port
self.token = token
self.tick = tick
self.save_dir = save_dir or os.path.join(PROJECT_ROOT, "saves")
# 防御式默认:调用方传 None 时用标准位置,绝不让 pid_file 变成 None
self.pid_file = pid_file or DEFAULT_PID_FILE
self.log_file = log_file or DEFAULT_LOG_FILE
self.python = python or sys.executable
# ------------------------------------------------------------ pid 文件
def read_pid(self) -> int | None:
try:
with open(self.pid_file, encoding="utf-8") as handle:
return int(handle.read().strip())
except (OSError, ValueError):
return None
def write_pid(self, pid: int) -> None:
os.makedirs(os.path.dirname(self.pid_file), exist_ok=True)
with open(self.pid_file, "w", encoding="utf-8") as handle:
handle.write(str(pid))
def clear_pid(self) -> None:
with contextlib.suppress(OSError):
os.remove(self.pid_file)
def current(self) -> int | None:
"""返回正在运行的服务器 pid;pid 文件过期则顺手清理。"""
pid = self.read_pid()
if pid is None:
return None
if pid_alive(pid):
return pid
self.clear_pid()
return None
# ------------------------------------------------------------ 探测
def _get_json(self, path: str, timeout: float, token: bool = False) -> dict[str, Any] | None:
"""访问自己这个服务的某个接口;连不上或回包不是 JSON 就返回 None。
一律走 :func:`farm.net.open_url`:本地回环请求不能被系统代理截走,
否则在设了 ``HTTP_PROXY`` 的机器上会得到莫名其妙的 502。
末尾那道 ``isinstance`` 是为了让返回类型名副其实——回包万一是个数组,
调用方的 ``.get(...)`` 会直接崩在属性访问上。
"""
url = f"http://{self.host}:{self.port}{path}"
if token and self.token:
url += "?token=" + urllib.parse.quote(self.token)
try:
with net.open_url(url, timeout=timeout) as response:
payload = json.loads(response.read().decode("utf-8"))
except (urllib.error.URLError, OSError, ValueError):
return None
return payload if isinstance(payload, dict) else None
def probe(self, timeout: float = 1.5) -> dict[str, Any] | None:
"""访问 /api/health,成功说明服务真的在监听。"""
return self._get_json("/api/health", timeout)
def world(self, timeout: float = 2.0) -> dict[str, Any] | None:
return self._get_json("/api/world", timeout, token=True)
def port_busy(self) -> bool:
"""端口被别的程序占了吗(用于给出"换端口"的提示)。"""
return port_busy(self.host, self.port)
# ------------------------------------------------------------ 启动
def command(self) -> list[str]:
args = [
self.python,
"-m",
"farm.server",
"--host",
self.host,
"--port",
str(self.port),
"--tick",
str(self.tick),
"--save-dir",
self.save_dir,
# 关键:pid 文件由**服务进程自己**写。
# Windows 上 venv 的 python.exe 可能是个转发器,父进程拿到的 pid
# 未必是真正在监听端口的那个进程,写错 pid 会导致 stop 杀错人。
"--pid-file",
self.pid_file,
]
if self.token:
args += ["--token", self.token]
return args
def start(self, wait: float = 12.0) -> tuple[bool, str]:
existing = self.current()
if existing is not None:
return False, f"服务器已经在运行(pid {existing}),无需重复启动"
if self.probe() is not None:
return False, f"端口 {self.port} 上已经有一个 SimpleFarm 服务器在跑"
if self.port_busy():
return False, f"端口 {self.port} 被其它程序占用,请改用 --port 8899"
os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
os.makedirs(os.path.dirname(self.pid_file), exist_ok=True)
self.clear_pid() # 清掉上一次留下的陈旧 pid
env = dict(os.environ)
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONIOENCODING"] = "utf-8"
env["PYTHONPATH"] = PROJECT_ROOT + os.pathsep + env.get("PYTHONPATH", "")
kwargs: dict[str, Any] = {
"cwd": PROJECT_ROOT,
"env": env,
"stdin": subprocess.DEVNULL,
}
if os.name == "nt":
# DETACHED_PROCESS:父进程退出后子进程继续活;
# CREATE_NEW_PROCESS_GROUP:方便单独给它发 Ctrl+Break
kwargs["creationflags"] = (
subprocess.DETACHED_PROCESS
| subprocess.CREATE_NEW_PROCESS_GROUP
| getattr(subprocess, "CREATE_NO_WINDOW", 0)
)
else:
kwargs["start_new_session"] = True
# 日志交给子进程自己写文件:父进程退出后文件描述符依然有效。
# 用 with 管理句柄:Popen 已经把 fd 复制给子进程,父进程这边可以安全关闭。
with open(self.log_file, "a", encoding="utf-8") as log_handle:
try:
process = subprocess.Popen(
self.command(),
stdout=log_handle,
stderr=log_handle,
**kwargs,
)
except OSError as exc:
return False, f"启动失败:{exc}"
# 等它真的能响应,而不是"进程起来了但端口还没监听"
deadline = time.time() + wait
while time.time() < deadline:
if self.probe() is not None:
pid = self.current() or process.pid
return True, (
f"服务器已在后台启动(pid {pid})\n"
f" 网页 http://{self.host}:{self.port}/\n"
f" 日志 {self.log_file}\n"
f" 停止 uv run main.py stop"
)
if process.poll() is not None and self.read_pid() is None:
return False, (
f"服务器进程启动后立刻退出(退出码 {process.returncode})。"
f"日志:{self.log_file}"
)
time.sleep(0.25)
return False, (f"服务器进程已启动但 {wait:.0f} 秒内没响应。请查看日志:{self.log_file}")
# ------------------------------------------------------------ 停止
def stop(self, force: bool = False) -> tuple[bool, str]:
pid = self.current()
online = self.probe() is not None
if pid is None and not online:
self.clear_pid()
return True, "服务器当前没有运行"
# 先请它自己优雅退出:这条路会把所有牧场写进存档
if online and self._request_shutdown() and self._wait_offline(pid, 8.0):
self.clear_pid()
return True, f"服务器已优雅停机(pid {pid or '未知'},所有牧场已存档)"
if pid is None:
return False, (
f"服务器仍在 {self.host}:{self.port} 上响应,但 pid 文件里没有记录,"
"无法确认该结束哪个进程。请手动处理,或用 docker/任务管理器结束它。"
)
try:
os.kill(pid, signal.SIGTERM)
except OSError as exc:
self.clear_pid()
return False, f"发送停止信号失败:{exc}"
if self._wait_offline(pid, 5.0):
self.clear_pid()
return True, f"服务器已停止(pid {pid})"
if force and os.name == "nt":
subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)], capture_output=True, check=False
)
if self._wait_offline(pid, 3.0):
self.clear_pid()
return True, f"服务器已强制结束(pid {pid})"
elif force:
with contextlib.suppress(OSError):
os.kill(pid, signal.SIGKILL)
if self._wait_offline(pid, 3.0):
self.clear_pid()
return True, f"服务器已强制结束(pid {pid})"
return False, (
f"进程 {pid} 没有在超时内退出。"
+ ("" if force else "可加 --force 强制结束。")
+ f" 日志:{self.log_file}"
)
def restart(self) -> tuple[bool, str]:
stopped, message = self.stop()
if not stopped:
return False, message
return self.start()
def _request_shutdown(self) -> bool:
url = f"http://{self.host}:{self.port}/api/admin/shutdown"
if self.token:
url += "?token=" + urllib.parse.quote(self.token)
request = urllib.request.Request(
url, data=b"{}", method="POST", headers={"Content-Type": "application/json"}
)
try:
with net.open_url(request, timeout=3.0) as response:
return response.status == 200
except (urllib.error.URLError, OSError):
return False
@staticmethod
def _wait_gone(pid: int, seconds: float) -> bool:
deadline = time.time() + seconds
while time.time() < deadline:
if not pid_alive(pid):
return True
time.sleep(0.2)
return not pid_alive(pid)
def _wait_offline(self, pid: int | None, seconds: float) -> bool:
"""等到进程消失 **且** 端口不再响应。
两件事都要等:进程可能已经死了但端口还被 TIME_WAIT 占着,
也可能 pid 文件缺失(拿不到 pid),那就只看端口。
"""
deadline = time.time() + seconds
while time.time() < deadline:
process_gone = pid is None or not pid_alive(pid)
if process_gone and self.probe(timeout=0.6) is None:
return True
time.sleep(0.25)
process_gone = pid is None or not pid_alive(pid)
return process_gone and self.probe(timeout=0.6) is None
# ------------------------------------------------------------ 状态
def status(self) -> dict[str, Any]:
pid = self.current()
health = self.probe()
info: dict[str, Any] = {
"pid": pid,
"running": pid is not None or health is not None,
"host": self.host,
"port": self.port,
"log_file": self.log_file,
"pid_file": self.pid_file,
"health": health,
}
if health:
info["url"] = f"http://{self.host}:{self.port}/"
info["farms"] = health.get("farms")
info["clients"] = health.get("clients")
info["uptime"] = health.get("uptime")
return info
def tail(self, lines: int = 40) -> list[str]:
try:
with open(self.log_file, encoding="utf-8", errors="replace") as handle:
return handle.read().splitlines()[-lines:]
except OSError:
return []