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.
Files changed (53) hide show
  1. norain/__init__.py +3 -0
  2. norain/__main__.py +5 -0
  3. norain/block.py +281 -0
  4. norain/boot.py +142 -0
  5. norain/cli.py +748 -0
  6. norain/control.py +703 -0
  7. norain/defaults.py +42 -0
  8. norain/generate.py +264 -0
  9. norain/install.py +312 -0
  10. norain/maintain.py +313 -0
  11. norain/model.py +409 -0
  12. norain/monitor.py +314 -0
  13. norain/paths.py +124 -0
  14. norain/probe.py +158 -0
  15. norain/proxy.py +136 -0
  16. norain/repair.py +278 -0
  17. norain/routing.py +332 -0
  18. norain/rules.py +214 -0
  19. norain/runner.py +59 -0
  20. norain-0.2.0.dev0.dist-info/METADATA +99 -0
  21. norain-0.2.0.dev0.dist-info/RECORD +53 -0
  22. norain-0.2.0.dev0.dist-info/WHEEL +5 -0
  23. norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
  24. norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
  25. norain-0.2.0.dev0.dist-info/top_level.txt +3 -0
  26. norain_core/__init__.py +4 -0
  27. norain_core/apply.py +70 -0
  28. norain_core/atomic.py +80 -0
  29. norain_core/cliutil.py +68 -0
  30. norain_core/daemonctl.py +192 -0
  31. norain_core/errors.py +60 -0
  32. norain_core/fetch.py +158 -0
  33. norain_core/log.py +104 -0
  34. norain_core/migrate.py +86 -0
  35. norain_core/osutil.py +332 -0
  36. norain_core/redact.py +60 -0
  37. norain_core/secrets.py +87 -0
  38. norain_core/singbox.py +93 -0
  39. norain_core/state.py +97 -0
  40. norain_core/supervisor.py +352 -0
  41. norain_core/sysproxy.py +112 -0
  42. norain_core/tomlio.py +86 -0
  43. norain_server/__init__.py +3 -0
  44. norain_server/__main__.py +5 -0
  45. norain_server/cert.py +276 -0
  46. norain_server/cli.py +477 -0
  47. norain_server/deploy.py +604 -0
  48. norain_server/firewall.py +226 -0
  49. norain_server/generate.py +112 -0
  50. norain_server/model.py +272 -0
  51. norain_server/paths.py +101 -0
  52. norain_server/runner.py +123 -0
  53. norain_server/service.py +83 -0
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: norain
3
+ Version: 0.2.0.dev0
4
+ Summary: Norain:基于 sing-box 的 Hysteria2/Trojan 客户端与服务端控制层
5
+ Author-email: jcy0chenyuan0 <jboxi@qq.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/jcy0chenyuan0/norain
8
+ Project-URL: Repository, https://github.com/jcy0chenyuan0/norain
9
+ Project-URL: Issues, https://github.com/jcy0chenyuan0/norain/issues
10
+ Keywords: sing-box,hysteria2,trojan,proxy,vpn
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Internet :: Proxy Servers
22
+ Classifier: Topic :: System :: Networking
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: pydantic>=2.5
27
+ Requires-Dist: cryptography>=42
28
+ Requires-Dist: psutil>=5.9
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # Norain
34
+
35
+ 基于 sing-box 的 Hysteria2 / Trojan 代理:客户端 `norain` 和服务端 `norain-server`,Python 做控制层,
36
+ sing-box 做数据面,兼容 Windows 和 Linux。
37
+
38
+ **当前状态:0.2.0.dev0 预发布。两端模块代码齐备;测试套件在 Windows 上 95 项通过(3 项仅 POSIX 跳过)。
39
+ 已在真实环境验证过的部分**:生成配置通过真实 `sing-box 1.14.4 check`、本地端到端隧道、TUN 路由接管与还原、
40
+ Windows 防火墙阻断与解除、nftables 阻断、系统代理写入与还原、服务端 install/reload/fix/update/uninstall、
41
+ systemd 开机自启(真实重启)、真实 ACME 签发。**仍未验证**:客户端与 Linux 的安装流程、TUN 的实际流量、
42
+ 监控错误码、自维持互拉、分流学习闭环。逐项见 [docs/pending.md](docs/pending.md)。
43
+
44
+ 优先级:以最初目标 [docs/reference/original-goals.md](docs/reference/original-goals.md) 为准,除非有硬性 bug。
45
+
46
+ ## 客户端(九个模块)
47
+
48
+ 代理、分流、监控、自维持、阻断、修复、启动、内控制、外控制。
49
+
50
+ ```bash
51
+ norain install --server example.com # 部署:sing-box、配置、norain 命令、环境变量、开机自启动
52
+ norain start | stop | restart | status
53
+ norain config protocol auto # 自适应 / hysteria2 / trojan
54
+ norain config mode safe # 安全模式:不开机自启动
55
+ norain list white add example.com # 白名单 / black 黑名单 / blue 蓝名单 / monitor 监控名单
56
+ norain module monitor restart # 启动 / 结束 / 重启单个模块
57
+ norain repair file|builtin|full|reload # 四种修复
58
+ norain block status|off # 阻断模式;off = 手动解除
59
+ norain once monitor # 一次性执行某个模块的某个功能
60
+ norain status -t # -t:显示每个模块的运行情况和返回结果
61
+ norain uninstall
62
+ ```
63
+
64
+ ## 服务端
65
+
66
+ 干净机器上可以直接用引导脚本(系统依赖 → 虚拟环境 → 安装包 → `norain-server install`):
67
+
68
+ ```bash
69
+ sudo ./scripts/bootstrap-server.sh
70
+ ```
71
+
72
+ 已经装好 Python 与 venv 时,照常手动安装:
73
+
74
+ ```bash
75
+ NORAIN_DOMAIN=example.com NORAIN_PASSWORD=… norain-server install
76
+ norain-server start | stop | restart | reload | status
77
+ norain-server config validate|show|edit
78
+ norain-server cert check | cert self-signed --domain <域名>
79
+ norain-server firewall open|close|status
80
+ norain-server fix
81
+ norain-server update | uninstall [--purge]
82
+ ```
83
+
84
+ ## 文档
85
+
86
+ - 交接说明和未验证项目:[HANDOFF.md](HANDOFF.md)
87
+ - 实现状态清单:[docs/pending.md](docs/pending.md)
88
+ - 决策记录:[docs/decisions/](docs/decisions/README.md)
89
+ - 配置示例:[examples/server.toml](examples/server.toml)、[examples/cfg.toml](examples/cfg.toml)
90
+ - sing-box 锁定版本:[third_party/singbox.lock.toml](third_party/singbox.lock.toml)(1.14.4)
91
+
92
+ ## 开发
93
+
94
+ 需要 Python ≥ 3.11,以及 pydantic、cryptography、psutil。
95
+
96
+ ```bash
97
+ pip install -e ".[dev]"
98
+ python3 -m pytest -q
99
+ ```
@@ -0,0 +1,53 @@
1
+ norain/__init__.py,sha256=Uw4tis5K7d9Q7-OPiyxAdvHyiDzsdxqrOboTNRsRu6E,83
2
+ norain/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ norain/block.py,sha256=5DQRJTLWMvOv4rVhOTS2SDohnoutQAiLx2uWAL5MLjc,13199
4
+ norain/boot.py,sha256=wRWk3Wm9cNMGlKvcT0MZcDvJIBfTVyaIaovV828a984,5808
5
+ norain/cli.py,sha256=K7ylU4ZMcyaR1pykyDZW7AIpw1G5CCB3AHT6WsjjIB4,37657
6
+ norain/control.py,sha256=qd_GoIGHSqKb8JHUD4tkJjGLxK-SHqqUsQehjHC5IBk,35367
7
+ norain/defaults.py,sha256=s4RrC01o2eS8yM1spdSJBxf3pmwSbnKriVbi2U6Fv4M,2816
8
+ norain/generate.py,sha256=_gZGhw4N3z2_jE4JjbUQtBirsw9Sh4lL_BAYuLy5xME,11803
9
+ norain/install.py,sha256=1iYNpOHCSgEHcatq5_GMXEm0DtcNwoeRA22nbkL2lo0,14128
10
+ norain/maintain.py,sha256=Eu0gCHMPMztDQo3ITuU1X4GqHRy3E0ssmOxKgNgCfSE,14559
11
+ norain/model.py,sha256=lFhjlFNy8CZXFyPxqGrhdmCtp2u9CjdWeZtn3LpYibY,18537
12
+ norain/monitor.py,sha256=5uBgP5JpcNm4Q3bRZq3YQr1s9ElN4yky6W4V_sJ63lk,14395
13
+ norain/paths.py,sha256=2-n8sbf5xQbotXnTENfeH0faqbsnBZbdByJIn3mqjuU,5061
14
+ norain/probe.py,sha256=859BesycPd651A8ohzpyA4tgibv-fqIXgyzVh-CI9Dg,6939
15
+ norain/proxy.py,sha256=Hvd665TEw3s7QuoKB44p-uFvNt4YjHEWIBr2T6gz8kw,5280
16
+ norain/repair.py,sha256=c2EVFU9FGMPEot8ZavUjEGm4M6uUNgi3IVtr6L91MFM,12288
17
+ norain/routing.py,sha256=HlC9lu9s6baVqimgtvM0YNsOKIeWZY8-P43vi24dxIQ,16154
18
+ norain/rules.py,sha256=YOnqClBJNrj6RY5f6fC6vccLEAvu2h4fJS26uuWgxd8,9180
19
+ norain/runner.py,sha256=eCJJZrf82FMXhsMhV-AkhfY6oVbhMKOM5Do3kmHQty4,2077
20
+ norain-0.2.0.dev0.dist-info/licenses/LICENSE,sha256=KPImr4P5_JwhCejv_fwtUxFYBOGimyIX14cOn3dGKfY,1070
21
+ norain_core/__init__.py,sha256=UU-5CedGlhOWq6_W_gdvBEgQ1QraJTEr3YJboYP0uIg,223
22
+ norain_core/apply.py,sha256=ILFJK1fET0eZG_bGtD2HES3OdUkR4vx4jkiJcCKUPrk,2233
23
+ norain_core/atomic.py,sha256=QPa3bmUc9Jou-FH02yi2U2YtHkg8K2rOwfM_iiyxNOk,3030
24
+ norain_core/cliutil.py,sha256=Fy_TxOi7f6cJ7BdFQFgZciYBMP6QN4ZT63BWO3acylM,2362
25
+ norain_core/daemonctl.py,sha256=gwL50cHCt8JJbiKSUG4J-2CVa2emOm722-ucCs6VZMk,7013
26
+ norain_core/errors.py,sha256=gTfy_Kyl2tAUOnK4SYyriAumVIjLqbZMqivud0bjKu0,1465
27
+ norain_core/fetch.py,sha256=oW00Qy3wj1VHikdLK2uOrrSdK7wkqUgqlQtV4VXh9C0,6695
28
+ norain_core/log.py,sha256=k0nBS9aAttC__506uZmEmebXJDXmH9gZqFZnpt-zPuU,4039
29
+ norain_core/migrate.py,sha256=Uy1MoJ6JMvztamCRSdH3ITpSKLPdULeZYEfoOfManD4,3457
30
+ norain_core/osutil.py,sha256=XcNEHlXQ5kV9aMIM0UMtpvrCz1keOJSmVedZhZXA3Kw,14337
31
+ norain_core/redact.py,sha256=wNm3rZDsmMoUXfCTAwAEWDzvRi02csd6Ghl94TJ1Dmk,2261
32
+ norain_core/secrets.py,sha256=IJH-WLrFeepQsriyCuN4-SIV8kadYOSniy6OKVpKg4Y,3426
33
+ norain_core/singbox.py,sha256=guY1Y0uZpoP4Rq0Gu7aXAEdNX5NBXptY6OQbx4X-pgQ,4350
34
+ norain_core/state.py,sha256=loixCXFtnDYcH1X8hEUY3U3GIN5XNZIfA0UyCKvNklc,3558
35
+ norain_core/supervisor.py,sha256=XvY9QQ_b3aJY1vV4g4lhqBBVwapeuosJ1bmhQau9Zq8,14897
36
+ norain_core/sysproxy.py,sha256=SNLPpXmNjQTImhAWz-i2HW1UnDl3eLjgWj7QOoNuWb4,3829
37
+ norain_core/tomlio.py,sha256=0RR1B2NomidXUxmmpUjBMUOhFmC3GxCvSYqNMDuR9Ok,2667
38
+ norain_server/__init__.py,sha256=4CZzvpa4NNTBAxsW0cTSxTJuLO62YaIvO5OB6g9ffGo,83
39
+ norain_server/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
40
+ norain_server/cert.py,sha256=ZzFKl7a5aTXoW1WwO1JWUkhAHTExQ7iThmVNhzkahMc,12142
41
+ norain_server/cli.py,sha256=NfDvNM_cl2dEGFLSj_pBIcbAnfSDHebht_kUyi0Sppk,22381
42
+ norain_server/deploy.py,sha256=eCziWpYZX0UtZn4OKY_tRCftfoNVBhMIaCM_p5gl4eQ,28827
43
+ norain_server/firewall.py,sha256=PwjXnV56KF70sG7ZJcSaCqPXxyqNnRZQb1I-mj1bMpE,8969
44
+ norain_server/generate.py,sha256=D7xXxNj5npDYNeGjCLCNWpUY6SUGQDcEBMbv6hpyweM,4927
45
+ norain_server/model.py,sha256=BdW_5i2_ZyoWbBeKXtZTFmrNr-_znnHv_QVn2fp4C_0,10455
46
+ norain_server/paths.py,sha256=8wsxbuxHQxEvfuXAt0uwqBLZao_oTXR0UNDx5_g2bKY,3938
47
+ norain_server/runner.py,sha256=Bidp2e7DZleObX4-wuVbOefe2cfQhsYdAlqgDnFY2rI,5029
48
+ norain_server/service.py,sha256=sEcwGcYjJlhlI-QneqTljQ4HwOpymdPD129WY65jkfA,3360
49
+ norain-0.2.0.dev0.dist-info/METADATA,sha256=H90E82RUwVGKKXsgly3a1f-CjYM5LF0jYtiR3Rpl6Dk,4435
50
+ norain-0.2.0.dev0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
51
+ norain-0.2.0.dev0.dist-info/entry_points.txt,sha256=-C4KY6qWSqclp-4lOMKecWjaWdCDZYsJ4e3X1kCdJLc,82
52
+ norain-0.2.0.dev0.dist-info/top_level.txt,sha256=IDdoFZZAzQe7257dE_mn6L_DeAIfF_c_V2i_GfbsiIo,33
53
+ norain-0.2.0.dev0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ norain = norain.cli:main
3
+ norain-server = norain_server.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jcy0chenyuan0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ norain
2
+ norain_core
3
+ norain_server
@@ -0,0 +1,4 @@
1
+ """Norain 客户端与服务端共享的基础组件:退出码、脱敏、秘密引用、原子写入、日志、
2
+ 期望状态、sing-box 定位与校验、子进程监督、系统适配。"""
3
+
4
+ __version__ = "0.2.0.dev0"
norain_core/apply.py ADDED
@@ -0,0 +1,70 @@
1
+ """「生成候选 → sing-box check → 备份 → 原子替换」流程,客户端和服务端共用。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from . import __version__ as GENERATOR_VERSION
13
+ from . import atomic, singbox
14
+ from .state import write_json
15
+
16
+
17
+ def dumps(doc: dict) -> bytes:
18
+ """确定性序列化:同一输入必须得到字节级相同的输出。"""
19
+ return (json.dumps(doc, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8")
20
+
21
+
22
+ def version_of(data: bytes) -> str:
23
+ return hashlib.sha256(data).hexdigest()[:12]
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ApplyResult:
28
+ version: str
29
+ changed: bool
30
+ backup: Path | None
31
+
32
+
33
+ def _private_dir(path: Path) -> None:
34
+ path.mkdir(parents=True, exist_ok=True)
35
+ os.chmod(path, 0o700)
36
+
37
+
38
+ def check_only(data: bytes, run_dir: Path, binary: Path) -> None:
39
+ """只校验,不替换当前配置。"""
40
+ _private_dir(run_dir)
41
+ tmp = run_dir / f".validate-{os.getpid()}.json"
42
+ atomic.write_private(tmp, data)
43
+ try:
44
+ singbox.check(binary, tmp)
45
+ finally:
46
+ tmp.unlink(missing_ok=True)
47
+
48
+
49
+ def apply(data: bytes, *, run_dir: Path, current: Path, backups: Path, meta: Path, source: Path,
50
+ schema: int, binary: Path) -> ApplyResult:
51
+ """校验失败时抛出异常,当前配置保持不变。"""
52
+ _private_dir(run_dir)
53
+ candidate = run_dir / f".candidate-{os.getpid()}.json"
54
+ atomic.write_private(candidate, data)
55
+ try:
56
+ singbox.check(binary, candidate)
57
+ if current.exists() and current.read_bytes() == data:
58
+ return ApplyResult(version_of(data), False, None)
59
+ saved = atomic.promote(candidate, current, backups)
60
+ finally:
61
+ candidate.unlink(missing_ok=True)
62
+ write_json(meta, {
63
+ "config_version": version_of(data),
64
+ "generator_version": GENERATOR_VERSION,
65
+ "singbox_version": singbox.PINNED_VERSION,
66
+ "norain_schema": schema,
67
+ "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
68
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
69
+ })
70
+ return ApplyResult(version_of(data), True, saved)
norain_core/atomic.py ADDED
@@ -0,0 +1,80 @@
1
+ """原子写入和备份轮换。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+
11
+ _BINARY = getattr(os, "O_BINARY", 0) # Windows 上不加它,os.open 得到的是文本模式的描述符
12
+
13
+
14
+ def write_private(path: Path, data: bytes, *, durable: bool = True) -> None:
15
+ """以 0600 权限写入。durable=True 时 fsync(配置、秘密等掉电后必须完整的文件)。"""
16
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | _BINARY
17
+ try:
18
+ fd = os.open(path, flags, 0o600)
19
+ except FileNotFoundError: # 目录通常已经存在:只在缺失时才创建,省掉每次写入前的 mkdir
20
+ path.parent.mkdir(parents=True, exist_ok=True)
21
+ fd = os.open(path, flags, 0o600)
22
+ try:
23
+ view = memoryview(data)
24
+ while view:
25
+ view = view[os.write(fd, view):]
26
+ if durable:
27
+ os.fsync(fd)
28
+ if os.name == "posix":
29
+ os.fchmod(fd, 0o600) # 文件已存在时 os.open 的 mode 不生效
30
+ finally:
31
+ os.close(fd)
32
+
33
+
34
+ def replace(src: Path, dst: Path, *, attempts: int = 6) -> None:
35
+ """os.replace。Windows 上目标文件正被别的进程读取时会短暂报 PermissionError,重试几次。"""
36
+ for n in range(attempts):
37
+ try:
38
+ os.replace(src, dst)
39
+ return
40
+ except PermissionError:
41
+ if os.name != "nt" or n + 1 == attempts:
42
+ raise
43
+ time.sleep(0.02 * (n + 1))
44
+
45
+
46
+ def atomic_write(path: Path, data: bytes, *, durable: bool = True) -> None:
47
+ """写临时文件再原子替换。durable=False 用于高频改写的状态文件(丢了可以重建,不值得 fsync)。"""
48
+ # 临时文件名带线程 ID:同一进程的两个线程同时写同一个文件时不会互相踩临时文件
49
+ tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}-{threading.get_ident()}")
50
+ try:
51
+ write_private(tmp, data, durable=durable)
52
+ replace(tmp, path)
53
+ except BaseException:
54
+ try:
55
+ tmp.unlink(missing_ok=True)
56
+ except OSError:
57
+ pass
58
+ raise
59
+
60
+
61
+ def backup(path: Path, backup_dir: Path, *, keep: int = 5) -> Path | None:
62
+ """把 path 复制到备份目录,保留最近 keep 份。path 不存在时返回 None。"""
63
+ if not path.exists():
64
+ return None
65
+ backup_dir.mkdir(parents=True, exist_ok=True)
66
+ os.chmod(backup_dir, 0o700)
67
+ stamp = f"{time.strftime('%Y%m%dT%H%M%S')}-{time.time_ns() % 10**9:09d}"
68
+ dest = backup_dir / f"{path.name}.{stamp}"
69
+ shutil.copy2(path, dest)
70
+ os.chmod(dest, 0o600)
71
+ for stale in sorted(backup_dir.glob(f"{path.name}.*"))[:-keep]:
72
+ stale.unlink(missing_ok=True)
73
+ return dest
74
+
75
+
76
+ def promote(candidate: Path, current: Path, backup_dir: Path, *, keep: int = 5) -> Path | None:
77
+ """备份 current,再用 candidate 原子替换它。返回备份路径。"""
78
+ saved = backup(current, backup_dir, keep=keep)
79
+ replace(candidate, current)
80
+ return saved
norain_core/cliutil.py ADDED
@@ -0,0 +1,68 @@
1
+ """命令行共用的输出、错误显示和日志查看。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import json
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from .errors import EXIT_FAILURE, EXIT_OK, NorainError
12
+ from .log import new_op_id
13
+ from .redact import redact
14
+
15
+
16
+ def out(args, payload: dict, text: str) -> None:
17
+ if getattr(args, "json", False):
18
+ print(json.dumps({"ok": True, "exit_code": 0, "business_code": 0, **payload},
19
+ ensure_ascii=False, indent=2))
20
+ else:
21
+ print(text)
22
+
23
+
24
+ def fail(args, e: NorainError) -> int:
25
+ if getattr(args, "json", False):
26
+ print(json.dumps({
27
+ "ok": False, "exit_code": e.exit_code, "business_code": e.business_code,
28
+ "error_id": new_op_id(), "module": e.module, "retryable": e.retryable,
29
+ "detail": redact(e.message), "hint": e.hint,
30
+ "field_errors": [f.as_dict() for f in e.field_errors],
31
+ }, ensure_ascii=False, indent=2))
32
+ else:
33
+ print(f"错误:{redact(e.message)}", file=sys.stderr)
34
+ for f in e.field_errors:
35
+ print(f" {f.path}: {redact(f.message)}", file=sys.stderr)
36
+ if e.hint:
37
+ print(f"提示:{e.hint}", file=sys.stderr)
38
+ if e.business_code:
39
+ print(f"业务码:{e.business_code}", file=sys.stderr)
40
+ return e.exit_code or EXIT_FAILURE
41
+
42
+
43
+ def tail(path: Path, *, lines: int, follow: bool) -> int:
44
+ if not path.exists():
45
+ raise NorainError(f"还没有日志:{path}", module="log")
46
+ f = path.open("r", encoding="utf-8", errors="replace")
47
+ try:
48
+ # 只保留最后 lines 行,不把整个日志(可达几十 MB)读进内存;-n 0 不输出历史
49
+ sys.stdout.writelines(collections.deque(f, maxlen=max(lines, 0)))
50
+ sys.stdout.flush()
51
+ while follow:
52
+ line = f.readline()
53
+ if line:
54
+ sys.stdout.write(line)
55
+ sys.stdout.flush()
56
+ continue
57
+ time.sleep(0.5)
58
+ try:
59
+ if path.stat().st_size < f.tell(): # 日志已轮转
60
+ f.close()
61
+ f = path.open("r", encoding="utf-8", errors="replace")
62
+ except FileNotFoundError:
63
+ pass
64
+ except KeyboardInterrupt:
65
+ pass
66
+ finally:
67
+ f.close()
68
+ return EXIT_OK
@@ -0,0 +1,192 @@
1
+ """在后台启动、停止和查询守护进程(`python -m <模块> run`),客户端和服务端共用。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import signal
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ import psutil
14
+
15
+ from .errors import BIZ_PROCESS_EXITED, EXIT_EXTERNAL, EXIT_PERMISSION, EXIT_TIMEOUT, NorainError
16
+ from .state import read_json
17
+
18
+
19
+ @dataclass
20
+ class ServiceStatus:
21
+ backend: str
22
+ state: str # running | stopped | failed
23
+ pid: int | None = None
24
+ child_pid: int | None = None
25
+ restarts: int = 0
26
+ outer_restarts: int | None = None
27
+
28
+
29
+ def alive(pid: int | None) -> bool:
30
+ if not pid:
31
+ return False
32
+ try:
33
+ return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
34
+ except psutil.Error:
35
+ return False
36
+
37
+
38
+ def runner_info(runner_file: Path) -> dict:
39
+ info = read_json(runner_file) or {}
40
+ return info if alive(info.get("pid")) else {}
41
+
42
+
43
+ def _same_or_child(pid: int | None, launched: int) -> bool:
44
+ """pid 是我们启动的进程,或者是它的直接子进程(Windows 虚拟环境的 python.exe 是转发器)。"""
45
+ if not pid:
46
+ return False
47
+ if pid == launched:
48
+ return True
49
+ try:
50
+ return psutil.Process(pid).ppid() == launched
51
+ except psutil.Error:
52
+ return False
53
+
54
+
55
+ def _kill(pid: int | None) -> None:
56
+ try:
57
+ if pid:
58
+ psutil.Process(pid).kill()
59
+ except psutil.Error:
60
+ pass
61
+
62
+
63
+ def _kill_tree(pid: int | None) -> None:
64
+ """终止守护进程及其包装器/子进程,避免 Windows 启动器留下孤儿。"""
65
+ if not pid:
66
+ return
67
+ try:
68
+ proc = psutil.Process(pid)
69
+ children = proc.children(recursive=True)
70
+ except psutil.Error:
71
+ children = []
72
+ for child in reversed(children):
73
+ try:
74
+ child.kill()
75
+ except psutil.Error:
76
+ pass
77
+ _kill(pid)
78
+
79
+
80
+ def _unlink_quiet(path: Path) -> None:
81
+ try:
82
+ path.unlink(missing_ok=True)
83
+ except OSError:
84
+ pass
85
+
86
+
87
+ class DetachedBackend:
88
+ """没有外层保活:守护进程自身被结束后不会恢复。"""
89
+
90
+ name = "detached"
91
+
92
+ def __init__(self, *, module: str, runner_file: Path, last_error_file: Path, stop_file: Path,
93
+ log_dir: Path) -> None:
94
+ self.module, self.runner_file, self.last_error_file = module, runner_file, last_error_file
95
+ self.stop_file, self.log_dir = stop_file, log_dir
96
+
97
+ def status(self) -> ServiceStatus:
98
+ info = runner_info(self.runner_file)
99
+ if info:
100
+ return ServiceStatus(self.name, "running", info["pid"], info.get("child_pid"),
101
+ info.get("restarts", 0))
102
+ return ServiceStatus(self.name, "stopped")
103
+
104
+ def start(self, *, timeout: float = 20.0) -> None:
105
+ if runner_info(self.runner_file):
106
+ return # 幂等
107
+ self.log_dir.mkdir(parents=True, exist_ok=True)
108
+ self.last_error_file.unlink(missing_ok=True)
109
+ self.stop_file.unlink(missing_ok=True)
110
+ extra = {}
111
+ if os.name == "nt":
112
+ extra["creationflags"] = (subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
113
+ | subprocess.CREATE_NO_WINDOW)
114
+ else:
115
+ extra["start_new_session"] = True
116
+ with open(self.log_dir / "daemon.out", "ab") as out:
117
+ proc = subprocess.Popen([sys.executable, "-m", self.module, "run"],
118
+ stdin=subprocess.DEVNULL, stdout=out, stderr=out,
119
+ close_fds=True, **extra)
120
+ deadline = time.monotonic() + timeout
121
+ while time.monotonic() < deadline:
122
+ rc = proc.poll()
123
+ if rc is not None:
124
+ err = read_json(self.last_error_file) or {}
125
+ raise NorainError(
126
+ f"启动失败:{err.get('message', f'守护进程退出,退出码 {rc}')}",
127
+ exit_code=rc if 0 < rc < 10 else EXIT_EXTERNAL,
128
+ business_code=err.get("business_code", BIZ_PROCESS_EXITED), module="daemon",
129
+ hint="查看日志了解详情")
130
+ info = read_json(self.runner_file) or {}
131
+ if (_same_or_child(info.get("pid"), proc.pid) and info.get("ready")
132
+ and alive(info.get("child_pid"))):
133
+ return
134
+ time.sleep(0.1)
135
+ # 超时:先请守护进程自己停(停止请求文件),再强杀,避免留下孤儿进程占着端口、
136
+ # 稍后又被看门狗或开机自启动拉起来,而用户看到的是「启动失败」
137
+ try:
138
+ self.stop_file.parent.mkdir(parents=True, exist_ok=True)
139
+ self.stop_file.write_text("stop\n", encoding="utf-8")
140
+ except OSError:
141
+ pass
142
+ info = runner_info(self.runner_file)
143
+ try:
144
+ proc.terminate()
145
+ proc.wait(5)
146
+ except (subprocess.TimeoutExpired, OSError):
147
+ try:
148
+ proc.kill()
149
+ except OSError:
150
+ pass
151
+ # If the supervisor was a wrapper process, terminating it may leave the
152
+ # child sing-box alive. Use the last runner record as a second cleanup path.
153
+ if info and info.get("pid") == proc.pid:
154
+ _kill_tree(proc.pid)
155
+ raise NorainError("启动超时:sing-box 在限定时间内没有开始监听端口", exit_code=EXIT_TIMEOUT,
156
+ module="daemon", retryable=True, hint="查看日志了解详情")
157
+
158
+ def stop(self, *, timeout: float = 20.0) -> None:
159
+ info = runner_info(self.runner_file)
160
+ if not info:
161
+ return # 幂等
162
+ pid = info["pid"]
163
+ try:
164
+ cmd = " ".join(psutil.Process(pid).cmdline())
165
+ except psutil.Error:
166
+ return
167
+ if "norain" not in cmd:
168
+ raise NorainError(f"PID {pid} 不是 Norain 守护进程,拒绝停止", exit_code=EXIT_EXTERNAL,
169
+ module="daemon", hint=f"检查并删除过期的 {self.runner_file}")
170
+ # 停止请求文件在所有平台都有效;POSIX 上再发 SIGTERM 让它立刻响应
171
+ try:
172
+ self.stop_file.parent.mkdir(parents=True, exist_ok=True)
173
+ self.stop_file.write_text(str(os.getpid()))
174
+ except OSError:
175
+ pass
176
+ if os.name == "posix":
177
+ try:
178
+ os.kill(pid, signal.SIGTERM)
179
+ except PermissionError:
180
+ raise NorainError(f"没有权限停止 PID {pid}", exit_code=EXIT_PERMISSION,
181
+ module="daemon") from None
182
+ except ProcessLookupError:
183
+ pass
184
+ deadline = time.monotonic() + timeout
185
+ while time.monotonic() < deadline:
186
+ if not alive(pid):
187
+ break
188
+ time.sleep(0.1)
189
+ else:
190
+ _kill_tree(pid)
191
+ _unlink_quiet(self.runner_file)
192
+ _unlink_quiet(self.stop_file)
norain_core/errors.py ADDED
@@ -0,0 +1,60 @@
1
+ """CLI 退出码、业务状态码和统一异常。约定见 docs/decisions/0003。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ # CLI 进程退出码
8
+ EXIT_OK = 0
9
+ EXIT_FAILURE = 1
10
+ EXIT_USAGE = 2
11
+ EXIT_CONFIG = 3
12
+ EXIT_PERMISSION = 4
13
+ EXIT_DEPENDENCY = 5
14
+ EXIT_TIMEOUT = 6
15
+ EXIT_CONFLICT = 7
16
+ EXIT_EXTERNAL = 8
17
+ EXIT_RESTART_LIMIT = 9 # 守护达到连续重启上限;systemd 单元用它阻止外层再拉起
18
+
19
+ # 服务端业务状态码(最初目标约定)
20
+ BIZ_OK = 0
21
+ BIZ_CONFIG = 110
22
+ BIZ_CERT = 120
23
+ BIZ_PORT_IN_USE = 130
24
+ BIZ_PROCESS_EXITED = 140
25
+ BIZ_BINARY_MISSING = 150
26
+ BIZ_RESTART_LIMIT = 160
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class FieldError:
31
+ path: str
32
+ message: str
33
+
34
+ def as_dict(self) -> dict:
35
+ return {"path": self.path, "message": self.message}
36
+
37
+
38
+ @dataclass
39
+ class NorainError(Exception):
40
+ message: str
41
+ exit_code: int = EXIT_FAILURE
42
+ business_code: int = BIZ_OK
43
+ module: str = "core"
44
+ retryable: bool = False
45
+ hint: str = ""
46
+ field_errors: list[FieldError] = field(default_factory=list)
47
+
48
+ def __str__(self) -> str:
49
+ return self.message
50
+
51
+
52
+ def config_error(errors: list[FieldError], *, module: str = "config") -> NorainError:
53
+ return NorainError(
54
+ message="配置无效",
55
+ exit_code=EXIT_CONFIG,
56
+ business_code=BIZ_CONFIG,
57
+ module=module,
58
+ field_errors=errors,
59
+ hint="按字段路径修正配置后重新运行 config validate",
60
+ )