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/cli.py
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
"""norain-server 命令行(外控制模块)。
|
|
2
|
+
|
|
3
|
+
配置类:config validate/show/edit、cert check/self-signed、secret generate
|
|
4
|
+
控制类:start/stop/restart/reload/status/run、firewall open/close/status、fix
|
|
5
|
+
部署类:install/update/uninstall
|
|
6
|
+
日志: log [-f]
|
|
7
|
+
|
|
8
|
+
所有指令返回明确的退出码(norain_core.errors)。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import subprocess
|
|
18
|
+
import tempfile
|
|
19
|
+
import time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from norain_core import apply as core_apply
|
|
23
|
+
from norain_core import atomic, cliutil, osutil, singbox
|
|
24
|
+
from norain_core.errors import (BIZ_BINARY_MISSING, BIZ_CERT, BIZ_OK, BIZ_PROCESS_EXITED,
|
|
25
|
+
BIZ_RESTART_LIMIT, EXIT_CONFIG, EXIT_DEPENDENCY, EXIT_FAILURE,
|
|
26
|
+
EXIT_OK, EXIT_TIMEOUT, EXIT_USAGE, NorainError)
|
|
27
|
+
from norain_core.log import new_op_id
|
|
28
|
+
from norain_core.migrate import migration_warnings
|
|
29
|
+
from norain_core.secrets import generate_to_file
|
|
30
|
+
from norain_core.state import RUNNING, STOPPED, get_desired, op_lock, read_json, set_desired
|
|
31
|
+
|
|
32
|
+
from . import cert as certmod
|
|
33
|
+
from . import deploy, firewall, generate, runner
|
|
34
|
+
from .model import load_config
|
|
35
|
+
from .paths import Paths
|
|
36
|
+
from .service import pick_backend
|
|
37
|
+
|
|
38
|
+
_out, _fail = cliutil.out, cliutil.fail
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---- config ----------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
def cmd_config_validate(args, paths: Paths) -> int:
|
|
44
|
+
prep = runner.prepare(paths, apply=False)
|
|
45
|
+
# 生成候选并跑 sing-box check,但不替换当前配置
|
|
46
|
+
data = generate.render(prep.cfg, prep.secret, prep.paths)
|
|
47
|
+
core_apply.check_only(data, prep.paths.run_dir, prep.binary.path)
|
|
48
|
+
warnings = prep.warnings
|
|
49
|
+
_out(args, {"config": str(paths.config), "config_version": generate.version_of(data),
|
|
50
|
+
"singbox_version": prep.binary.version, "warnings": warnings},
|
|
51
|
+
"配置有效(已通过 sing-box check)" + "".join(f"\n警告:{w}" for w in warnings))
|
|
52
|
+
return EXIT_OK
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_config_show(args, paths: Paths) -> int:
|
|
56
|
+
cfg = load_config(paths.config)
|
|
57
|
+
doc = cfg.model_dump(by_alias=True)
|
|
58
|
+
doc["auth"]["password"] = "***" if cfg.auth.password else ""
|
|
59
|
+
try:
|
|
60
|
+
secret = generate.resolve_secret(cfg)
|
|
61
|
+
doc["auth"]["resolved"] = {"source": secret.source, "fingerprint": secret.fingerprint}
|
|
62
|
+
except NorainError as e:
|
|
63
|
+
doc["auth"]["resolved"] = {"error": "; ".join(f.message for f in e.field_errors) or e.message}
|
|
64
|
+
if args.json:
|
|
65
|
+
_out(args, {"config": doc}, "")
|
|
66
|
+
else:
|
|
67
|
+
print(json.dumps(doc, ensure_ascii=False, indent=2))
|
|
68
|
+
return EXIT_OK
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def cmd_config_edit(args, paths: Paths) -> int:
|
|
72
|
+
"""在编辑器里修改 server.toml。保存后先校验,通过才替换原文件;不自动重启。"""
|
|
73
|
+
editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or (
|
|
74
|
+
"notepad" if osutil.IS_WINDOWS else shutil.which("nano") or shutil.which("vi"))
|
|
75
|
+
if not editor:
|
|
76
|
+
raise NorainError("找不到编辑器", exit_code=EXIT_DEPENDENCY, module="config",
|
|
77
|
+
hint=f"设置 EDITOR 环境变量,或直接编辑 {paths.config}")
|
|
78
|
+
if not paths.config.exists():
|
|
79
|
+
raise NorainError(f"配置文件不存在:{paths.config}", exit_code=EXIT_CONFIG, business_code=110,
|
|
80
|
+
module="config", hint="运行 norain-server install 或 norain-server fix 生成默认配置")
|
|
81
|
+
fd, tmp_name = tempfile.mkstemp(prefix="server-", suffix=".toml", dir=str(paths.config.parent))
|
|
82
|
+
tmp = Path(tmp_name)
|
|
83
|
+
try:
|
|
84
|
+
with os.fdopen(fd, "wb") as f:
|
|
85
|
+
f.write(paths.config.read_bytes())
|
|
86
|
+
os.chmod(tmp, 0o600)
|
|
87
|
+
before = tmp.read_bytes()
|
|
88
|
+
subprocess.run([*editor.split(), str(tmp)], check=False)
|
|
89
|
+
after = tmp.read_bytes()
|
|
90
|
+
if after == before:
|
|
91
|
+
_out(args, {"changed": False}, "没有修改")
|
|
92
|
+
return EXIT_OK
|
|
93
|
+
try:
|
|
94
|
+
load_config(tmp)
|
|
95
|
+
except NorainError as e:
|
|
96
|
+
keep = paths.config.with_name(paths.config.name + ".rejected")
|
|
97
|
+
os.replace(tmp, keep)
|
|
98
|
+
e.hint = f"原配置没有被改动。你的修改保存在 {keep},修正后可覆盖 {paths.config}"
|
|
99
|
+
raise
|
|
100
|
+
saved = atomic.backup(paths.config, paths.backups)
|
|
101
|
+
mode = paths.config.stat().st_mode & 0o777
|
|
102
|
+
os.replace(tmp, paths.config)
|
|
103
|
+
os.chmod(paths.config, mode)
|
|
104
|
+
finally:
|
|
105
|
+
tmp.unlink(missing_ok=True)
|
|
106
|
+
_out(args, {"changed": True, "backup": str(saved) if saved else None},
|
|
107
|
+
f"配置已保存(旧配置备份在 {saved})。\n"
|
|
108
|
+
"修改不会自动生效:运行 norain-server restart,或只换证书时运行 norain-server reload。")
|
|
109
|
+
return EXIT_OK
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---- cert / secret ---------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def cmd_cert_check(args, paths: Paths) -> int:
|
|
115
|
+
cfg = load_config(paths.config)
|
|
116
|
+
tags = None
|
|
117
|
+
tags_unknown = False
|
|
118
|
+
if cfg.tls.mode == "acme":
|
|
119
|
+
try:
|
|
120
|
+
tags = runner.locate_singbox(paths).tags
|
|
121
|
+
except NorainError:
|
|
122
|
+
tags_unknown = True # 二进制不可验证时,ACME 不能报「前置条件通过」
|
|
123
|
+
st = runner.cert_status(cfg, paths, tags=tags, service_running=runner.service_running(paths),
|
|
124
|
+
tags_unknown=tags_unknown)
|
|
125
|
+
if not st.ok:
|
|
126
|
+
certmod.raise_for_mode(cfg.tls.mode, st)
|
|
127
|
+
if st.days_left is None:
|
|
128
|
+
text = f"证书模式 {cfg.tls.mode}:前置条件检查通过,证书尚未签发"
|
|
129
|
+
else:
|
|
130
|
+
text = f"证书有效,{st.days_left} 天后过期\nSHA-256 指纹:{st.fingerprint_sha256}"
|
|
131
|
+
_out(args, {"cert": st.as_dict(), "mode": cfg.tls.mode},
|
|
132
|
+
text + "".join(f"\n警告:{w}" for w in st.warnings))
|
|
133
|
+
return EXIT_OK
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cmd_cert_self_signed(args, paths: Paths) -> int:
|
|
137
|
+
if args.days <= 0:
|
|
138
|
+
raise NorainError("--days 必须是正整数", exit_code=EXIT_USAGE, module="cert")
|
|
139
|
+
c, k = paths.tls_dir / "self-signed.crt", paths.tls_dir / "self-signed.key"
|
|
140
|
+
st, method = certmod.self_signed(args.domain, c, k, days=args.days, force=args.force)
|
|
141
|
+
if not st.ok:
|
|
142
|
+
raise NorainError("生成的证书无效:" + ";".join(st.errors), exit_code=EXIT_CONFIG,
|
|
143
|
+
business_code=BIZ_CERT, module="cert")
|
|
144
|
+
_out(args, {"cert": st.as_dict(), "method": method},
|
|
145
|
+
f"已生成自签证书({method}):\n 证书:{c}\n 私钥:{k}\n"
|
|
146
|
+
f" SHA-256 指纹:{st.fingerprint_sha256}\n"
|
|
147
|
+
"在 server.toml 中设置 [tls] mode = \"self-signed\" 即可使用。"
|
|
148
|
+
"客户端需要拿到这张证书文件才能信任服务端。")
|
|
149
|
+
return EXIT_OK
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cmd_secret_generate(args, paths: Paths) -> int:
|
|
153
|
+
path = paths.secrets_dir / "password"
|
|
154
|
+
secret = generate_to_file(path, force=args.force)
|
|
155
|
+
_out(args, {"credential_ref": secret.source, "fingerprint": secret.fingerprint},
|
|
156
|
+
f"已生成密码并写入 {path}(权限 0600)。\n"
|
|
157
|
+
f"在 server.toml 中设置:[auth] credential_ref = \"{secret.source}\"\n"
|
|
158
|
+
f"密码不会显示在这里;需要配置客户端时直接查看该文件。")
|
|
159
|
+
return EXIT_OK
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ---- 生命周期 ----------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
def cmd_start(args, paths: Paths) -> int:
|
|
165
|
+
op_id = new_op_id()
|
|
166
|
+
with op_lock(paths.lock, op="start", op_id=op_id):
|
|
167
|
+
runner.prepare(paths, apply=False) # 先在前台报出配置和证书问题
|
|
168
|
+
set_desired(paths.desired, RUNNING, op_id=op_id)
|
|
169
|
+
backend = pick_backend(paths)
|
|
170
|
+
try:
|
|
171
|
+
backend.start()
|
|
172
|
+
except NorainError as e:
|
|
173
|
+
if e.exit_code == EXIT_TIMEOUT: # 超时已把守护进程停掉,别再留 running
|
|
174
|
+
set_desired(paths.desired, STOPPED, op_id=op_id)
|
|
175
|
+
raise
|
|
176
|
+
_out(args, {"state": "running", "backend": backend.name, "op_id": op_id}, "已启动")
|
|
177
|
+
return EXIT_OK
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def cmd_stop(args, paths: Paths) -> int:
|
|
181
|
+
op_id = new_op_id()
|
|
182
|
+
with op_lock(paths.lock, op="stop", op_id=op_id):
|
|
183
|
+
set_desired(paths.desired, STOPPED, op_id=op_id) # 先写期望状态,保证不会被拉起
|
|
184
|
+
backend = pick_backend(paths)
|
|
185
|
+
backend.stop()
|
|
186
|
+
_out(args, {"state": "stopped", "backend": backend.name, "op_id": op_id}, "已停止")
|
|
187
|
+
return EXIT_OK
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def cmd_restart(args, paths: Paths) -> int:
|
|
191
|
+
op_id = new_op_id()
|
|
192
|
+
with op_lock(paths.lock, op="restart", op_id=op_id):
|
|
193
|
+
runner.prepare(paths, apply=False) # 新配置无效时不动正在运行的服务
|
|
194
|
+
backend = pick_backend(paths)
|
|
195
|
+
backend.stop()
|
|
196
|
+
set_desired(paths.desired, RUNNING, op_id=op_id)
|
|
197
|
+
backend.start()
|
|
198
|
+
_out(args, {"state": "running", "backend": backend.name, "op_id": op_id}, "已重启")
|
|
199
|
+
return EXIT_OK
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def cmd_reload(args, paths: Paths) -> int:
|
|
203
|
+
"""重新检查证书并加载新配置。只重启 sing-box 子进程,不重启系统服务,也不计入失败次数。"""
|
|
204
|
+
op_id = new_op_id()
|
|
205
|
+
with op_lock(paths.lock, op="reload", op_id=op_id):
|
|
206
|
+
prep = runner.prepare(paths, apply=True) # 证书无效或 check 不通过时在这里中止,旧配置保留
|
|
207
|
+
running = pick_backend(prep.paths).status().state == "running"
|
|
208
|
+
if running:
|
|
209
|
+
paths.reload_file.parent.mkdir(parents=True, exist_ok=True)
|
|
210
|
+
paths.reload_file.write_text(op_id, encoding="utf-8")
|
|
211
|
+
deadline = time.monotonic() + 20
|
|
212
|
+
while time.monotonic() < deadline and paths.reload_file.exists():
|
|
213
|
+
time.sleep(0.2)
|
|
214
|
+
if paths.reload_file.exists():
|
|
215
|
+
paths.reload_file.unlink(missing_ok=True)
|
|
216
|
+
raise NorainError("守护进程没有响应重载请求", exit_code=6, module="daemon", retryable=True,
|
|
217
|
+
hint="运行 norain-server restart")
|
|
218
|
+
warnings = prep.warnings
|
|
219
|
+
_out(args, {"reloaded": running, "config_version": prep.applied.version,
|
|
220
|
+
"config_changed": prep.applied.changed, "warnings": warnings, "op_id": op_id},
|
|
221
|
+
("已重载" if running else "服务没有运行,只更新了配置文件")
|
|
222
|
+
+ "".join(f"\n警告:{w}" for w in warnings))
|
|
223
|
+
return EXIT_OK
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cmd_run(args, paths: Paths) -> int:
|
|
227
|
+
if getattr(args, "if_desired", False) and get_desired(paths.desired) != RUNNING:
|
|
228
|
+
return EXIT_OK # 用户手动 stop 过:开机自启时不拉起
|
|
229
|
+
return runner.run_foreground(paths)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def cmd_fix(args, paths: Paths) -> int:
|
|
233
|
+
op_id = new_op_id()
|
|
234
|
+
with op_lock(paths.lock, op="fix", op_id=op_id):
|
|
235
|
+
res = deploy.fix(paths)
|
|
236
|
+
_out(args, {**res, "op_id": op_id},
|
|
237
|
+
"\n".join(res["actions"]) + "".join(f"\n警告:{w}" for w in res["warnings"])
|
|
238
|
+
+ ("\n配置有变化,运行 norain-server reload 使其生效" if res["restart_needed"] else ""))
|
|
239
|
+
return EXIT_OK
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _summary_text(sm: dict) -> str:
|
|
243
|
+
lines = [f"域名:{sm['domain']}"]
|
|
244
|
+
lines += [f"协议:{p['name']} {p['port']}/{p['transport']}" for p in sm["protocols"]]
|
|
245
|
+
tls = sm["tls"]
|
|
246
|
+
lines.append(f"证书:{tls['mode']}" + (f",SHA-256 指纹 {tls['fingerprint_sha256']}"
|
|
247
|
+
if tls["fingerprint_sha256"] else "(尚未签发)"))
|
|
248
|
+
lines.append(f"密码:来源 {sm['auth']['source']},指纹 {sm['auth']['fingerprint']}(明文不显示)")
|
|
249
|
+
lines += [f"{k}:{v}" for k, v in sm["paths"].items()]
|
|
250
|
+
return "\n".join(lines)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def cmd_install(args, paths: Paths) -> int:
|
|
254
|
+
op_id = new_op_id()
|
|
255
|
+
paths.state.mkdir(parents=True, exist_ok=True)
|
|
256
|
+
with op_lock(paths.lock, op="install", op_id=op_id, timeout=600):
|
|
257
|
+
res = deploy.install(paths, force=args.force,
|
|
258
|
+
archive=Path(args.singbox_archive) if args.singbox_archive else None,
|
|
259
|
+
sha256=args.singbox_sha256,
|
|
260
|
+
singbox_path=Path(args.singbox_path) if args.singbox_path else None,
|
|
261
|
+
start=not args.no_start, open_firewall=not args.no_firewall)
|
|
262
|
+
_out(args, {**res, "op_id": op_id},
|
|
263
|
+
"\n".join(f"· {x}" for x in res["steps"]) + "".join(f"\n警告:{w}" for w in res["warnings"])
|
|
264
|
+
+ "\n\n服务端摘要\n" + _summary_text(res["summary"])
|
|
265
|
+
+ "\n\n环境变量在新开的终端里生效。")
|
|
266
|
+
return EXIT_OK
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def cmd_update(args, paths: Paths) -> int:
|
|
270
|
+
op_id = new_op_id()
|
|
271
|
+
with op_lock(paths.lock, op="update", op_id=op_id, timeout=600):
|
|
272
|
+
res = deploy.update(paths, archive=Path(args.singbox_archive) if args.singbox_archive else None,
|
|
273
|
+
sha256=args.singbox_sha256,
|
|
274
|
+
singbox_path=Path(args.singbox_path) if args.singbox_path else None)
|
|
275
|
+
_out(args, {**res, "op_id": op_id}, "\n".join(f"· {x}" for x in res["steps"]))
|
|
276
|
+
return EXIT_OK
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def cmd_uninstall(args, paths: Paths) -> int:
|
|
280
|
+
res = deploy.uninstall(paths, purge=args.purge)
|
|
281
|
+
text = "\n".join(f"· {x}" for x in res["done"])
|
|
282
|
+
if res["kept"]:
|
|
283
|
+
text += "\n保留(加 --purge 才删除):" + "、".join(res["kept"])
|
|
284
|
+
if res["errors"]:
|
|
285
|
+
text += "".join(f"\n未完成:{e}" for e in res["errors"])
|
|
286
|
+
_out(args, res, text)
|
|
287
|
+
return EXIT_FAILURE if res["errors"] else EXIT_OK
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def cmd_desired_is(args, paths: Paths) -> int:
|
|
291
|
+
return EXIT_OK if get_desired(paths.desired) == args.state else EXIT_FAILURE
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def build_status(paths: Paths) -> dict:
|
|
295
|
+
status: dict = {"updated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
|
296
|
+
"desired": get_desired(paths.desired)}
|
|
297
|
+
business = BIZ_OK
|
|
298
|
+
cfg = None
|
|
299
|
+
try:
|
|
300
|
+
cfg = load_config(paths.config)
|
|
301
|
+
paths = paths.with_log_dir(cfg.logging.directory)
|
|
302
|
+
status["protocols"] = [
|
|
303
|
+
{"name": n, "port": p.port, "transport": t}
|
|
304
|
+
for n, p, t in (("hysteria2", cfg.protocols.hysteria2, "udp"),
|
|
305
|
+
("trojan", cfg.protocols.trojan, "tcp")) if p.enabled]
|
|
306
|
+
status["config"] = {"valid": True, "warnings": migration_warnings(cfg)}
|
|
307
|
+
except NorainError as e:
|
|
308
|
+
business = e.business_code
|
|
309
|
+
status["config"] = {"valid": False, "errors": [f.as_dict() for f in e.field_errors] or e.message}
|
|
310
|
+
status["protocols"] = []
|
|
311
|
+
|
|
312
|
+
if cfg is not None:
|
|
313
|
+
tags, tags_unknown = None, False
|
|
314
|
+
if cfg.tls.mode == "acme":
|
|
315
|
+
try:
|
|
316
|
+
tags = runner.locate_singbox(paths).tags
|
|
317
|
+
except NorainError:
|
|
318
|
+
tags_unknown = True
|
|
319
|
+
st = runner.cert_status(cfg, paths, tags=tags, service_running=True,
|
|
320
|
+
tags_unknown=tags_unknown)
|
|
321
|
+
status["cert"] = {"ok": st.ok, "mode": cfg.tls.mode, "not_after": st.not_after,
|
|
322
|
+
"days_left": st.days_left, "self_signed": st.self_signed,
|
|
323
|
+
"errors": st.errors, "warnings": st.warnings}
|
|
324
|
+
if not st.ok and not business:
|
|
325
|
+
business = 120
|
|
326
|
+
try:
|
|
327
|
+
info = runner.locate_singbox(paths)
|
|
328
|
+
status["singbox"] = {"path": str(info.path), "version": info.version,
|
|
329
|
+
"pinned": singbox.PINNED_VERSION,
|
|
330
|
+
"version_ok": info.version == singbox.PINNED_VERSION}
|
|
331
|
+
except NorainError as e:
|
|
332
|
+
status["singbox"] = {"error": e.message}
|
|
333
|
+
business = business or BIZ_BINARY_MISSING
|
|
334
|
+
|
|
335
|
+
svc = pick_backend(paths).status()
|
|
336
|
+
status["service"] = {"backend": svc.backend, "state": svc.state, "pid": svc.pid,
|
|
337
|
+
"outer_restarts": svc.outer_restarts}
|
|
338
|
+
status["process"] = {"running": bool(svc.child_pid), "pid": svc.child_pid}
|
|
339
|
+
status["restarts"] = svc.restarts
|
|
340
|
+
meta = read_json(paths.meta_json) or {}
|
|
341
|
+
status["config"]["version"] = meta.get("config_version")
|
|
342
|
+
status["config"]["generated_at"] = meta.get("generated_at")
|
|
343
|
+
last = read_json(paths.last_error)
|
|
344
|
+
status["last_error"] = last
|
|
345
|
+
if status["desired"] == RUNNING and svc.state != "running":
|
|
346
|
+
code = (last or {}).get("business_code")
|
|
347
|
+
business = code if code else (business or BIZ_PROCESS_EXITED)
|
|
348
|
+
if svc.state == "failed" and not code:
|
|
349
|
+
business = BIZ_RESTART_LIMIT
|
|
350
|
+
elif svc.state == "running":
|
|
351
|
+
business = BIZ_OK if status["process"]["running"] else BIZ_PROCESS_EXITED
|
|
352
|
+
status["business_code"] = business
|
|
353
|
+
return status
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def cmd_status(args, paths: Paths) -> int:
|
|
357
|
+
# 最初目标:status 输出 JSON。--json 只为兼容,行为相同。
|
|
358
|
+
print(json.dumps(build_status(paths), ensure_ascii=False, indent=2))
|
|
359
|
+
return EXIT_OK
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# ---- log / firewall --------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
def cmd_log(args, paths: Paths) -> int:
|
|
365
|
+
try:
|
|
366
|
+
paths = paths.with_log_dir(load_config(paths.config).logging.directory)
|
|
367
|
+
except NorainError:
|
|
368
|
+
pass
|
|
369
|
+
return cliutil.tail(paths.log_file, lines=args.lines, follow=args.follow)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def cmd_firewall(args, paths: Paths) -> int:
|
|
373
|
+
if args.action == "close":
|
|
374
|
+
try:
|
|
375
|
+
cfg = load_config(paths.config)
|
|
376
|
+
except NorainError:
|
|
377
|
+
cfg = None # 配置损坏时仍然可以移除 Norain 创建的规则
|
|
378
|
+
res = firewall.close_ports(paths, cfg)
|
|
379
|
+
else:
|
|
380
|
+
cfg = load_config(paths.config)
|
|
381
|
+
res = firewall.open_ports(cfg, paths) if args.action == "open" else firewall.status(cfg, paths)
|
|
382
|
+
lines = [f"防火墙后端:{res.get('backend') or '无(未找到 ufw 或 firewalld)'}"]
|
|
383
|
+
if args.action == "status":
|
|
384
|
+
for row in res["ports"]:
|
|
385
|
+
state = {True: "已放行", False: "未放行", None: "未知"}[row["open"]]
|
|
386
|
+
lines.append(f" {row['port']}({row['purpose']}):{state}"
|
|
387
|
+
+ (",由 Norain 创建" if row["managed_by_norain"] else ""))
|
|
388
|
+
else:
|
|
389
|
+
for key, label in (("opened", "新放行"), ("already_open", "原本已放行"),
|
|
390
|
+
("closed_stale", "已移除不再需要的"), ("closed", "已移除")):
|
|
391
|
+
if res.get(key):
|
|
392
|
+
lines.append(f" {label}:{'、'.join(res[key])}")
|
|
393
|
+
if res.get("note"):
|
|
394
|
+
lines.append(res["note"])
|
|
395
|
+
lines += [f" {c}" for c in res.get("manual_commands", [])]
|
|
396
|
+
_out(args, res, "\n".join(lines))
|
|
397
|
+
return EXIT_OK
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# ---- 入口 --------------------------------------------------------------------
|
|
401
|
+
|
|
402
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
403
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
404
|
+
common.add_argument("--json", action="store_true", help="以 JSON 输出结果")
|
|
405
|
+
p = argparse.ArgumentParser(prog="norain-server", description="Norain 服务端")
|
|
406
|
+
sub = p.add_subparsers(dest="command", required=True, metavar="<命令>")
|
|
407
|
+
|
|
408
|
+
def add(parent, name, func, help_):
|
|
409
|
+
sp = parent.add_parser(name, parents=[common], help=help_)
|
|
410
|
+
sp.set_defaults(func=func)
|
|
411
|
+
return sp
|
|
412
|
+
|
|
413
|
+
cfg = sub.add_parser("config", help="配置").add_subparsers(dest="sub", required=True)
|
|
414
|
+
add(cfg, "validate", cmd_config_validate, "校验 server.toml 并运行 sing-box check")
|
|
415
|
+
add(cfg, "show", cmd_config_show, "显示生效配置(隐藏秘密)")
|
|
416
|
+
add(cfg, "edit", cmd_config_edit, "编辑 server.toml(保存后校验,不自动重启)")
|
|
417
|
+
|
|
418
|
+
crt = sub.add_parser("cert", help="证书").add_subparsers(dest="sub", required=True)
|
|
419
|
+
add(crt, "check", cmd_cert_check, "检查证书")
|
|
420
|
+
ss = add(crt, "self-signed", cmd_cert_self_signed, "生成自签证书")
|
|
421
|
+
ss.add_argument("--domain", required=True)
|
|
422
|
+
ss.add_argument("--days", type=int, default=365)
|
|
423
|
+
ss.add_argument("--force", action="store_true")
|
|
424
|
+
|
|
425
|
+
sec = sub.add_parser("secret", help="密码").add_subparsers(dest="sub", required=True)
|
|
426
|
+
add(sec, "generate", cmd_secret_generate, "生成随机密码文件").add_argument("--force", action="store_true")
|
|
427
|
+
|
|
428
|
+
add(sub, "start", cmd_start, "启动")
|
|
429
|
+
add(sub, "stop", cmd_stop, "停止(之后不会被自动拉起)")
|
|
430
|
+
add(sub, "restart", cmd_restart, "重启")
|
|
431
|
+
add(sub, "status", cmd_status, "输出 JSON 状态")
|
|
432
|
+
add(sub, "reload", cmd_reload, "检查证书并重新加载配置(不重启系统服务)")
|
|
433
|
+
rn = add(sub, "run", cmd_run, "前台运行守护进程(供 systemd / 计划任务调用)")
|
|
434
|
+
rn.add_argument("--if-desired", action="store_true", help="期望状态不是 running 时直接退出")
|
|
435
|
+
add(sub, "fix", cmd_fix, "重建配置、检查证书、恢复缺失文件")
|
|
436
|
+
|
|
437
|
+
def singbox_source(sp):
|
|
438
|
+
sp.add_argument("--singbox-archive", help="本地的 sing-box 压缩包(不联网)")
|
|
439
|
+
sp.add_argument("--singbox-sha256", help="压缩包的 SHA-256(默认用锁定文件里的值)")
|
|
440
|
+
sp.add_argument("--singbox-path", help="直接使用已有的 sing-box 可执行文件")
|
|
441
|
+
|
|
442
|
+
ins = add(sub, "install", cmd_install, "安装:sing-box、默认配置、开机自启、环境变量")
|
|
443
|
+
singbox_source(ins)
|
|
444
|
+
ins.add_argument("--force", action="store_true", help="覆盖已有的 server.toml(先备份)")
|
|
445
|
+
ins.add_argument("--no-start", action="store_true", help="不做启动测试")
|
|
446
|
+
ins.add_argument("--no-firewall", action="store_true", help="不修改防火墙")
|
|
447
|
+
singbox_source(add(sub, "update", cmd_update, "更新 sing-box 和自启动注册(先备份配置和证书)"))
|
|
448
|
+
un = add(sub, "uninstall", cmd_uninstall, "卸载(默认保留配置和日志)")
|
|
449
|
+
un.add_argument("--purge", action="store_true", help="同时删除配置和日志")
|
|
450
|
+
lg = add(sub, "log", cmd_log, "查看日志")
|
|
451
|
+
lg.add_argument("-f", "--follow", action="store_true")
|
|
452
|
+
lg.add_argument("-n", "--lines", type=int, default=50)
|
|
453
|
+
fw = add(sub, "firewall", cmd_firewall, "放行 / 关闭 / 查看协议端口")
|
|
454
|
+
fw.add_argument("action", choices=["open", "close", "status"])
|
|
455
|
+
ds = add(sub, "_desired-state-is", cmd_desired_is, argparse.SUPPRESS)
|
|
456
|
+
ds.add_argument("state", choices=[RUNNING, STOPPED])
|
|
457
|
+
return p
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def main(argv: list[str] | None = None) -> int:
|
|
461
|
+
args = build_parser().parse_args(argv)
|
|
462
|
+
paths = Paths.from_env()
|
|
463
|
+
try:
|
|
464
|
+
return args.func(args, paths)
|
|
465
|
+
except NorainError as e:
|
|
466
|
+
return _fail(args, e)
|
|
467
|
+
except KeyboardInterrupt:
|
|
468
|
+
return 130
|
|
469
|
+
finally:
|
|
470
|
+
try:
|
|
471
|
+
deploy.sync_ownership(paths)
|
|
472
|
+
except OSError:
|
|
473
|
+
pass
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
if __name__ == "__main__": # python -m norain_server.cli 也要能用;缺了它会静默退出 0
|
|
477
|
+
raise SystemExit(main())
|