norain 0.2.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- norain/__init__.py +3 -0
- norain/__main__.py +5 -0
- norain/block.py +281 -0
- norain/boot.py +142 -0
- norain/cli.py +748 -0
- norain/control.py +703 -0
- norain/defaults.py +42 -0
- norain/generate.py +264 -0
- norain/install.py +312 -0
- norain/maintain.py +313 -0
- norain/model.py +409 -0
- norain/monitor.py +314 -0
- norain/paths.py +124 -0
- norain/probe.py +158 -0
- norain/proxy.py +136 -0
- norain/repair.py +278 -0
- norain/routing.py +332 -0
- norain/rules.py +214 -0
- norain/runner.py +59 -0
- norain-0.2.0.dev0.dist-info/METADATA +99 -0
- norain-0.2.0.dev0.dist-info/RECORD +53 -0
- norain-0.2.0.dev0.dist-info/WHEEL +5 -0
- norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
- norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
- norain-0.2.0.dev0.dist-info/top_level.txt +3 -0
- norain_core/__init__.py +4 -0
- norain_core/apply.py +70 -0
- norain_core/atomic.py +80 -0
- norain_core/cliutil.py +68 -0
- norain_core/daemonctl.py +192 -0
- norain_core/errors.py +60 -0
- norain_core/fetch.py +158 -0
- norain_core/log.py +104 -0
- norain_core/migrate.py +86 -0
- norain_core/osutil.py +332 -0
- norain_core/redact.py +60 -0
- norain_core/secrets.py +87 -0
- norain_core/singbox.py +93 -0
- norain_core/state.py +97 -0
- norain_core/supervisor.py +352 -0
- norain_core/sysproxy.py +112 -0
- norain_core/tomlio.py +86 -0
- norain_server/__init__.py +3 -0
- norain_server/__main__.py +5 -0
- norain_server/cert.py +276 -0
- norain_server/cli.py +477 -0
- norain_server/deploy.py +604 -0
- norain_server/firewall.py +226 -0
- norain_server/generate.py +112 -0
- norain_server/model.py +272 -0
- norain_server/paths.py +101 -0
- norain_server/runner.py +123 -0
- norain_server/service.py +83 -0
norain_server/deploy.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
"""部署更新模块:install / update / uninstall / fix,以及开机自启和环境变量注册。
|
|
2
|
+
|
|
3
|
+
Linux:sing-box 装到 /usr/local/bin,配置在 /etc/norain-server,状态在 /var/lib/norain-server,
|
|
4
|
+
注册 systemd 单元,写 /etc/profile.d/norain-server.sh。
|
|
5
|
+
Windows:sing-box.exe 装到 %ProgramFiles%\\norain-server,配置在 %ProgramData%\\norain-server,
|
|
6
|
+
用开机计划任务自启,用 setx 写环境变量。
|
|
7
|
+
|
|
8
|
+
所有步骤幂等;重复安装不覆盖已有用户配置(除非 --force);安装失败按相反顺序回滚。
|
|
9
|
+
已在真实 Ubuntu 上验证:install / reload / fix / update / uninstall,以及 systemd 开机自启(含真实重启)。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import socket
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Callable
|
|
22
|
+
|
|
23
|
+
from norain_core import fetch, osutil, singbox
|
|
24
|
+
from norain_core.errors import EXIT_CONFIG, EXIT_CONFLICT, EXIT_EXTERNAL, NorainError
|
|
25
|
+
from norain_core.log import new_op_id
|
|
26
|
+
from norain_core.secrets import generate_to_file
|
|
27
|
+
from norain_core.state import RUNNING, STOPPED, get_desired, read_json, set_desired, write_json
|
|
28
|
+
|
|
29
|
+
from . import cert as certmod
|
|
30
|
+
from . import firewall, generate, runner
|
|
31
|
+
from .model import load_config
|
|
32
|
+
from .paths import Paths
|
|
33
|
+
from .service import UNIT, pick_backend
|
|
34
|
+
|
|
35
|
+
SERVICE_USER = "norain"
|
|
36
|
+
TASK_NAME = "norain-server"
|
|
37
|
+
ENV_NAME = "norain-server"
|
|
38
|
+
UNIT_PATH = Path("/etc/systemd/system") / UNIT
|
|
39
|
+
|
|
40
|
+
_UNIT_TEMPLATE = """\
|
|
41
|
+
# 由 norain-server install 生成。职责见 docs/decisions/0012:Python 守护负责重启 sing-box,
|
|
42
|
+
# systemd 只在守护进程自身异常退出时把它拉起。
|
|
43
|
+
[Unit]
|
|
44
|
+
Description=Norain server (sing-box supervisor)
|
|
45
|
+
After=network-online.target
|
|
46
|
+
Wants=network-online.target
|
|
47
|
+
StartLimitIntervalSec=600
|
|
48
|
+
StartLimitBurst=5
|
|
49
|
+
|
|
50
|
+
[Service]
|
|
51
|
+
Type=simple
|
|
52
|
+
User={user}
|
|
53
|
+
Group={user}
|
|
54
|
+
EnvironmentFile=-{home}/env
|
|
55
|
+
# 用户手动 stop 之后(期望状态为 stopped),开机时跳过启动,不算失败
|
|
56
|
+
ExecCondition={python} -m norain_server _desired-state-is running
|
|
57
|
+
ExecStart={python} -m norain_server run
|
|
58
|
+
Restart=on-failure
|
|
59
|
+
RestartSec=5
|
|
60
|
+
# 3=配置无效 5=缺少 sing-box 9=已达连续重启上限:这些情况再拉起也没用,避免无限循环
|
|
61
|
+
RestartPreventExitStatus=3 5 9
|
|
62
|
+
KillMode=mixed
|
|
63
|
+
TimeoutStopSec=20
|
|
64
|
+
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
65
|
+
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
|
|
66
|
+
NoNewPrivileges=true
|
|
67
|
+
ProtectSystem=strict
|
|
68
|
+
ProtectHome={protect_home}
|
|
69
|
+
PrivateTmp=true
|
|
70
|
+
ReadWritePaths={state} {log}
|
|
71
|
+
|
|
72
|
+
[Install]
|
|
73
|
+
WantedBy=multi-user.target
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _env_vars(paths: Paths) -> dict[str, str]:
|
|
78
|
+
return {"NORAIN_SERVER_HOME": str(paths.home), "NORAIN_SERVER_CONFIG": str(paths.config),
|
|
79
|
+
"NORAIN_SERVER_STATE": str(paths.state), "NORAIN_SERVER_LOG": str(paths.log_dir),
|
|
80
|
+
"NORAIN_SERVER_SINGBOX": str(paths.default_singbox)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def default_config_text(paths: Paths, env, *, secret_ref: str) -> str:
|
|
84
|
+
"""生成默认 server.toml。NORAIN_DOMAIN / NORAIN_HY2_PORT / NORAIN_TROJAN_PORT /
|
|
85
|
+
NORAIN_CERT_MODE 在安装时写进文件,之后不依赖这些环境变量仍然存在。"""
|
|
86
|
+
domain = (env.get("NORAIN_DOMAIN") or "").strip() or socket.gethostname()
|
|
87
|
+
mode = (env.get("NORAIN_CERT_MODE") or "").strip() or "self-signed"
|
|
88
|
+
def port_env(name: str, default: int) -> int:
|
|
89
|
+
raw = (env.get(name) or "").strip()
|
|
90
|
+
if not raw:
|
|
91
|
+
return default
|
|
92
|
+
try:
|
|
93
|
+
return int(raw)
|
|
94
|
+
except ValueError:
|
|
95
|
+
raise NorainError(f"环境变量 {name} 必须是整数", exit_code=EXIT_CONFIG, module="deploy") from None
|
|
96
|
+
|
|
97
|
+
hy2 = port_env("NORAIN_HY2_PORT", 443)
|
|
98
|
+
trojan_port = env.get("NORAIN_TROJAN_PORT")
|
|
99
|
+
trojan = port_env("NORAIN_TROJAN_PORT", 443) if trojan_port else 443
|
|
100
|
+
def q(value: str) -> str:
|
|
101
|
+
# JSON basic-string escaping is also valid TOML basic-string escaping.
|
|
102
|
+
# Values come from environment variables and paths, so interpolating them
|
|
103
|
+
# directly would make quotes, backslashes, or newlines corrupt the file.
|
|
104
|
+
return json.dumps(str(value), ensure_ascii=False)
|
|
105
|
+
|
|
106
|
+
lines = [
|
|
107
|
+
"# 由 norain-server install 生成。修改后运行 norain-server config validate 和 norain-server restart",
|
|
108
|
+
"schema = 1", "",
|
|
109
|
+
"[server]", f"domain = {q(domain)}", 'listen = "::"', "",
|
|
110
|
+
"[protocols.hysteria2]", "enabled = true", f"port = {hy2}", "",
|
|
111
|
+
"[protocols.trojan]", f"enabled = {'true' if trojan_port else 'false'}",
|
|
112
|
+
f"port = {trojan}", "",
|
|
113
|
+
"[auth]", f"credential_ref = {q(secret_ref)}", "",
|
|
114
|
+
"[tls]", f"mode = {q(mode)}",
|
|
115
|
+
]
|
|
116
|
+
if mode == "acme" and env.get("NORAIN_ACME_EMAIL"):
|
|
117
|
+
lines.append(f"email = {q(env['NORAIN_ACME_EMAIL'])}")
|
|
118
|
+
lines += ["", "[service]", "check_interval_seconds = 30", "restart_limit = 3",
|
|
119
|
+
"restart_backoff_seconds = 2", "",
|
|
120
|
+
"[logging]", 'directory = ""', 'level = "info"', "max_size_mb = 20", "retain_files = 5", ""]
|
|
121
|
+
return "\n".join(lines)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ---- 属主与目录 ----------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def _service_ids() -> tuple[int, int] | None:
|
|
127
|
+
if os.name != "posix":
|
|
128
|
+
return None
|
|
129
|
+
import pwd
|
|
130
|
+
try:
|
|
131
|
+
pw = pwd.getpwnam(SERVICE_USER)
|
|
132
|
+
except KeyError:
|
|
133
|
+
return None
|
|
134
|
+
return pw.pw_uid, pw.pw_gid
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sync_ownership(paths: Paths) -> None:
|
|
138
|
+
"""root 执行过的命令会在状态目录留下 root 属主的 0600 文件,守护进程(norain 用户)读不到,
|
|
139
|
+
表现为「start 之后服务不启动」。所以每条命令结束时把目录属主同步回服务用户。
|
|
140
|
+
只在通过 install 安装过(存在安装记录)时执行。"""
|
|
141
|
+
ids = _service_ids()
|
|
142
|
+
if ids is None or os.geteuid() != 0 or not paths.install_record.exists():
|
|
143
|
+
return
|
|
144
|
+
for top in (paths.home, paths.state, paths.log_dir):
|
|
145
|
+
if not top.exists():
|
|
146
|
+
continue
|
|
147
|
+
for root, dirs, files in os.walk(top):
|
|
148
|
+
for name in (".", *dirs, *files):
|
|
149
|
+
try:
|
|
150
|
+
os.chown(os.path.join(root, name), *ids)
|
|
151
|
+
except OSError:
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _ensure_user(undo: list) -> None:
|
|
156
|
+
if os.name != "posix" or _service_ids() is not None:
|
|
157
|
+
return
|
|
158
|
+
osutil.run_checked(["useradd", "--system", "--home-dir", "/var/lib/norain-server", "--shell",
|
|
159
|
+
"/usr/sbin/nologin", SERVICE_USER], what="创建服务用户", module="deploy")
|
|
160
|
+
undo.append(lambda: osutil.run(["userdel", SERVICE_USER]))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _ensure_dirs(paths: Paths) -> None:
|
|
164
|
+
for d, mode in ((paths.home, 0o750), (paths.state, 0o750), (paths.log_dir, 0o750),
|
|
165
|
+
(paths.tls_dir, 0o700), (paths.secrets_dir, 0o700), (paths.run_dir, 0o700)):
|
|
166
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
os.chmod(d, mode)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# ---- 自启动 --------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
def _write_unit(paths: Paths) -> None:
|
|
173
|
+
exe = sys.executable
|
|
174
|
+
protect = "read-only" if exe.startswith("/home/") else "true"
|
|
175
|
+
UNIT_PATH.write_text(_UNIT_TEMPLATE.format(
|
|
176
|
+
user=SERVICE_USER, home=paths.home, python=exe, protect_home=protect,
|
|
177
|
+
state=paths.state, log=paths.log_dir), encoding="utf-8")
|
|
178
|
+
env_file = paths.home / "env"
|
|
179
|
+
env_file.write_text("".join(f"{k}={v}\n" for k, v in _env_vars(paths).items()), encoding="utf-8")
|
|
180
|
+
os.chmod(env_file, 0o640)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _venv_package() -> str:
|
|
184
|
+
return f"python3.{sys.version_info.minor}-venv"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _ensure_prereqs(steps: list[str], warnings: list[str]) -> None:
|
|
188
|
+
"""补齐运行 norain-server 需要的前置条件(Linux)。
|
|
189
|
+
|
|
190
|
+
安装器本身已经是 Python 程序,所以“装 Python 本身”由引导脚本 scripts/bootstrap-server.sh 做;
|
|
191
|
+
这里补的是 venv 模块和 pip——Debian/Ubuntu 上要单独装(python3.X-venv / python3-pip),
|
|
192
|
+
否则给服务建虚拟环境、装依赖都会失败。只在有 apt-get 且是 root 时自动装,其余发行版给出命令。
|
|
193
|
+
"""
|
|
194
|
+
if osutil.IS_WINDOWS or not shutil.which("systemctl"):
|
|
195
|
+
return
|
|
196
|
+
missing: list[str] = []
|
|
197
|
+
if osutil.run([sys.executable, "-c", "import venv"]).returncode != 0:
|
|
198
|
+
missing.append(_venv_package())
|
|
199
|
+
if osutil.run([sys.executable, "-m", "pip", "--version"]).returncode != 0:
|
|
200
|
+
missing.append("python3-pip")
|
|
201
|
+
if not missing:
|
|
202
|
+
return
|
|
203
|
+
if shutil.which("apt-get") and osutil.is_admin():
|
|
204
|
+
for pkg in missing:
|
|
205
|
+
osutil.run_checked(["apt-get", "install", "-y", "-q", pkg],
|
|
206
|
+
what=f"安装前置依赖 {pkg}", module="deploy")
|
|
207
|
+
steps.append(f"前置依赖:已安装 {pkg}")
|
|
208
|
+
return
|
|
209
|
+
warnings.append("缺少前置依赖:" + "、".join(missing) + ";请手动安装后重试")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def register_autostart(paths: Paths) -> str:
|
|
213
|
+
if osutil.IS_WINDOWS:
|
|
214
|
+
cmd = osutil.quote_cmd([sys.executable, "-m", "norain_server", "run", "--if-desired"])
|
|
215
|
+
osutil.task_create(TASK_NAME, cmd, trigger="ONSTART", highest=True, as_system=True)
|
|
216
|
+
return f"计划任务 {TASK_NAME}(开机时以 SYSTEM 运行)"
|
|
217
|
+
if not shutil.which("systemctl"):
|
|
218
|
+
raise NorainError("没有 systemd,无法注册开机自启", exit_code=EXIT_EXTERNAL, module="deploy",
|
|
219
|
+
hint="可以手动把 `norain-server run` 加到你的服务管理器")
|
|
220
|
+
_write_unit(paths)
|
|
221
|
+
osutil.run_checked(["systemctl", "daemon-reload"], what="重载 systemd", module="deploy")
|
|
222
|
+
osutil.run_checked(["systemctl", "enable", UNIT], what="启用开机自启", module="deploy")
|
|
223
|
+
return f"systemd 单元 {UNIT_PATH}"
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def unregister_autostart() -> list[str]:
|
|
227
|
+
done = []
|
|
228
|
+
if osutil.IS_WINDOWS:
|
|
229
|
+
if osutil.task_delete(TASK_NAME):
|
|
230
|
+
done.append(f"删除计划任务 {TASK_NAME}")
|
|
231
|
+
return done
|
|
232
|
+
if UNIT_PATH.exists():
|
|
233
|
+
osutil.run(["systemctl", "disable", "--now", UNIT])
|
|
234
|
+
UNIT_PATH.unlink(missing_ok=True)
|
|
235
|
+
osutil.run(["systemctl", "daemon-reload"])
|
|
236
|
+
osutil.run(["systemctl", "reset-failed", UNIT])
|
|
237
|
+
done.append(f"删除 {UNIT_PATH}")
|
|
238
|
+
return done
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _check_service_user_can_run() -> str | None:
|
|
242
|
+
"""守护进程以 norain 用户运行,它必须能导入本程序。返回警告文字或 None。"""
|
|
243
|
+
if os.name != "posix" or not shutil.which("runuser"):
|
|
244
|
+
return None
|
|
245
|
+
proc = osutil.run(["runuser", "-u", SERVICE_USER, "--", sys.executable, "-c", "import norain_server"],
|
|
246
|
+
timeout=30)
|
|
247
|
+
if proc.returncode != 0:
|
|
248
|
+
return (f"用户 {SERVICE_USER} 无法导入 norain_server(Python 装在它读不到的位置,例如 /root 下)。"
|
|
249
|
+
"请把 Norain 安装到系统级位置(例如 pip install 到 /usr/local 或 /opt 下的虚拟环境)")
|
|
250
|
+
return None
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ---- 安装 ----------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
def summary(paths: Paths) -> dict:
|
|
256
|
+
"""部署摘要,不含密码明文。"""
|
|
257
|
+
cfg = load_config(paths.config)
|
|
258
|
+
secret = generate.resolve_secret(cfg)
|
|
259
|
+
st = runner.cert_status(cfg, paths, service_running=True)
|
|
260
|
+
return {
|
|
261
|
+
"domain": cfg.server.domain,
|
|
262
|
+
"protocols": [{"name": label, "port": port, "transport": proto}
|
|
263
|
+
for proto, port, label in runner.firewall_ports(cfg) if label != "acme"],
|
|
264
|
+
"tls": {"mode": cfg.tls.mode, "fingerprint_sha256": st.fingerprint_sha256,
|
|
265
|
+
"not_after": st.not_after, "self_signed": st.self_signed},
|
|
266
|
+
"auth": {"source": secret.source, "fingerprint": secret.fingerprint},
|
|
267
|
+
"paths": {"config": str(paths.config), "state": str(paths.state), "log": str(paths.log_dir),
|
|
268
|
+
"singbox": str(paths.default_singbox)},
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def install(paths: Paths, *, force: bool = False, archive: Path | None = None,
|
|
273
|
+
sha256: str | None = None, singbox_path: Path | None = None, start: bool = True,
|
|
274
|
+
open_firewall: bool = True, env=None) -> dict:
|
|
275
|
+
env = os.environ if env is None else env
|
|
276
|
+
osutil.require_admin("安装服务端", module="deploy")
|
|
277
|
+
undo: list[Callable[[], object]] = []
|
|
278
|
+
steps: list[str] = []
|
|
279
|
+
warnings: list[str] = []
|
|
280
|
+
fresh_state = not paths.state.exists()
|
|
281
|
+
try:
|
|
282
|
+
_ensure_prereqs(steps, warnings)
|
|
283
|
+
# 1. 目录和服务用户
|
|
284
|
+
_ensure_user(undo)
|
|
285
|
+
_ensure_dirs(paths)
|
|
286
|
+
if fresh_state:
|
|
287
|
+
undo.append(lambda: shutil.rmtree(paths.state, ignore_errors=True))
|
|
288
|
+
steps.append("目录就绪")
|
|
289
|
+
|
|
290
|
+
# 2. sing-box(校验 SHA-256,再核对版本和构建标签)
|
|
291
|
+
had_bin = paths.default_singbox.is_file()
|
|
292
|
+
info = fetch.install_singbox(paths.default_singbox, paths.cache_dir, archive=archive,
|
|
293
|
+
expected_sha256=sha256, existing=singbox_path,
|
|
294
|
+
need_tags={"with_quic"})
|
|
295
|
+
if not had_bin:
|
|
296
|
+
undo.append(lambda: paths.default_singbox.unlink(missing_ok=True))
|
|
297
|
+
steps.append(f"sing-box {info.version} → {paths.default_singbox}")
|
|
298
|
+
|
|
299
|
+
# 3. 密码:NORAIN_PASSWORD 注入,否则生成;已有的密码文件不覆盖
|
|
300
|
+
secret_file = paths.secrets_dir / "password"
|
|
301
|
+
injected = (env.get("NORAIN_PASSWORD") or "").strip()
|
|
302
|
+
if injected and (force or not secret_file.exists()):
|
|
303
|
+
old = secret_file.read_bytes() if secret_file.exists() else None
|
|
304
|
+
fd = os.open(secret_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
305
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
306
|
+
f.write(injected + "\n")
|
|
307
|
+
if old is None:
|
|
308
|
+
undo.append(lambda: secret_file.unlink(missing_ok=True))
|
|
309
|
+
else: # --force 覆盖了已有密码:失败时还原
|
|
310
|
+
undo.append(lambda old=old: (secret_file.write_bytes(old), os.chmod(secret_file, 0o600)))
|
|
311
|
+
steps.append("密码取自 NORAIN_PASSWORD,已写入密码文件")
|
|
312
|
+
elif not secret_file.exists():
|
|
313
|
+
generate_to_file(secret_file)
|
|
314
|
+
undo.append(lambda: secret_file.unlink(missing_ok=True))
|
|
315
|
+
steps.append(f"已生成随机密码:{secret_file}")
|
|
316
|
+
|
|
317
|
+
# 4. 配置:已有的用户配置不覆盖,除非 --force(覆盖前备份)
|
|
318
|
+
if paths.config.exists() and not force:
|
|
319
|
+
steps.append(f"保留已有配置 {paths.config}")
|
|
320
|
+
else:
|
|
321
|
+
if paths.config.exists():
|
|
322
|
+
bak = paths.config.with_name(f"{paths.config.name}.{time.strftime('%Y%m%dT%H%M%S')}.bak")
|
|
323
|
+
shutil.copy2(paths.config, bak)
|
|
324
|
+
undo.append(lambda bak=bak: shutil.copy2(bak, paths.config)) # --force 失败时还原旧配置
|
|
325
|
+
steps.append(f"已备份旧配置到 {bak}")
|
|
326
|
+
else:
|
|
327
|
+
undo.append(lambda: paths.config.unlink(missing_ok=True))
|
|
328
|
+
paths.config.write_text(
|
|
329
|
+
default_config_text(paths, env, secret_ref=f"file:{secret_file.as_posix()}"),
|
|
330
|
+
encoding="utf-8")
|
|
331
|
+
os.chmod(paths.config, 0o640)
|
|
332
|
+
steps.append(f"已写入默认配置 {paths.config}")
|
|
333
|
+
|
|
334
|
+
# 5. 证书:self-signed 模式且还没有证书时生成(模式已在配置里显式写明)
|
|
335
|
+
clean_env = {k: v for k, v in env.items() if not k.startswith("NORAIN_") or k == "NORAIN_PASSWORD"}
|
|
336
|
+
cfg = load_config(paths.config, env=clean_env)
|
|
337
|
+
if cfg.tls.mode == "self-signed":
|
|
338
|
+
c, k = generate.cert_paths(cfg, paths)
|
|
339
|
+
if not (c.exists() and k.exists()):
|
|
340
|
+
certmod.self_signed(cfg.server.domain, c, k, force=True)
|
|
341
|
+
steps.append(f"已生成自签证书 {c}")
|
|
342
|
+
|
|
343
|
+
# 6. 生成 sing-box.json 并用 sing-box check 校验
|
|
344
|
+
prep = runner.prepare(paths, apply=True)
|
|
345
|
+
steps.append(f"配置校验通过(版本 {prep.applied.version})")
|
|
346
|
+
|
|
347
|
+
# 7. 安装记录、属主、启动器、环境变量、自启动
|
|
348
|
+
write_json(paths.install_record, {"installed_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
|
349
|
+
"singbox_installed_by_norain": not had_bin or bool(
|
|
350
|
+
(read_json(paths.install_record) or {}).get(
|
|
351
|
+
"singbox_installed_by_norain")),
|
|
352
|
+
"python": sys.executable})
|
|
353
|
+
sync_ownership(paths)
|
|
354
|
+
launcher_dir = paths.install_dir
|
|
355
|
+
if not shutil.which("norain-server"):
|
|
356
|
+
osutil.write_launcher(launcher_dir, "norain-server", "norain_server")
|
|
357
|
+
undo.append(lambda: osutil.remove_launcher(launcher_dir, "norain-server"))
|
|
358
|
+
steps.append(f"启动器:{launcher_dir}")
|
|
359
|
+
env_vars = _env_vars(paths)
|
|
360
|
+
if osutil.IS_WINDOWS: # 最初目标:Windows 用 setx 写 HOME 和 CONFIG
|
|
361
|
+
env_vars = {k: env_vars[k] for k in ("NORAIN_SERVER_HOME", "NORAIN_SERVER_CONFIG")}
|
|
362
|
+
steps += osutil.persist_env(env_vars, system=True, name=ENV_NAME,
|
|
363
|
+
path_dirs=(str(launcher_dir),) if osutil.IS_WINDOWS else ())
|
|
364
|
+
undo.append(lambda: osutil.unpersist_env(list(env_vars), system=True, name=ENV_NAME,
|
|
365
|
+
path_dirs=(str(launcher_dir),) if osutil.IS_WINDOWS else ()))
|
|
366
|
+
steps.append("开机自启:" + register_autostart(paths))
|
|
367
|
+
undo.append(unregister_autostart)
|
|
368
|
+
warn = _check_service_user_can_run()
|
|
369
|
+
if warn:
|
|
370
|
+
warnings.append(warn)
|
|
371
|
+
|
|
372
|
+
# 8. 防火墙(失败只警告:安装本身不应因为防火墙后端的问题回滚)
|
|
373
|
+
if open_firewall:
|
|
374
|
+
try:
|
|
375
|
+
fw = firewall.open_ports(cfg, paths)
|
|
376
|
+
steps.append("防火墙:" + ("已放行 " + "、".join(fw["ports"]) if fw.get("applied")
|
|
377
|
+
else fw.get("note", "需要手动放行")))
|
|
378
|
+
except NorainError as e:
|
|
379
|
+
warnings.append(f"防火墙未放行:{e.message}")
|
|
380
|
+
|
|
381
|
+
# 9. 启动测试,失败回滚
|
|
382
|
+
if start:
|
|
383
|
+
op_id = new_op_id()
|
|
384
|
+
set_desired(paths.desired, RUNNING, op_id=op_id)
|
|
385
|
+
sync_ownership(paths)
|
|
386
|
+
backend = pick_backend(paths)
|
|
387
|
+
undo.append(lambda: (set_desired(paths.desired, STOPPED, op_id=op_id), backend.stop()))
|
|
388
|
+
backend.start()
|
|
389
|
+
deadline = time.monotonic() + 30
|
|
390
|
+
while time.monotonic() < deadline:
|
|
391
|
+
st = backend.status()
|
|
392
|
+
if st.state == "running" and st.child_pid:
|
|
393
|
+
break
|
|
394
|
+
if st.state == "failed":
|
|
395
|
+
break
|
|
396
|
+
time.sleep(0.5)
|
|
397
|
+
else:
|
|
398
|
+
st = backend.status()
|
|
399
|
+
if not (st.state == "running" and st.child_pid):
|
|
400
|
+
last = (read_json(paths.last_error) or {}).get("message", "sing-box 没有进入运行状态")
|
|
401
|
+
raise NorainError(f"启动测试失败:{last}", exit_code=EXIT_EXTERNAL, module="deploy",
|
|
402
|
+
hint="已回滚本次安装所做的修改;用户配置和日志保留")
|
|
403
|
+
steps.append(f"启动测试通过({backend.name})")
|
|
404
|
+
except BaseException:
|
|
405
|
+
for fn in reversed(undo):
|
|
406
|
+
try:
|
|
407
|
+
fn()
|
|
408
|
+
except Exception: # noqa: BLE001 回滚尽力而为,不能掩盖原始错误
|
|
409
|
+
pass
|
|
410
|
+
raise
|
|
411
|
+
sync_ownership(paths)
|
|
412
|
+
return {"steps": steps, "warnings": warnings, "summary": summary(paths)}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
# ---- 更新 ----------------------------------------------------------------------
|
|
416
|
+
|
|
417
|
+
def backup_user_data(paths: Paths) -> Path:
|
|
418
|
+
"""更新前备份配置和证书。"""
|
|
419
|
+
dest = paths.backups / f"update-{time.strftime('%Y%m%dT%H%M%S')}"
|
|
420
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
421
|
+
os.chmod(dest, 0o700)
|
|
422
|
+
if paths.config.exists():
|
|
423
|
+
shutil.copy2(paths.config, dest / paths.config.name)
|
|
424
|
+
for src, name in ((paths.tls_dir, "tls"), (paths.secrets_dir, "secrets"), (paths.acme_dir, "acme")):
|
|
425
|
+
if src.is_dir():
|
|
426
|
+
shutil.copytree(src, dest / name, dirs_exist_ok=True)
|
|
427
|
+
if paths.default_singbox.is_file():
|
|
428
|
+
shutil.copy2(paths.default_singbox, dest / paths.default_singbox.name)
|
|
429
|
+
return dest
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def update(paths: Paths, *, archive: Path | None = None, sha256: str | None = None,
|
|
433
|
+
singbox_path: Path | None = None) -> dict:
|
|
434
|
+
"""把 sing-box 换成本版本锁定的版本,重写单元和环境变量,重新生成配置。
|
|
435
|
+
Python 代码本身的升级由包管理器(pip)完成,升级后再运行本命令。"""
|
|
436
|
+
osutil.require_admin("更新服务端", module="deploy")
|
|
437
|
+
steps = []
|
|
438
|
+
backup = backup_user_data(paths)
|
|
439
|
+
steps.append(f"已备份配置和证书到 {backup}")
|
|
440
|
+
cfg = load_config(paths.config)
|
|
441
|
+
was_running = get_desired(paths.desired) == RUNNING
|
|
442
|
+
old_bin = backup / paths.default_singbox.name
|
|
443
|
+
try:
|
|
444
|
+
info = fetch.install_singbox(paths.default_singbox, paths.cache_dir, archive=archive,
|
|
445
|
+
expected_sha256=sha256, existing=singbox_path,
|
|
446
|
+
need_tags=runner.need_tags(cfg))
|
|
447
|
+
steps.append(f"sing-box {info.version}")
|
|
448
|
+
prep = runner.prepare(paths, apply=True)
|
|
449
|
+
steps.append(f"配置校验通过(版本 {prep.applied.version})")
|
|
450
|
+
steps.append("开机自启:" + register_autostart(paths))
|
|
451
|
+
sync_ownership(paths)
|
|
452
|
+
if was_running:
|
|
453
|
+
backend = pick_backend(paths)
|
|
454
|
+
backend.stop()
|
|
455
|
+
backend.start()
|
|
456
|
+
steps.append("已重启服务")
|
|
457
|
+
except NorainError:
|
|
458
|
+
if old_bin.is_file(): # 恢复旧二进制并尽量恢复服务
|
|
459
|
+
shutil.copy2(old_bin, paths.default_singbox)
|
|
460
|
+
if was_running:
|
|
461
|
+
try:
|
|
462
|
+
pick_backend(paths).start()
|
|
463
|
+
except NorainError:
|
|
464
|
+
pass
|
|
465
|
+
raise
|
|
466
|
+
return {"steps": steps, "backup": str(backup), "singbox_version": singbox.PINNED_VERSION}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# ---- 卸载 ----------------------------------------------------------------------
|
|
470
|
+
|
|
471
|
+
def uninstall(paths: Paths, *, purge: bool = False) -> dict:
|
|
472
|
+
"""清理自启动项、环境变量、防火墙规则、二进制和状态目录。默认保留配置和日志,--purge 才删除。"""
|
|
473
|
+
osutil.require_admin("卸载服务端", module="deploy")
|
|
474
|
+
done: list[str] = []
|
|
475
|
+
errors: list[str] = []
|
|
476
|
+
clean_state = True
|
|
477
|
+
try:
|
|
478
|
+
set_desired(paths.desired, STOPPED, op_id=new_op_id())
|
|
479
|
+
pick_backend(paths).stop()
|
|
480
|
+
done.append("已停止服务")
|
|
481
|
+
except (NorainError, OSError) as e:
|
|
482
|
+
errors.append(f"停止服务:{e}")
|
|
483
|
+
clean_state = False
|
|
484
|
+
try:
|
|
485
|
+
done += unregister_autostart()
|
|
486
|
+
except (NorainError, OSError) as e:
|
|
487
|
+
errors.append(f"清理自启动项:{e}")
|
|
488
|
+
clean_state = False
|
|
489
|
+
try:
|
|
490
|
+
fw = firewall.close_ports(paths)
|
|
491
|
+
if fw.get("closed"):
|
|
492
|
+
done.append("已移除防火墙规则:" + "、".join(fw["closed"]))
|
|
493
|
+
except NorainError as e:
|
|
494
|
+
errors.append(e.message)
|
|
495
|
+
clean_state = False
|
|
496
|
+
record = read_json(paths.install_record) or {}
|
|
497
|
+
launcher_dir = paths.install_dir
|
|
498
|
+
try:
|
|
499
|
+
done += osutil.unpersist_env(list(_env_vars(paths)), system=True, name=ENV_NAME,
|
|
500
|
+
path_dirs=(str(launcher_dir),) if osutil.IS_WINDOWS else ())
|
|
501
|
+
except NorainError as e:
|
|
502
|
+
errors.append(e.message)
|
|
503
|
+
clean_state = False
|
|
504
|
+
if osutil.remove_launcher(launcher_dir, "norain-server"):
|
|
505
|
+
done.append("已删除启动器")
|
|
506
|
+
# 只有确认是 Norain 装的才删:安装记录缺失时不能假定这个二进制属于我们
|
|
507
|
+
if record.get("singbox_installed_by_norain") is True and paths.default_singbox.is_file():
|
|
508
|
+
paths.default_singbox.unlink(missing_ok=True)
|
|
509
|
+
done.append(f"已删除 {paths.default_singbox}")
|
|
510
|
+
if osutil.IS_WINDOWS and launcher_dir.is_dir() and not any(launcher_dir.iterdir()):
|
|
511
|
+
launcher_dir.rmdir()
|
|
512
|
+
(paths.home / "env").unlink(missing_ok=True)
|
|
513
|
+
if clean_state and paths.state.exists():
|
|
514
|
+
shutil.rmtree(paths.state, ignore_errors=True)
|
|
515
|
+
if paths.state.exists():
|
|
516
|
+
errors.append(f"删除状态目录失败:{paths.state}")
|
|
517
|
+
clean_state = False
|
|
518
|
+
else:
|
|
519
|
+
done.append(f"已删除状态目录 {paths.state}")
|
|
520
|
+
elif paths.state.exists():
|
|
521
|
+
errors.append(f"服务、启动项、防火墙或环境变量未清理干净,保留状态目录 {paths.state};"
|
|
522
|
+
"处理上面的错误后重新运行 uninstall")
|
|
523
|
+
kept = []
|
|
524
|
+
if purge and clean_state:
|
|
525
|
+
for d in (paths.home, paths.log_dir):
|
|
526
|
+
if d.exists():
|
|
527
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
528
|
+
done.append(f"已删除 {d}")
|
|
529
|
+
if os.name == "posix" and _service_ids() is not None:
|
|
530
|
+
osutil.run(["userdel", SERVICE_USER])
|
|
531
|
+
done.append(f"已删除用户 {SERVICE_USER}")
|
|
532
|
+
elif purge and not clean_state:
|
|
533
|
+
errors.append("因为前面的清理失败,保留配置和日志;处理错误后重新运行 uninstall --purge")
|
|
534
|
+
kept = [str(d) for d in (paths.home, paths.log_dir) if d.exists()]
|
|
535
|
+
else:
|
|
536
|
+
kept = [str(d) for d in (paths.home, paths.log_dir) if d.exists()]
|
|
537
|
+
return {"done": done, "kept": kept, "errors": errors}
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
# ---- fix -----------------------------------------------------------------------
|
|
541
|
+
|
|
542
|
+
def fix(paths: Paths, *, env=None) -> dict:
|
|
543
|
+
"""配置重建、证书检查、缺失文件恢复(最初目标:不做客户端式的四级修复)。"""
|
|
544
|
+
env = os.environ if env is None else env
|
|
545
|
+
actions: list[str] = []
|
|
546
|
+
problems: list[str] = []
|
|
547
|
+
_ensure_dirs(paths)
|
|
548
|
+
|
|
549
|
+
secret_file = paths.secrets_dir / "password"
|
|
550
|
+
if not paths.config.exists():
|
|
551
|
+
if not secret_file.exists():
|
|
552
|
+
generate_to_file(secret_file)
|
|
553
|
+
actions.append(f"密码文件缺失,已重新生成:{secret_file}(客户端需要换成新密码)")
|
|
554
|
+
paths.config.write_text(default_config_text(paths, env, secret_ref=f"file:{secret_file}"),
|
|
555
|
+
encoding="utf-8")
|
|
556
|
+
os.chmod(paths.config, 0o640)
|
|
557
|
+
actions.append(f"配置文件缺失,已写入默认配置:{paths.config}")
|
|
558
|
+
cfg = load_config(paths.config) # 配置格式错误在这里抛出,带字段级错误
|
|
559
|
+
|
|
560
|
+
ref = cfg.auth.credential_ref
|
|
561
|
+
if ref.startswith("file:") and not Path(ref[5:]).expanduser().exists():
|
|
562
|
+
if Path(ref[5:]).expanduser() == secret_file:
|
|
563
|
+
generate_to_file(secret_file)
|
|
564
|
+
actions.append(f"密码文件缺失,已重新生成:{secret_file}(客户端需要换成新密码)")
|
|
565
|
+
else:
|
|
566
|
+
problems.append(f"密码文件不存在:{ref[5:]}(不是 Norain 管理的路径,需要手动恢复)")
|
|
567
|
+
|
|
568
|
+
try:
|
|
569
|
+
info = runner.locate_singbox(paths)
|
|
570
|
+
singbox.require(info, need_tags=runner.need_tags(cfg))
|
|
571
|
+
except NorainError as e:
|
|
572
|
+
if paths.singbox:
|
|
573
|
+
problems.append(f"{e.message}(NORAIN_SERVER_SINGBOX 指向的文件需要手动处理)")
|
|
574
|
+
else:
|
|
575
|
+
info = fetch.install_singbox(paths.default_singbox, paths.cache_dir,
|
|
576
|
+
need_tags=runner.need_tags(cfg))
|
|
577
|
+
actions.append(f"sing-box 缺失或版本不符,已重新安装 {info.version}")
|
|
578
|
+
|
|
579
|
+
st = runner.cert_status(cfg, paths, service_running=runner.service_running(paths))
|
|
580
|
+
if not st.ok:
|
|
581
|
+
if cfg.tls.mode == "self-signed":
|
|
582
|
+
c, k = generate.cert_paths(cfg, paths)
|
|
583
|
+
if c.parent == paths.tls_dir:
|
|
584
|
+
certmod.self_signed(cfg.server.domain, c, k, force=True)
|
|
585
|
+
actions.append("自签证书缺失或失效,已重新生成(客户端需要换成新证书)")
|
|
586
|
+
else:
|
|
587
|
+
problems += st.errors
|
|
588
|
+
else:
|
|
589
|
+
problems += st.errors
|
|
590
|
+
if problems:
|
|
591
|
+
raise NorainError("有问题无法自动修复:" + ";".join(problems), exit_code=EXIT_CONFLICT,
|
|
592
|
+
business_code=120 if not st.ok else 110, module="fix",
|
|
593
|
+
hint="按提示手动处理后重新运行 fix")
|
|
594
|
+
|
|
595
|
+
prep = runner.prepare(paths, apply=True)
|
|
596
|
+
actions.append(f"已重建 sing-box.json(版本 {prep.applied.version}"
|
|
597
|
+
f"{',内容有变化' if prep.applied.changed else ',内容未变'})")
|
|
598
|
+
if paths.install_record.exists():
|
|
599
|
+
missing_autostart = (not osutil.task_exists(TASK_NAME)) if osutil.IS_WINDOWS else not UNIT_PATH.exists()
|
|
600
|
+
if missing_autostart and osutil.is_admin():
|
|
601
|
+
actions.append("自启动项缺失,已恢复:" + register_autostart(paths))
|
|
602
|
+
sync_ownership(paths)
|
|
603
|
+
return {"actions": actions, "restart_needed": prep.applied.changed,
|
|
604
|
+
"warnings": st.warnings}
|