dev.py:无 .env/旧自动生成 .env 自动进安装向导(不连库),有 .env 才迁移+种子+起三端; popen 支持 env,移除 build_env/write_env/wait_db_auth/ensure_mysql_database,config.yaml 精简; build_docker 不再预置 DATABASE_URL/管理员,挂载 data/config 并注入安装预填充; entrypoint 直接启动,建库/迁移/建超管交由安装向导,杜绝默认口令。
428 lines
16 KiB
Python
428 lines
16 KiB
Python
"""artveris 脚本公共库:读取 YAML 配置、生成 .env、运行命令。"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import socket
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
from shutil import which
|
||
|
||
import yaml
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
SCRIPTS = ROOT / "scripts"
|
||
IS_WINDOWS = os.name == "nt"
|
||
|
||
|
||
def load_config(path: Path | None = None) -> dict:
|
||
path = path or (SCRIPTS / "config.yaml")
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
return yaml.safe_load(f)
|
||
|
||
|
||
def ensure_pnpm() -> None:
|
||
"""确保 pnpm 可用;若未安装则通过 Node 自带的 corepack 激活项目声明的版本。"""
|
||
if which("pnpm"):
|
||
return
|
||
if not which("node"):
|
||
print("[artveris] 未找到 node,请先安装 Node.js 20+ 后重试。")
|
||
sys.exit(1)
|
||
if not which("corepack"):
|
||
print("[artveris] 未找到 pnpm/corepack,请确认 Node.js 20+ 已正确安装并加入 PATH。")
|
||
sys.exit(1)
|
||
|
||
version = "10.28.0"
|
||
try:
|
||
with open(ROOT / "package.json", "r", encoding="utf-8") as f:
|
||
package_manager = json.load(f).get("packageManager", "")
|
||
if package_manager.startswith("pnpm@"):
|
||
version = package_manager.removeprefix("pnpm@")
|
||
except (OSError, json.JSONDecodeError):
|
||
pass
|
||
|
||
print(f"[artveris] 未检测到 pnpm,正在通过 corepack 激活 pnpm@{version} …")
|
||
run("corepack enable")
|
||
run(f"corepack prepare pnpm@{version} --activate")
|
||
if not which("pnpm"):
|
||
print("[artveris] pnpm 激活后仍不可用,请重新打开终端后再试。")
|
||
sys.exit(1)
|
||
|
||
|
||
def run(cmd: str, cwd: Path | None = None, check: bool = True) -> int:
|
||
print(f"[artveris] $ {cmd}")
|
||
proc = subprocess.run(cmd, cwd=str(cwd or ROOT), shell=True)
|
||
if check and proc.returncode != 0:
|
||
print(f"[artveris] 命令失败(退出码 {proc.returncode}):{cmd}")
|
||
sys.exit(proc.returncode)
|
||
return proc.returncode
|
||
|
||
|
||
_WIN: dict = {}
|
||
|
||
|
||
def _winapi():
|
||
"""初始化并缓存配置好签名的 Win32 函数(64 位下 HANDLE 必须显式声明,否则被截断为 32 位)。"""
|
||
if _WIN:
|
||
return _WIN["k32"], _WIN["ntdll"]
|
||
import ctypes
|
||
from ctypes import wintypes
|
||
|
||
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||
ntdll = ctypes.WinDLL("ntdll", use_last_error=True)
|
||
k32.CreateJobObjectW.restype = wintypes.HANDLE
|
||
k32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR]
|
||
k32.OpenProcess.restype = wintypes.HANDLE
|
||
k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||
k32.AssignProcessToJobObject.restype = wintypes.BOOL
|
||
k32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
||
k32.SetInformationJobObject.restype = wintypes.BOOL
|
||
k32.SetInformationJobObject.argtypes = [
|
||
wintypes.HANDLE,
|
||
ctypes.c_int,
|
||
wintypes.LPVOID,
|
||
wintypes.DWORD,
|
||
]
|
||
k32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||
_WIN.update(k32=k32, ntdll=ntdll, ctypes=ctypes, wintypes=wintypes)
|
||
return k32, ntdll
|
||
|
||
|
||
def create_kill_job():
|
||
"""创建一个设置了 KILL_ON_JOB_CLOSE 的 Windows Job Object。
|
||
将子进程加入该 Job 后,一旦本脚本进程结束(即使被强制结束、未走 finally),
|
||
操作系统会自动终止 Job 内所有子进程,从根本上杜绝 nest/vite 残留。
|
||
非 Windows 返回 None(用进程组 + killpg 处理)。"""
|
||
if not IS_WINDOWS:
|
||
return None
|
||
try:
|
||
k32, _ = _winapi()
|
||
ctypes = _WIN["ctypes"]
|
||
wintypes = _WIN["wintypes"]
|
||
job = k32.CreateJobObjectW(None, None)
|
||
if not job:
|
||
return None
|
||
|
||
class _BASIC(ctypes.Structure):
|
||
_fields_ = [
|
||
("PerProcessUserTimeLimit", ctypes.c_int64),
|
||
("PerJobUserTimeLimit", ctypes.c_int64),
|
||
("LimitFlags", wintypes.DWORD),
|
||
("MinimumWorkingSetSize", ctypes.c_size_t),
|
||
("MaximumWorkingSetSize", ctypes.c_size_t),
|
||
("ActiveProcessLimit", wintypes.DWORD),
|
||
("Affinity", ctypes.c_void_p),
|
||
("PriorityClass", wintypes.DWORD),
|
||
("SchedulingClass", wintypes.DWORD),
|
||
]
|
||
|
||
class _IO(ctypes.Structure):
|
||
_fields_ = [(n, ctypes.c_uint64) for n in (
|
||
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount",
|
||
)]
|
||
|
||
class _EXT(ctypes.Structure):
|
||
_fields_ = [
|
||
("BasicLimitInformation", _BASIC),
|
||
("IoInfo", _IO),
|
||
("ProcessMemoryLimit", ctypes.c_size_t),
|
||
("JobMemoryLimit", ctypes.c_size_t),
|
||
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
||
("PeakJobMemoryUsed", ctypes.c_size_t),
|
||
]
|
||
|
||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
|
||
info = _EXT()
|
||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||
if not k32.SetInformationJobObject(
|
||
job, 9, ctypes.byref(info), ctypes.sizeof(info)
|
||
):
|
||
return None
|
||
return job
|
||
except Exception: # noqa: BLE001
|
||
return None
|
||
|
||
|
||
def _assign_and_resume(job, pid: int) -> None:
|
||
"""把挂起创建的进程加入 Job 后再恢复运行。
|
||
必须在进程派生任何子进程之前完成,才能确保其所有后代都纳入 Job。"""
|
||
k32, ntdll = _winapi()
|
||
PROCESS_TERMINATE = 0x0001
|
||
PROCESS_SET_QUOTA = 0x0100
|
||
PROCESS_SUSPEND_RESUME = 0x0800
|
||
h = k32.OpenProcess(
|
||
PROCESS_TERMINATE | PROCESS_SET_QUOTA | PROCESS_SUSPEND_RESUME, False, pid
|
||
)
|
||
if not h:
|
||
return
|
||
try:
|
||
k32.AssignProcessToJobObject(job, h)
|
||
finally:
|
||
# 无论是否加入成功都必须恢复,否则进程会一直挂起
|
||
ntdll.NtResumeProcess(h)
|
||
k32.CloseHandle(h)
|
||
|
||
|
||
CREATE_SUSPENDED = 0x00000004
|
||
|
||
|
||
def popen(
|
||
cmd: str, cwd: Path | None = None, job=None, env: dict[str, str] | None = None
|
||
) -> subprocess.Popen:
|
||
print(f"[artveris] 启动: {cmd}")
|
||
kwargs: dict = {}
|
||
if IS_WINDOWS:
|
||
# 独立进程组:Ctrl+C 不直接乱传播给子进程,统一由脚本在退出时整树结束
|
||
flags = subprocess.CREATE_NEW_PROCESS_GROUP
|
||
if job:
|
||
flags |= CREATE_SUSPENDED # 挂起创建,加入 Job 后再恢复,避免漏掉先派生的子进程
|
||
kwargs["creationflags"] = flags
|
||
else:
|
||
kwargs["start_new_session"] = True # 便于用 killpg 整组结束
|
||
if env:
|
||
kwargs["env"] = {**os.environ, **env}
|
||
proc = subprocess.Popen(cmd, cwd=str(cwd or ROOT), shell=True, **kwargs)
|
||
if IS_WINDOWS and job:
|
||
try:
|
||
_assign_and_resume(job, proc.pid)
|
||
except Exception: # noqa: BLE001
|
||
# 兜底恢复,避免进程一直挂起
|
||
try:
|
||
k32, ntdll = _winapi()
|
||
h = k32.OpenProcess(0x0800, False, proc.pid)
|
||
if h:
|
||
ntdll.NtResumeProcess(h)
|
||
k32.CloseHandle(h)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
return proc
|
||
|
||
|
||
def stop_proc_tree(proc: subprocess.Popen) -> None:
|
||
"""结束一个 popen 进程的整棵子树(含 pnpm -> nest/vite -> node)。"""
|
||
try:
|
||
if proc.poll() is not None:
|
||
return
|
||
if IS_WINDOWS:
|
||
subprocess.run(
|
||
f"taskkill /F /T /PID {proc.pid}", shell=True, capture_output=True
|
||
)
|
||
else:
|
||
import signal
|
||
|
||
try:
|
||
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
|
||
except ProcessLookupError:
|
||
pass
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
|
||
def stop_all(procs: list[subprocess.Popen]) -> None:
|
||
for p in procs:
|
||
stop_proc_tree(p)
|
||
|
||
|
||
def install_console_ctrl_handler(cleanup) -> None:
|
||
"""在 OS 层拦截 Ctrl+C / Ctrl+Break / 关闭终端 / 注销 / 关机 等事件,
|
||
统一调用 cleanup 结束所有子进程。比依赖 Python 信号更可靠,且能覆盖"关闭窗口"。"""
|
||
if not IS_WINDOWS:
|
||
return
|
||
import ctypes
|
||
from ctypes import wintypes
|
||
|
||
HANDLER = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
|
||
|
||
def _handler(ctrl_type): # 0=C 1=BREAK 2=CLOSE 5=LOGOFF 6=SHUTDOWN
|
||
try:
|
||
cleanup()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
return ctrl_type in (0, 1) # C/Break 由我们处理;其余交还系统(子进程已清理)
|
||
|
||
cb = HANDLER(_handler)
|
||
_WIN.setdefault("handlers", []).append(cb) # 持有引用,防止被 GC 回收
|
||
k32, _ = _winapi()
|
||
k32.SetConsoleCtrlHandler.argtypes = [HANDLER, wintypes.BOOL]
|
||
k32.SetConsoleCtrlHandler.restype = wintypes.BOOL
|
||
k32.SetConsoleCtrlHandler(cb, True)
|
||
|
||
|
||
def _kill_tree_windows(pid: str) -> None:
|
||
# /T 结束进程树(含 nest --watch 等监视器派生的子进程),避免端口被自动重启重新占用
|
||
subprocess.run(f"taskkill /F /T /PID {pid}", shell=True, capture_output=True)
|
||
|
||
|
||
def _free_port_psutil(port: int) -> bool:
|
||
"""用 psutil 按端口定位进程,并结束其"监视父进程 + 整棵子树"。
|
||
仅作用于真正监听该端口的进程及其 node 监视器,不影响 IDE 语言服务。"""
|
||
try:
|
||
import psutil # 延迟导入:仅 dev.py 声明该依赖
|
||
except ImportError:
|
||
return False
|
||
for conn in psutil.net_connections(kind="inet"):
|
||
try:
|
||
if not (conn.laddr and conn.laddr.port == port):
|
||
continue
|
||
if conn.status != psutil.CONN_LISTEN or not conn.pid:
|
||
continue
|
||
proc = psutil.Process(conn.pid)
|
||
root = proc
|
||
parent = proc.parent()
|
||
# nest start --watch / pnpm 会在子进程退出后重启:上溯到 node 父进程一并结束
|
||
if parent and "node" in (parent.name() or "").lower():
|
||
root = parent
|
||
for child in root.children(recursive=True):
|
||
try:
|
||
child.kill()
|
||
except psutil.Error:
|
||
pass
|
||
root.kill()
|
||
print(f"[artveris] 释放端口 {port}(结束进程树 PID {root.pid})")
|
||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
||
continue
|
||
return True
|
||
|
||
|
||
def free_port(port: int) -> None:
|
||
"""结束本机占用指定端口的进程(释放上次的 api/admin/client,并解除对 Prisma 引擎 DLL 的占用)。
|
||
仅用于本地 node 服务,不要对 Docker 管理的端口使用。"""
|
||
try:
|
||
if _free_port_psutil(port):
|
||
return
|
||
# 回退:psutil 不可用时用系统命令(taskkill /T 结束进程树)
|
||
if IS_WINDOWS:
|
||
out = subprocess.run(
|
||
"netstat -ano -p tcp", capture_output=True, text=True, shell=True
|
||
).stdout
|
||
pids: set[str] = set()
|
||
for line in out.splitlines():
|
||
if f":{port} " in line and "LISTENING" in line.upper():
|
||
pid = line.split()[-1]
|
||
if pid and pid != "0":
|
||
pids.add(pid)
|
||
for pid in pids:
|
||
_kill_tree_windows(pid)
|
||
print(f"[artveris] 释放端口 {port}(结束 PID {pid})")
|
||
else:
|
||
out = subprocess.run(
|
||
f"lsof -ti tcp:{port}", capture_output=True, text=True, shell=True
|
||
).stdout
|
||
for pid in out.split():
|
||
subprocess.run(f"kill -9 {pid}", shell=True, capture_output=True)
|
||
print(f"[artveris] 释放端口 {port}(结束 PID {pid})")
|
||
except Exception as e: # noqa: BLE001
|
||
print(f"[artveris] 释放端口 {port} 失败(忽略):{e}")
|
||
|
||
|
||
def free_ports(ports: list[int]) -> None:
|
||
for p in ports:
|
||
free_port(int(p))
|
||
|
||
|
||
# 本项目本地服务的命令行特征:用于按命令行(而非端口)精准识别 nest/vite/api 进程,
|
||
# 以便清理处于 idle 状态、当前并不监听端口的 `nest --watch` 监视器。
|
||
_SERVER_MARKERS = (
|
||
"nest",
|
||
"vite",
|
||
"dist\\main",
|
||
"dist/main",
|
||
"start:dev",
|
||
"dev:api",
|
||
"dev:admin",
|
||
"dev:client",
|
||
"nodemon",
|
||
)
|
||
|
||
|
||
def _kill_project_psutil(root_lower: str) -> tuple[bool, int]:
|
||
try:
|
||
import psutil # 延迟导入:仅 dev.py 声明该依赖
|
||
except ImportError:
|
||
return False, 0
|
||
killed = 0
|
||
me = os.getpid()
|
||
for proc in psutil.process_iter(["pid", "name", "cmdline"]):
|
||
try:
|
||
if proc.pid == me:
|
||
continue
|
||
name = (proc.info.get("name") or "").lower()
|
||
if "node" not in name:
|
||
continue
|
||
cmd = " ".join(proc.info.get("cmdline") or []).lower()
|
||
# 必须同时命中"项目路径"和"服务特征",避免误杀 IDE 的 tsserver/eslint 等
|
||
if root_lower not in cmd:
|
||
continue
|
||
if not any(m in cmd for m in _SERVER_MARKERS):
|
||
continue
|
||
for child in proc.children(recursive=True):
|
||
try:
|
||
child.kill()
|
||
except psutil.Error:
|
||
pass
|
||
proc.kill()
|
||
killed += 1
|
||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
||
continue
|
||
return True, killed
|
||
|
||
|
||
def _kill_project_fallback(root_lower: str) -> None:
|
||
if IS_WINDOWS:
|
||
ps = (
|
||
"Get-CimInstance Win32_Process | Where-Object { "
|
||
"$_.Name -like 'node*' -and "
|
||
f"$_.CommandLine -like '*{root_lower}*' -and "
|
||
"($_.CommandLine -match 'nest|vite|dist.main|dev:') } | "
|
||
"ForEach-Object { taskkill /F /T /PID $_.ProcessId } | Out-Null"
|
||
)
|
||
subprocess.run(
|
||
["powershell", "-NoProfile", "-Command", ps], capture_output=True
|
||
)
|
||
else:
|
||
for pat in ("nest start", "vite", "dist/main"):
|
||
subprocess.run(f"pkill -f '{pat}'", shell=True, capture_output=True)
|
||
|
||
|
||
def kill_project_servers(ports: list[int] | None = None, root: Path | None = None) -> None:
|
||
"""清理本项目残留的本地服务进程(nest/vite/api 及其子进程)。
|
||
按命令行特征识别,可清掉处于 idle、当前未监听端口的 `nest --watch` 监视器,
|
||
从根本上避免下次启动时被其自动重启抢占端口(EADDRINUSE)。"""
|
||
root_lower = str(root or ROOT).lower()
|
||
ok, killed = _kill_project_psutil(root_lower)
|
||
if ok:
|
||
if killed:
|
||
print(f"[artveris] 已清理 {killed} 个残留服务进程(nest/vite/api)")
|
||
else:
|
||
_kill_project_fallback(root_lower)
|
||
if ports:
|
||
free_ports(ports) # 端口兜底:防止非 node 进程或漏网者占用
|
||
|
||
|
||
def run_retry(cmd: str, cwd: Path | None = None, attempts: int = 4, delay: float = 2.0) -> bool:
|
||
"""运行命令,失败自动重试(用于规避偶发文件锁,如 Prisma 引擎 DLL 占用)。"""
|
||
for i in range(attempts):
|
||
if run(cmd, cwd=cwd, check=False) == 0:
|
||
return True
|
||
if i < attempts - 1:
|
||
print(f"[artveris] 命令失败,{delay} 秒后重试({i + 1}/{attempts - 1})…")
|
||
time.sleep(delay)
|
||
return False
|
||
|
||
|
||
def wait_port(host: str, port: int, timeout: int = 60) -> bool:
|
||
print(f"[artveris] 等待 {host}:{port} 就绪 …")
|
||
start = time.time()
|
||
while time.time() - start < timeout:
|
||
try:
|
||
with socket.create_connection((host, port), timeout=2):
|
||
print(f"[artveris] {host}:{port} 已就绪")
|
||
return True
|
||
except OSError:
|
||
time.sleep(1.5)
|
||
print(f"[artveris] 等待 {host}:{port} 超时")
|
||
return False
|