Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(tray): 托盘把子服务挂进 kill-on-close Job,重启先等旧服务退净,端口被孤儿占着时开工前就拒绝

longmeidaofd24993768f7
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index bd5c89e1c..b23465929 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -199,7 +199,8 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt
什么时候用这条:代码已经在检出里、只要让运行中的托盘重新加载,不换二进制。
- 不要用 Computer Use 点托盘。`python scripts/restart_windows_tray.py` 按精确 EXE 路径找到 pystray 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务。
-- 找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。
+- 找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。旧托盘退出后还要等它名下的子服务退净才起新托盘;端口若被不归旧托盘管的 `serve` 进程占着,开工前就拒绝并报出它们的 PID,因为换托盘换不掉它们。
+- 托盘把自己拉起的子服务挂进 kill-on-close Job:托盘被 `Stop-Process -Force` 之类强杀时,内核关句柄,整棵 `serve` 子树一起退,不留孤儿继续占 80/443 跑旧代码。托盘每轮健康检查发现端口暗了会补拉;见到健康却不归自己的服务只记 warning、不接管。启动与补拉记在 `<数据根>/logs/tray.log`。
- `--swap-from <暂存包>` 让它在旧托盘退出后、新托盘启动前顺手换掉二进制,那是整个换包过程中唯一一个目标文件没有进程持有的窗口。换生产二进制走 `deploy_windows_tray.py`,不要单独调它。
- 打包托盘窗口不在时命令自动改走源码托盘:`find_source_tray_windows()` 按同一窗口类名加「命令行含 `peach.tray`」认源码托盘,`restart_source_tray()` 照抄原命令行(含 `--show`/数据根)等托盘退出后自起,不换包不备份;`--source` 显式跳过打包入口。
diff --git a/scripts/restart_windows_tray.py b/scripts/restart_windows_tray.py
index aea4235f3..134ece268 100644
--- a/scripts/restart_windows_tray.py
+++ b/scripts/restart_windows_tray.py
@@ -18,7 +18,7 @@ if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from peach.windows_restart import (
- find_tray_windows, restart_source_tray, restart_tray,
+ DEFAULT_TIMEOUT, find_tray_windows, restart_source_tray, restart_tray,
)
@@ -26,7 +26,7 @@ def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="静默无窗口地重启 Windows Peach 托盘及子服务")
parser.add_argument("--target", type=Path,
default=PROJECT_ROOT / "dist" / "Peach" / "Peach.exe")
- parser.add_argument("--timeout", type=float, default=25.0)
+ parser.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT)
parser.add_argument("--source", action="store_true",
help="重启源码部署的托盘(pythonw -m peach.tray),不做换包")
parser.add_argument("--swap-from", type=Path, default=None,
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index b4dc9c0ad..559d624bc 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -110,7 +110,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_link_repair.py",
"test_subprocess_encoding.py", "test_module_layering.py",
"test_copy_final_state.py", "test_demo_dataset.py",
- "test_cloudflared_packaging.py", "test_tunnel.py"),
+ "test_cloudflared_packaging.py", "test_tunnel.py", "test_process_job.py"),
# 前端 island 层(ADR-0022)。产物与源码的断言不需要 Node;vitest 那部分在没有
# npm 时自己跳过,所以这个域在任何机器上都能跑,`full` 也就自动包含它。
# `test_web_perf.py` 两个域都登记:压缩与 ETag 是 API 交付(catalog),
@@ -157,6 +157,8 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"src/peach/routes_pages.py": ("catalog", "tooling", "web"),
# 托盘既是 sync 域的服务编排,也被版本与桌面设置那些 tooling 测试读源码。
"src/peach/tray.py": ("sync", "tooling"),
+ # 托盘子服务与隧道的 cloudflared 共用这份 Job Object;两边的测试都要跑到。
+ "src/peach/process_job.py": ("tooling", "sync"),
"src/peach/jav_poster_crop.py": ("metadata", "web"),
# genre 词表按名字只推得出 metadata。复核队列与 API 那两处的用例拿「词表没收的词」
# 当素材:词表一收那个词,`test_web_review.py`(catalog)与 `test_fastapi_api.py`
diff --git a/src/peach/process_job.py b/src/peach/process_job.py
new file mode 100644
index 000000000..f6fd6acd6
--- /dev/null
+++ b/src/peach/process_job.py
@@ -0,0 +1,105 @@
+"""随句柄关闭一并终止成员的 Windows Job Object。
+
+父进程被强杀时不会走自己的收尾代码,子进程于是成了孤儿,继续占着端口或留在公网上转发。
+把子进程挂进一个 `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` 的 Job,句柄随父进程退出由内核关闭,
+成员随之一并终止,不管父进程是怎么死的。托盘的 `peach serve` 子服务与服务里的
+cloudflared 都用这一份。非 Windows 上三个函数都是空操作。
+"""
+from __future__ import annotations
+
+import ctypes
+import os
+
+__all__ = ["assign_to_job", "close_job", "create_kill_on_close_job"]
+
+_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
+#: JobObjectExtendedLimitInformation
+_JOB_EXTENDED_LIMIT_CLASS = 9
+
+
+def create_kill_on_close_job():
+ """建一个随句柄关闭一并终止成员的 Job Object;非 Windows 或建不成时返回 None。
+
+ 句柄不可继承:子进程要是继承了它,Job 就要等到最后一个子进程退出才关,
+ 父进程死了成员也不会被收走。
+ """
+ if os.name != "nt":
+ return None
+ from ctypes import wintypes
+
+ class _IoCounters(ctypes.Structure):
+ _fields_ = [(name, ctypes.c_ulonglong) for name in (
+ "ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
+ "ReadTransferCount", "WriteTransferCount", "OtherTransferCount",
+ )]
+
+ class _BasicLimits(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+ class _ExtendedLimits(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", _BasicLimits),
+ ("IoInfo", _IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
+ kernel32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)
+ job = kernel32.CreateJobObjectW(None, None)
+ if not job:
+ return None
+ limits = _ExtendedLimits()
+ limits.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not kernel32.SetInformationJobObject(
+ wintypes.HANDLE(job), _JOB_EXTENDED_LIMIT_CLASS,
+ ctypes.byref(limits), ctypes.sizeof(limits),
+ ):
+ kernel32.CloseHandle(wintypes.HANDLE(job))
+ return None
+ return job
+
+
+def assign_to_job(job, process) -> None:
+ """把一个 `subprocess.Popen` 挂进 Job;挂不上照样放行。
+
+ 内核拒绝嵌套 Job 时子进程仍然在跑,调用方自己的停止路径照旧收得掉它,
+ 只是少了强杀时的那层兜底。
+ """
+ if job is None or os.name != "nt":
+ return
+ handle = getattr(process, "_handle", None)
+ if handle is None:
+ return
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ try:
+ kernel32.AssignProcessToJobObject(wintypes.HANDLE(job), wintypes.HANDLE(int(handle)))
+ except (OSError, ValueError, TypeError):
+ pass
+
+
+def close_job(job) -> None:
+ """关掉 Job 句柄;这一下就会终止里面还活着的成员。"""
+ if job is None or os.name != "nt":
+ return
+ from ctypes import wintypes
+
+ try:
+ ctypes.WinDLL("kernel32", use_last_error=True).CloseHandle(wintypes.HANDLE(job))
+ except (OSError, ValueError):
+ pass
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 973149a8d..72597a0c3 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -30,6 +30,7 @@ from .config import (
from .mdns import lan_ipv4
from .netwatch import NetworkChangeWatcher
from .mount import mount_share as mount_smb_share
+from .process_job import assign_to_job, create_kill_on_close_job
from .sync import COPY_ACTIONS, SyncPlan, device_id, resolve
from .versioning import VersionManager, VersionSnapshot
from .windows_update import (
@@ -218,7 +219,9 @@ class ServiceManager:
self._ledger_plan = ledger_plan or self._current_ledger_plan
self._mount_share = mount_share or self._mount_shared_root
self._owned: dict[str, subprocess.Popen] = {}
- self._logs: list[object] = []
+ # 子服务都挂进这个 Job:托盘被强杀时句柄由内核关闭,整棵 `peach serve` 一起收掉,
+ # 不会留下孤儿继续占着 80/443,让下一份托盘见端口健康就不拉自己的。
+ self._job = None
self._last_health: dict[str, tuple[bool, str]] = {
spec.name: (False, "未检测") for spec in specs
}
@@ -295,21 +298,30 @@ class ServiceManager:
if owned is not None and owned.poll() is None:
continue
if self.healthy(spec):
+ if owned is None:
+ logging.getLogger(__name__).warning(
+ "%s 端口上已有健康服务,但不是本托盘拉起的,未接管", spec.name)
continue
- stdout = (self._log_dir / f"tray-{spec.name}.out.log").open("ab")
- stderr = (self._log_dir / f"tray-{spec.name}.err.log").open("ab")
- self._logs.extend((stdout, stderr))
+ if self._job is None:
+ self._job = create_kill_on_close_job()
+ # 日志句柄交给子进程后父进程这一份就关掉:服务反复被补拉时不会越攒越多。
creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
- self._owned[spec.name] = self._popen(
- list(spec.command),
- cwd=str(PROJECT_ROOT),
- stdin=subprocess.DEVNULL,
- stdout=stdout,
- stderr=stderr,
- shell=False,
- creationflags=creationflags,
- env=environment,
- )
+ with (self._log_dir / f"tray-{spec.name}.out.log").open("ab") as stdout, \
+ (self._log_dir / f"tray-{spec.name}.err.log").open("ab") as stderr:
+ process = self._popen(
+ list(spec.command),
+ cwd=str(PROJECT_ROOT),
+ stdin=subprocess.DEVNULL,
+ stdout=stdout,
+ stderr=stderr,
+ shell=False,
+ creationflags=creationflags,
+ env=environment,
+ )
+ assign_to_job(self._job, process)
+ self._owned[spec.name] = process
+ logging.getLogger(__name__).info(
+ "拉起 %s 服务,PID %s", spec.name, getattr(process, "pid", "?"))
def wait_until_ready(self, timeout: float = 20.0) -> bool:
deadline = time.monotonic() + timeout
@@ -344,10 +356,6 @@ class ServiceManager:
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=3)
- if name is None:
- for handle in self._logs:
- handle.close()
- self._logs.clear()
def restart(self) -> bool:
self.stop_owned()
@@ -1067,11 +1075,30 @@ class PeachTray:
return
# 先看首次设置有没有完成:切换会换掉 `manager.specs`,采样必须落在换完之后。
self.gate.poll()
- for spec in self.manager.specs:
- self.manager.healthy(spec)
+ down = [spec for spec in self.manager.specs if not self.manager.healthy(spec)]
+ if down:
+ self.revive_services()
self.icon.update_menu()
self.poll_build_age()
+ def revive_services(self) -> bool:
+ """有服务不健康、又不在本托盘手里跑着,就补拉一份。返回这一轮有没有动手。
+
+ 被强杀的托盘留下的孤儿服务一退,端口就空着;启动时见它健康而没拉自己的那份,
+ 不补拉的话要等人去点「重启服务」。重启、同步账本、同步开发进度都在
+ `_action_lock` 里故意停服务,拿不到锁就是有人在维护,这一轮不动。
+ 本托盘拉起、还活着却没应答的(刚起、正忙)由 `start_missing` 自己跳过。
+ """
+ if not self._action_lock.acquire(blocking=False):
+ return False
+ try:
+ if self._stop_event.is_set():
+ return False
+ self.manager.start_missing()
+ return True
+ finally:
+ self._action_lock.release()
+
def _setup(self, icon) -> None:
icon.visible = True
# 必须等图标真的创建出来才拿得到底层 NSImage,所以放在 setup 里而不是构造时。
@@ -1104,6 +1131,7 @@ class PeachTray:
elif self.show_browser:
self.gate.open()
threading.Thread(target=self._monitor, name="PeachHealth", daemon=True).start()
+ logging.getLogger(__name__).info("托盘启动完成:%s", self.manager.status())
try:
self.icon.run(setup=self._setup)
finally:
@@ -1360,6 +1388,22 @@ def build_parser() -> argparse.ArgumentParser:
return parser
+def log_to_file(path: Path) -> logging.Handler | None:
+ """托盘自己的日志另落一份文件,返回挂上的 handler;写不了返回 None。
+
+ pythonw 下没有 stderr,`basicConfig` 那一份无处可落,启停时序出问题时只剩进程创建
+ 时间可对。写不了只是少一份证据,不拦托盘启动。
+ """
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handler = logging.FileHandler(path, encoding="utf-8")
+ except OSError:
+ return None
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
+ logging.getLogger().addHandler(handler)
+ return handler
+
+
def main(argv: list[str] | None = None) -> int:
# 参数解析必须排在任何进程级副作用之前:`--help` 和拼错的参数都要在 HiDPI 设置、
# 单实例锁和目录创建之前退出,否则一条试探命令就会在磁盘上凭空造出一个数据根,
@@ -1388,6 +1432,7 @@ def main(argv: list[str] | None = None) -> int:
logging.getLogger(__name__).info("日志整理:%s", action)
except Exception:
logging.getLogger(__name__).warning("日志整理失败", exc_info=True)
+ log_to_file(config.directory("logs") / "tray.log")
manager = ServiceManager(specs, log_dir=config.directory("logs"))
gate = SetupGate(manager, config, waiting=waiting)
if sys.platform == "darwin":
diff --git a/src/peach/tunnel.py b/src/peach/tunnel.py
index c6d063895..c754a9b58 100644
--- a/src/peach/tunnel.py
+++ b/src/peach/tunnel.py
@@ -28,6 +28,7 @@ from pathlib import Path
from typing import Callable, TextIO
from . import access
+from .process_job import assign_to_job, close_job, create_kill_on_close_job
STATE_FILENAME = "cloudflare-tunnel.json"
@@ -442,9 +443,6 @@ def _write_state(path: Path, snapshot: TunnelSnapshot) -> None:
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
_PROCESS_TERMINATE = 0x0001
-_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
-#: JobObjectExtendedLimitInformation
-_JOB_EXTENDED_LIMIT_CLASS = 9
def _windows_image_name(pid: int) -> str:
@@ -542,89 +540,6 @@ def terminate_pid(pid: int) -> None:
pass
-def _create_kill_on_close_job():
- """建一个随句柄关闭一并终止成员的 Job Object;非 Windows 返回 None。
-
- 服务进程被强杀时不会走 `stop()`,只有内核托管的 Job 能保证 cloudflared 不会
- 独自留在公网上继续转发。
- """
- if os.name != "nt":
- return None
- from ctypes import wintypes
-
- class _IoCounters(ctypes.Structure):
- _fields_ = [(name, ctypes.c_ulonglong) for name in (
- "ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
- "ReadTransferCount", "WriteTransferCount", "OtherTransferCount",
- )]
-
- class _BasicLimits(ctypes.Structure):
- _fields_ = [
- ("PerProcessUserTimeLimit", ctypes.c_longlong),
- ("PerJobUserTimeLimit", ctypes.c_longlong),
- ("LimitFlags", wintypes.DWORD),
- ("MinimumWorkingSetSize", ctypes.c_size_t),
- ("MaximumWorkingSetSize", ctypes.c_size_t),
- ("ActiveProcessLimit", wintypes.DWORD),
- ("Affinity", ctypes.c_size_t),
- ("PriorityClass", wintypes.DWORD),
- ("SchedulingClass", wintypes.DWORD),
- ]
-
- class _ExtendedLimits(ctypes.Structure):
- _fields_ = [
- ("BasicLimitInformation", _BasicLimits),
- ("IoInfo", _IoCounters),
- ("ProcessMemoryLimit", ctypes.c_size_t),
- ("JobMemoryLimit", ctypes.c_size_t),
- ("PeakProcessMemoryUsed", ctypes.c_size_t),
- ("PeakJobMemoryUsed", ctypes.c_size_t),
- ]
-
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- kernel32.CreateJobObjectW.restype = wintypes.HANDLE
- kernel32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)
- job = kernel32.CreateJobObjectW(None, None)
- if not job:
- return None
- limits = _ExtendedLimits()
- limits.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
- if not kernel32.SetInformationJobObject(
- wintypes.HANDLE(job), _JOB_EXTENDED_LIMIT_CLASS,
- ctypes.byref(limits), ctypes.sizeof(limits),
- ):
- kernel32.CloseHandle(wintypes.HANDLE(job))
- return None
- return job
-
-
-def _assign_to_job(job, process) -> None:
- if job is None or os.name != "nt":
- return
- handle = getattr(process, "_handle", None)
- if handle is None:
- return
- from ctypes import wintypes
-
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- try:
- kernel32.AssignProcessToJobObject(wintypes.HANDLE(job), wintypes.HANDLE(int(handle)))
- except (OSError, ValueError, TypeError):
- # 内核拒绝嵌套 Job 时仍然启动:stop() 与 pidfile 回收仍会收掉这个子进程。
- pass
-
-
-def _close_job(job) -> None:
- if job is None or os.name != "nt":
- return
- from ctypes import wintypes
-
- try:
- ctypes.WinDLL("kernel32", use_last_error=True).CloseHandle(wintypes.HANDLE(job))
- except (OSError, ValueError):
- pass
-
-
class TunnelManager:
"""一个 Peach 服务进程拥有的一条 cloudflared 子进程。"""
@@ -834,7 +749,7 @@ class TunnelManager:
self.reclaim_orphan()
self.pid_file.unlink(missing_ok=True)
if self._job is None:
- self._job = _create_kill_on_close_job()
+ self._job = create_kill_on_close_job()
handle: TextIO | None = None
process: subprocess.Popen | None = None
try:
@@ -864,7 +779,7 @@ class TunnelManager:
self._ready.set()
self._write_error(message)
raise TunnelError(message) from exc
- _assign_to_job(self._job, process)
+ assign_to_job(self._job, process)
self._process = process
stream = process.stdout
if stream is None:
@@ -959,7 +874,7 @@ class TunnelManager:
self._error = ""
self._ready.set()
self._terminate_process(process)
- _close_job(job)
+ close_job(job)
if reader is not None and reader.is_alive():
reader.join(timeout=1)
snapshot = TunnelSnapshot(state="stopped")
diff --git a/src/peach/windows_restart.py b/src/peach/windows_restart.py
index efcd689bb..35de3a2ba 100644
--- a/src/peach/windows_restart.py
+++ b/src/peach/windows_restart.py
@@ -22,6 +22,10 @@ from .windows_update import replace_with_retry, swap_tray_binary
WM_STOP = 0x0400 + 10 # pystray._util.win32.WM_STOP
+#: 停与起各一份的期限。正常一轮十来秒;机器忙着跑测试时新托盘光启动就可能过半分钟,
+#: 而成功时一就绪就返回,期限放宽只拖慢真失败的那一次。
+DEFAULT_TIMEOUT = 60.0
+
@dataclass(frozen=True)
class TrayWindow:
@@ -283,26 +287,152 @@ def post_stop(window_handle: int) -> bool:
return bool(user32.PostMessageW(window_handle, WM_STOP, 0, 0))
+def _descends_from(process_id: int, ancestor: int, parents: dict[int, int]) -> bool:
+ seen: set[int] = set()
+ parent = parents.get(process_id, 0)
+ while parent and parent not in seen:
+ if parent == ancestor:
+ return True
+ seen.add(parent)
+ parent = parents.get(parent, 0)
+ return False
+
+
def owned_service_pids(tray_process_id: int, service_executable: Path) -> tuple[int, ...]:
+ """这个托盘名下的服务入口进程。
+
+ 父进程号在父进程死后仍记在子进程身上,所以托盘退出后再问一次,拿到的就是它
+ 没收干净、还活着的那几个。
+ """
+ if os.name != "nt":
+ return ()
paths, parents = _process_paths_and_parents()
service_key = _normal_path(service_executable)
+ return tuple(sorted(
+ process_id for process_id, path in paths.items()
+ if _normal_path(path) == service_key
+ and _descends_from(process_id, tray_process_id, parents)
+ ))
- def descends_from(process_id: int) -> bool:
- seen: set[int] = set()
- parent = parents.get(process_id, 0)
- while parent and parent not in seen:
- if parent == tray_process_id:
- return True
- seen.add(parent)
- parent = parents.get(parent, 0)
- return False
- return tuple(sorted(
+def stray_service_pids(tray_process_id: int, service_executable: Path) -> tuple[int, ...]:
+ """不在这个托盘名下的 `peach serve`:被强杀的托盘留下的孤儿就在这里面。
+
+ 只认命令行第一个参数是 `serve` 的:同一个 venv 里跑着的批处理 CLI 不占端口。
+ """
+ if os.name != "nt":
+ return ()
+ paths, parents = _process_paths_and_parents()
+ service_key = _normal_path(service_executable)
+ candidates = [
process_id for process_id, path in paths.items()
- if _normal_path(path) == service_key and descends_from(process_id)
+ if _normal_path(path) == service_key
+ and not _descends_from(process_id, tray_process_id, parents)
+ ]
+ if not candidates:
+ return ()
+ commands = _command_lines(candidates)
+ return tuple(sorted(
+ process_id for process_id in candidates
+ if parse_windows_command_line(commands.get(process_id))[1:2] == ["serve"]
))
+def _stop_old_tray(
+ windows: tuple[TrayWindow, ...],
+ old_process_id: int,
+ service_executable: Path,
+ *,
+ timeout: float,
+ stop_window: Callable[[int], bool],
+ alive: Callable[[int], bool],
+ services: Callable[[int, Path], tuple[int, ...]],
+ strays: Callable[[int, Path], tuple[int, ...]],
+ sleep: Callable[[float], None],
+) -> RestartResult | None:
+ """发停止消息,等旧托盘退出,再等它名下的子服务退净;哪一步不成立就返回失败。
+
+ 发消息之前先看端口是不是旧托盘的。它名下凑不齐两个子服务、旁边却有别的 `serve`
+ 在跑,就是有托盘被强杀过、那几个服务成了孤儿:这时重启托盘换不掉代码,新托盘见
+ 端口健康就不拉自己的,只会一直等到超时。
+
+ 旧托盘退出时自己会停子服务;这里等它们真的消失,新托盘才不会把正在退出的旧服务
+ 当成现成的。
+ """
+ owned = services(old_process_id, service_executable)
+ if len(owned) < 2:
+ foreign = strays(old_process_id, service_executable)
+ if foreign:
+ listed = "、".join(str(pid) for pid in foreign)
+ return RestartResult(
+ False, f"拒绝重启:旧托盘名下只有 {len(owned)} 个子服务,端口由不归它管的"
+ f" serve 进程占着(PID {listed}),重启托盘换不掉它们",
+ old_tray_pid=old_process_id, service_pids=foreign)
+ if not all(stop_window(window.handle) for window in windows):
+ return RestartResult(False, "托盘停止消息发送失败", old_tray_pid=old_process_id)
+
+ deadline = time.monotonic() + timeout
+ while alive(old_process_id) and time.monotonic() < deadline:
+ sleep(0.1)
+ if alive(old_process_id):
+ return RestartResult(False, "托盘未在期限内正常退出;未强杀、未另启",
+ old_tray_pid=old_process_id)
+ while any(alive(pid) for pid in owned) and time.monotonic() < deadline:
+ sleep(0.1)
+ leftover = tuple(pid for pid in owned if alive(pid))
+ if leftover:
+ return RestartResult(False, "旧托盘已退出,但它的子服务未在期限内退出;未另启",
+ old_tray_pid=old_process_id, service_pids=leftover)
+ return None
+
+
+@dataclass(frozen=True)
+class _Launch:
+ """新托盘启动之后看到的样子。"""
+
+ exit_code: int | None = None
+ tray_pid: int | None = None
+ service_pids: tuple[int, ...] = ()
+
+ @property
+ def ready(self) -> bool:
+ return self.exit_code is None and len(self.service_pids) >= 2
+
+ def failure(self) -> str:
+ if self.exit_code is not None:
+ return f"新托盘退出,代码 {self.exit_code}"
+ if self.tray_pid is None:
+ return "新托盘窗口未在期限内出现"
+ return (f"新托盘(PID {self.tray_pid})已起,但名下只有 {len(self.service_pids)} 个"
+ "子服务:端口可能被不归它管的进程占着")
+
+
+def _await_new_tray(
+ launched: subprocess.Popen,
+ find_windows: Callable[[], tuple[TrayWindow, ...]],
+ service_executable: Path,
+ *,
+ timeout: float,
+ services: Callable[[int, Path], tuple[int, ...]],
+ sleep: Callable[[float], None],
+) -> _Launch:
+ """等新托盘建出唯一窗口并拥有两个子服务;期限到了返回最后看到的样子。"""
+ deadline = time.monotonic() + timeout
+ seen = _Launch()
+ while time.monotonic() < deadline:
+ if launched.poll() is not None:
+ return _Launch(exit_code=launched.returncode)
+ process_ids = {window.process_id for window in find_windows()}
+ if len(process_ids) == 1:
+ tray_pid = next(iter(process_ids))
+ seen = _Launch(tray_pid=tray_pid,
+ service_pids=services(tray_pid, service_executable))
+ if seen.ready:
+ return seen
+ sleep(0.2)
+ return seen
+
+
def start_tray(target: Path) -> subprocess.Popen:
environment = os.environ.copy()
environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"
@@ -350,13 +480,14 @@ def _rolled_back(
def restart_tray(
target: Path,
*,
- timeout: float = 25.0,
+ timeout: float = DEFAULT_TIMEOUT,
swap_from: Path | None = None,
find_windows: Callable[[Path], tuple[TrayWindow, ...]] = find_tray_windows,
stop_window: Callable[[int], bool] = post_stop,
alive: Callable[[int], bool] = process_alive,
start: Callable[[Path], subprocess.Popen] = start_tray,
services: Callable[[int, Path], tuple[int, ...]] = owned_service_pids,
+ strays: Callable[[int, Path], tuple[int, ...]] = stray_service_pids,
swap: Callable[[Path, Path], Path] = swap_tray_binary,
sleep: Callable[[float], None] = time.sleep,
) -> RestartResult:
@@ -372,14 +503,11 @@ def restart_tray(
if len(process_ids) != 1 or not windows:
return RestartResult(False, "拒绝重启:没有找到唯一且路径匹配的 Peach 托盘窗口")
old_process_id = next(iter(process_ids))
- if not all(stop_window(window.handle) for window in windows):
- return RestartResult(False, "托盘停止消息发送失败", old_tray_pid=old_process_id)
-
- deadline = time.monotonic() + timeout
- while alive(old_process_id) and time.monotonic() < deadline:
- sleep(0.1)
- if alive(old_process_id):
- return RestartResult(False, "托盘未在期限内正常退出;未强杀、未另启", old_tray_pid=old_process_id)
+ stopped = _stop_old_tray(
+ windows, old_process_id, service_executable, timeout=timeout,
+ stop_window=stop_window, alive=alive, services=services, strays=strays, sleep=sleep)
+ if stopped is not None:
+ return stopped
backup: Path | None = None
if swap_from is not None:
@@ -397,46 +525,34 @@ def restart_tray(
backup_path = str(backup) if backup is not None else None
# 停和起各拿一份完整预算:换一份 40 MB 的 EXE 要几秒,那几秒不该从新托盘的
# 启动窗口里扣掉,否则带 --swap-from 的这条路比不带的更容易假超时。
- deadline = time.monotonic() + timeout
- launched = start(target)
- while time.monotonic() < deadline:
- if launched.poll() is not None:
- if backup is not None:
- return _rolled_back(
- backup, target, start=start, sleep=sleep,
- message=f"新托盘退出,代码 {launched.returncode}",
- old_tray_pid=old_process_id, swapped_from=swapped_from)
- return RestartResult(False, f"新托盘退出,代码 {launched.returncode}", old_tray_pid=old_process_id)
- new_windows = find_windows(target)
- new_process_ids = {window.process_id for window in new_windows}
- if len(new_process_ids) == 1:
- new_process_id = next(iter(new_process_ids))
- service_pids = services(new_process_id, service_executable)
- if len(service_pids) >= 2:
- return RestartResult(
- True, "托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",
- old_tray_pid=old_process_id, new_tray_pid=new_process_id,
- service_pids=service_pids, swapped_from=swapped_from,
- backup=backup_path,
- )
- sleep(0.2)
+ launch = _await_new_tray(
+ start(target), lambda: find_windows(target), service_executable,
+ timeout=timeout, services=services, sleep=sleep)
+ if launch.ready:
+ return RestartResult(
+ True, "托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",
+ old_tray_pid=old_process_id, new_tray_pid=launch.tray_pid,
+ service_pids=launch.service_pids, swapped_from=swapped_from,
+ backup=backup_path,
+ )
if backup is not None:
return _rolled_back(
- backup, target, start=start, sleep=sleep,
- message="新托盘或两个子服务未在期限内就绪",
+ backup, target, start=start, sleep=sleep, message=launch.failure(),
old_tray_pid=old_process_id, swapped_from=swapped_from)
- return RestartResult(False, "新托盘或两个子服务未在期限内就绪", old_tray_pid=old_process_id)
+ return RestartResult(False, launch.failure(), old_tray_pid=old_process_id,
+ new_tray_pid=launch.tray_pid, service_pids=launch.service_pids)
def restart_source_tray(
*,
- timeout: float = 25.0,
+ timeout: float = DEFAULT_TIMEOUT,
find_windows: Callable[[], tuple[TrayWindow, ...]] = find_source_tray_windows,
stop_window: Callable[[int], bool] = post_stop,
alive: Callable[[int], bool] = process_alive,
command_lines: Callable[[], dict[int, str]] = _command_lines,
start: Callable[[list[str]], subprocess.Popen] | None = None,
services: Callable[[int, Path], tuple[int, ...]] = owned_service_pids,
+ strays: Callable[[int, Path], tuple[int, ...]] = stray_service_pids,
sleep: Callable[[float], None] = time.sleep,
) -> RestartResult:
"""源码部署托盘的正常重启:按同一命令行自起新托盘。
@@ -473,32 +589,18 @@ def restart_source_tray(
if not service_executable.is_file():
return RestartResult(False, f"拒绝重启:源码托盘旁没有服务入口 {service_executable}",
old_tray_pid=old_process_id)
- if not all(stop_window(window.handle) for window in windows):
- return RestartResult(False, "托盘停止消息发送失败", old_tray_pid=old_process_id)
-
- deadline = time.monotonic() + timeout
- while alive(old_process_id) and time.monotonic() < deadline:
- sleep(0.1)
- if alive(old_process_id):
- return RestartResult(False, "托盘未在期限内正常退出;未强杀、未另启",
- old_tray_pid=old_process_id)
-
- deadline = time.monotonic() + timeout
- launched = start_argv(argv)
- while time.monotonic() < deadline:
- if launched.poll() is not None:
- return RestartResult(False, f"新托盘退出,代码 {launched.returncode}",
- old_tray_pid=old_process_id)
- new_windows = find_windows()
- new_process_ids = {window.process_id for window in new_windows}
- if len(new_process_ids) == 1:
- new_process_id = next(iter(new_process_ids))
- service_pids = services(new_process_id, service_executable)
- if len(service_pids) >= 2:
- return RestartResult(True, "源码托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",
- old_tray_pid=old_process_id,
- new_tray_pid=new_process_id,
- service_pids=service_pids)
- sleep(0.2)
- return RestartResult(False, "新托盘或两个子服务未在期限内就绪",
- old_tray_pid=old_process_id)
+ stopped = _stop_old_tray(
+ windows, old_process_id, service_executable, timeout=timeout,
+ stop_window=stop_window, alive=alive, services=services, strays=strays, sleep=sleep)
+ if stopped is not None:
+ return stopped
+
+ launch = _await_new_tray(
+ start_argv(argv), find_windows, service_executable,
+ timeout=timeout, services=services, sleep=sleep)
+ if launch.ready:
+ return RestartResult(True, "源码托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",
+ old_tray_pid=old_process_id, new_tray_pid=launch.tray_pid,
+ service_pids=launch.service_pids)
+ return RestartResult(False, launch.failure(), old_tray_pid=old_process_id,
+ new_tray_pid=launch.tray_pid, service_pids=launch.service_pids)
diff --git a/tests/test_process_job.py b/tests/test_process_job.py
new file mode 100644
index 000000000..09300f17e
--- /dev/null
+++ b/tests/test_process_job.py
@@ -0,0 +1,94 @@
+import os
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+from peach.jobs import process_alive
+from peach.process_job import assign_to_job, close_job, create_kill_on_close_job
+
+ROOT = Path(__file__).resolve().parents[1]
+
+#: 一个最小的「托盘」:用真的 ServiceManager 拉起一个睡着的子服务,报出它的 PID 后原地等着被杀。
+TRAY_STAND_IN = """
+import sys, time
+from pathlib import Path
+from unittest import mock
+from peach.tray import ServiceManager, ServiceSpec
+
+spec = ServiceSpec("http", "http://127.0.0.1:9/healthz",
+ (sys.executable, "-c", "import time; time.sleep(120)"), True)
+manager = ServiceManager((spec,), log_dir=Path(sys.argv[1]),
+ health_get=mock.Mock(side_effect=OSError("down")))
+manager.start_missing()
+print(manager._owned["http"].pid, flush=True)
+time.sleep(120)
+"""
+
+
+def descendants(root: int) -> set[int]:
+ from peach.windows_restart import _process_paths_and_parents
+ _paths, parents = _process_paths_and_parents()
+ found, frontier = set(), [root]
+ while frontier:
+ current = frontier.pop()
+ for process_id, parent in parents.items():
+ if parent == current and process_id not in found:
+ found.add(process_id)
+ frontier.append(process_id)
+ return found
+
+
+def wait_until(predicate, seconds: float = 10.0) -> bool:
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.1)
+ return predicate()
+
+
[email protected](os.name == "nt", "Job Object 是 Windows 能力,其余平台三个函数都是空操作")
+class KillOnCloseJobTests(unittest.TestCase):
+ def sleeper(self) -> subprocess.Popen:
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"],
+ creationflags=subprocess.CREATE_NO_WINDOW)
+ self.addCleanup(lambda: child.poll() is None and child.kill())
+ return child
+
+ def test_closing_the_job_ends_the_processes_in_it(self):
+ child = self.sleeper()
+ job = create_kill_on_close_job()
+ self.assertIsNotNone(job)
+ assign_to_job(job, child)
+ close_job(job)
+ self.assertIsNotNone(child.wait(timeout=10))
+
+ def test_a_force_killed_tray_takes_its_services_along(self):
+ """`Stop-Process -Force` 打托盘时收尾代码一行不跑,只有内核关 Job 句柄这一步还在。
+
+ 2026-09-25 就是这样留下两棵孤儿服务,继续占着 80/443 跑旧代码。
+ """
+ with tempfile.TemporaryDirectory() as directory:
+ environment = {**os.environ, "PYTHONPATH": str(ROOT / "src"),
+ "PEACH_DATA_ROOT": directory}
+ tray = subprocess.Popen(
+ [sys.executable, "-c", TRAY_STAND_IN, directory], stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", env=environment,
+ creationflags=subprocess.CREATE_NO_WINDOW)
+ self.addCleanup(lambda: tray.poll() is None and tray.kill())
+ service = int(tray.stdout.readline())
+ # venv 的 python.exe 是个转发器,真正的解释器是它再起的子进程。
+ wait_until(lambda: descendants(service))
+ tree = {service} | descendants(service)
+ tray.kill()
+ tray.wait(timeout=10)
+ tray.stdout.close()
+ self.assertTrue(wait_until(lambda: not any(process_alive(pid) for pid in tree)),
+ f"托盘被强杀后这些服务进程还活着:{sorted(tree)}")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.py
index f0a129b59..f661344b0 100644
--- a/tests/test_restart_windows_tray.py
+++ b/tests/test_restart_windows_tray.py
@@ -172,6 +172,112 @@ class RestartWindowsTrayTests(unittest.TestCase):
self.assertEqual(result.new_tray_pid, 30)
self.assertEqual(result.service_pids, (51, 52))
+ def source_restart(self, **overrides):
+ pythonw = self.service.parent / "pythonw.exe"
+ pythonw.write_bytes(b"shim")
+ argv = [str(pythonw), "-c", self.BOOTSTRAP]
+ windows = iter(((windows_restart.TrayWindow(10, 20),),))
+ options = dict(
+ find_windows=lambda: next(windows, (windows_restart.TrayWindow(30, 40),)),
+ stop_window=lambda _handle: True,
+ alive=lambda _pid: False,
+ command_lines=lambda: {10: subprocess.list2cmdline(argv)},
+ services=lambda tray_pid, _executable: (51, 52) if tray_pid in (10, 30) else (),
+ strays=lambda _tray_pid, _executable: (),
+ sleep=lambda _seconds: None,
+ )
+ options.update(overrides)
+ return windows_restart.restart_source_tray(**options)
+
+ @staticmethod
+ def running_tray():
+ launched = mock.Mock()
+ launched.poll.return_value = None
+ return launched
+
+ def test_orphaned_services_on_the_ports_refuse_the_restart_before_anything_stops(self):
+ """被强杀过的托盘留下的服务不归任何人管,重启托盘换不掉它们。
+
+ 2026-09-25 就是这样:旧托盘名下一个子服务都没有,新托盘见端口健康也不拉自己的,
+ 脚本空等到超时,报的却是「未在期限内就绪」。
+ """
+ stop_window, start = mock.Mock(), mock.Mock()
+ result = self.source_restart(
+ services=lambda _tray_pid, _executable: (),
+ strays=lambda _tray_pid, _executable: (5428, 39272),
+ stop_window=stop_window, start=start,
+ )
+ self.assertFalse(result.ok)
+ self.assertIn("5428、39272", result.message)
+ self.assertEqual(result.service_pids, (5428, 39272))
+ stop_window.assert_not_called()
+ start.assert_not_called()
+
+ def test_a_tray_whose_services_simply_died_is_still_restarted(self):
+ """名下缺服务、旁边也没有别的 serve:重启正是修它的办法。"""
+ launched = self.running_tray()
+ result = self.source_restart(
+ services=lambda tray_pid, _executable: (51, 52) if tray_pid == 30 else (),
+ start=lambda _argv: launched,
+ )
+ self.assertTrue(result.ok, result.message)
+
+ def test_the_new_tray_starts_only_after_the_old_services_are_gone(self):
+ still_running = {51: 3, 52: 1}
+ seen_at_start = []
+
+ def alive(pid):
+ if still_running.get(pid, 0) == 0:
+ return False
+ still_running[pid] -= 1
+ return True
+
+ launched = self.running_tray()
+ result = self.source_restart(
+ alive=alive,
+ start=lambda _argv: seen_at_start.append(dict(still_running)) or launched,
+ )
+ self.assertTrue(result.ok, result.message)
+ self.assertEqual(seen_at_start, [{51: 0, 52: 0}])
+
+ def test_old_services_that_outlive_their_tray_block_the_new_one(self):
+ start = mock.Mock()
+ result = self.source_restart(
+ timeout=0.001, alive=lambda pid: pid in (51, 52), start=start,
+ )
+ self.assertFalse(result.ok)
+ self.assertIn("子服务未在期限内退出", result.message)
+ self.assertEqual(result.service_pids, (51, 52))
+ start.assert_not_called()
+
+ def test_a_new_tray_without_its_own_services_is_named_in_the_failure(self):
+ launched = self.running_tray()
+ result = self.source_restart(
+ timeout=0.05,
+ services=lambda tray_pid, _executable: (51, 52) if tray_pid == 10 else (),
+ start=lambda _argv: launched,
+ )
+ self.assertFalse(result.ok)
+ self.assertEqual(result.new_tray_pid, 30)
+ self.assertIn("PID 30", result.message)
+ self.assertIn("名下只有 0 个子服务", result.message)
+
+ @unittest.skipUnless(sys.platform == "win32", "进程快照只在 Windows 上有")
+ def test_strays_are_serve_launchers_outside_the_tray(self):
+ exe = str(self.service)
+ paths = {100: exe, 101: exe, 102: exe, 103: exe, 7: "C:/tray/pythonw.exe"}
+ parents = {100: 7, 101: 66, 102: 66, 103: 66, 7: 1}
+ commands = {101: f'"{exe}" serve --port 443', 102: f'"{exe}" scrape ABW-001',
+ 103: f'"{exe}" serve --port 80'}
+ with (
+ mock.patch.object(windows_restart, "_process_paths_and_parents",
+ return_value=(paths, parents)),
+ mock.patch.object(windows_restart, "_command_lines",
+ side_effect=lambda pids: {pid: commands.get(pid, "") for pid in pids}),
+ ):
+ self.assertEqual(windows_restart.stray_service_pids(7, self.service), (101, 103))
+ self.assertEqual(windows_restart.owned_service_pids(7, self.service), (100,))
+
def stage(self) -> Path:
staged = self.root / "staging" / "Peach.exe"
staged.parent.mkdir()
diff --git a/tests/test_tray.py b/tests/test_tray.py
index ceb854333..1d8b21efe 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -1238,5 +1238,82 @@ class TrayCommandLineTests(unittest.TestCase):
self._assert_nothing_touched()
+class ServiceRevivalTests(unittest.TestCase):
+ """托盘不只在启动时拉一次服务:端口空了就补拉,但不跟正在维护服务的动作抢。
+
+ 2026-09-25 一份被强杀的托盘留下两棵孤儿服务,新托盘启动时见端口健康就没拉自己的;
+ 孤儿被停掉以后端口空了一分半,直到有人去点「重启服务」。
+ """
+
+ SPEC = ServiceSpec("https", "https://local/healthz", ("peach", "serve"), True)
+
+ def tray(self, manager):
+ gate = Mock()
+ gate.waiting = False
+ snapshot = VersionSnapshot("0.7.14", "master", "abc12345", False, True, "origin/master")
+ with patch("peach.tray.pystray.Icon", return_value=Mock()):
+ return PeachTray(manager, FakeVersions(snapshot), FakeUpdates(), gate)
+
+ def one_health_round(self, tray):
+ stop = Mock()
+ stop.wait.side_effect = [False, True]
+ stop.is_set.return_value = False
+ tray._stop_event = stop
+ with patch("peach.standalone_update.poll"), patch("peach.desktop_uninstall.poll"):
+ tray._monitor()
+
+ def manager(self, *, healthy):
+ manager = Mock()
+ manager.specs = (self.SPEC,)
+ manager.healthy.return_value = healthy
+ return manager
+
+ def test_a_port_that_went_dark_is_refilled_on_the_next_health_round(self):
+ manager = self.manager(healthy=False)
+ self.one_health_round(self.tray(manager))
+ manager.start_missing.assert_called_once_with()
+
+ def test_healthy_services_are_left_alone(self):
+ manager = self.manager(healthy=True)
+ self.one_health_round(self.tray(manager))
+ manager.start_missing.assert_not_called()
+
+ def test_revival_yields_to_an_action_that_is_stopping_services_on_purpose(self):
+ manager = self.manager(healthy=False)
+ tray = self.tray(manager)
+ with tray._action_lock:
+ self.assertFalse(tray.revive_services())
+ tray._stop_event.set()
+ self.assertFalse(tray.revive_services())
+ manager.start_missing.assert_not_called()
+
+ def test_a_healthy_port_it_did_not_start_is_reported_not_adopted_silently(self):
+ popen = Mock()
+ with tempfile.TemporaryDirectory() as directory:
+ manager = ServiceManager((self.SPEC,), popen=popen, log_dir=Path(directory),
+ health_get=lambda *args, **kwargs: Response())
+ with self.assertLogs("peach.tray", "WARNING") as logs:
+ manager.start_missing()
+ popen.assert_not_called()
+ self.assertIn("不是本托盘拉起的", logs.output[0])
+
+ def test_log_handles_go_to_the_child_and_are_closed_in_the_tray(self):
+ """补拉会反复发生,父进程每拉一次就多握两个日志句柄的话会越攒越多。"""
+ handed = []
+
+ def popen(_command, **kwargs):
+ handed.extend((kwargs["stdout"], kwargs["stderr"]))
+ process = Mock()
+ process.poll.return_value = None
+ return process
+
+ with tempfile.TemporaryDirectory() as directory:
+ manager = ServiceManager((self.SPEC,), popen=popen, log_dir=Path(directory),
+ health_get=Mock(side_effect=OSError("down")))
+ manager.start_missing()
+ self.assertEqual(len(handed), 2)
+ self.assertTrue(all(handle.closed for handle in handed))
+
+
if __name__ == "__main__":
unittest.main()