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
norain/maintain.py ADDED
@@ -0,0 +1,313 @@
1
+ """自维持模块:维持代理正常运行,其他模块被杀死或异常时迅速拉起,修不好时启动阻断。
2
+
3
+ 两部分:
4
+
5
+ 1. Maintainer —— 内控制进程里的一个组件(线程),低开销地反复扫描:
6
+ - 监视各模块是否在线,掉线的模块向内控制申请拉起;
7
+ - 监控模块抛出错误码时:结束相应进程,调用修复模块(只用文件修复和内置配置修复),重启代理;
8
+ - 修复失败时启动阻断模块。
9
+ 2. 看门狗 —— 独立进程(`norain _watchdog`),与内控制进程互相拉起:
10
+ 内控制进程被杀,看门狗把它拉起;看门狗被杀,Maintainer 把它拉起。
11
+
12
+ 与其他模块的协同(避免互相打架):
13
+ - 所有拉起和结束都经内控制审批;启动测试期间内控制会拒绝本模块的拉起请求。
14
+ - 修复期间暂停监控,修复后由本模块主动验证;这样修复过程中的抖动不会被当成新故障。
15
+ - 任何保活方在拉起前都检查期望状态:用户 stop 之后(desired = stopped)不再拉起任何东西。
16
+ - 有操作锁(start/stop/restart/repair 正在执行)时看门狗不动作。
17
+ - 阻断生效后看门狗退出,不再拉起内控制进程。
18
+ - 用户用命令行停掉的单个模块不会被自动拉起(否则停不掉)。
19
+ - 看门狗在短时间内反复拉起仍然失败,或上次失败原因是配置无效 / 缺少 sing-box 时停止拉起。
20
+
21
+ 各错误码的处理:
22
+ 100 本地没有联网:不是代理的问题,不修复也不阻断,等网络恢复。
23
+ 301 直接进入阻断(最初目标)。
24
+ 600 重启代理;自适应协议时切换到另一个协议;仍不行 → 文件修复 + 内置配置修复 → 阻断。
25
+ 604/606 调整 DNS 的 IPv4/IPv6 策略并重启;仍不行 → 修复 → 阻断。
26
+ 400/401 清掉学到的名单并重新生成配置;仍不行 → 修复 → 阻断。
27
+ 140(代理进程无法维持) 修复 → 阻断。
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import collections
33
+ import os
34
+ import threading
35
+ import time
36
+ from typing import TYPE_CHECKING
37
+
38
+ import psutil
39
+
40
+ from norain_core import osutil
41
+ from norain_core.daemonctl import alive as pid_alive
42
+ from norain_core.daemonctl import runner_info
43
+ from norain_core.errors import BIZ_BINARY_MISSING, BIZ_CONFIG, EXIT_OK, NorainError
44
+ from norain_core.log import Logger, RotatingFile
45
+ from norain_core.state import RUNNING, get_desired, lock_holder, read_json, write_json
46
+
47
+ from . import block, repair
48
+ from .monitor import MEANING, OK
49
+ from .paths import Paths
50
+
51
+ if TYPE_CHECKING:
52
+ from .control import Controller
53
+
54
+ PROXY_DOWN = 140 # 代理进程无法维持(沿用服务端「sing-box 进程退出」的业务码)
55
+ WATCHED = ("routing", "proxy", "monitor")
56
+ PULL_WINDOW, PULL_LIMIT = 600, 5
57
+
58
+
59
+ class Maintainer:
60
+ name = "maintain"
61
+
62
+ def __init__(self, ctl: "Controller", log: Logger) -> None:
63
+ self.ctl, self.log = ctl, log
64
+ self._stop = threading.Event()
65
+ self._thread: threading.Thread | None = None
66
+ self._pending: tuple[int, str] | None = None
67
+ self._reported_100 = False
68
+ self.pulls = 0
69
+ self.last_result: dict | None = None
70
+
71
+ # 监控模块在错误码变化时调用(在监控线程里,只记下来,由本模块的线程处理)
72
+ def notify(self, code: int, reason: str) -> None:
73
+ self._pending = (code, reason)
74
+
75
+ def tick(self) -> None:
76
+ ctl = self.ctl
77
+ if ctl.phase != "running":
78
+ return # 启动测试、修复、停止、阻断期间不介入
79
+ if get_desired(ctl.paths.desired) != RUNNING:
80
+ return
81
+
82
+ # 1. 模块在线情况
83
+ for name in WATCHED:
84
+ mod = ctl.modules.get(name)
85
+ if mod is None or name in ctl.user_stopped or mod.alive():
86
+ continue
87
+ if name == "proxy" and ctl.proxy.failed:
88
+ self.escalate(PROXY_DOWN, "sing-box 连续重启失败,监督器已放弃")
89
+ return
90
+ ok, why = ctl.start_module(name, "maintain")
91
+ self.pulls += 1
92
+ self.log.warn("maintain.pulled", module=name, ok=ok, detail=why)
93
+
94
+ # 2. 互拉保活:监控通过之后才激活
95
+ if ctl.cfg.maintain.watchdog and "maintain" not in ctl.user_stopped:
96
+ if not ctl.keepalive and ctl.monitor_code() == OK:
97
+ ctl.activate_keepalive()
98
+ elif ctl.keepalive and not watchdog_alive(ctl.paths):
99
+ spawn_watchdog(ctl.paths)
100
+ self.pulls += 1
101
+ self.log.warn("maintain.pulled", module="watchdog")
102
+
103
+ # 3. 监控模块抛出的错误码
104
+ pending, self._pending = self._pending, None
105
+ code, reason = pending if pending else (ctl.monitor_code(), "")
106
+ if code == OK:
107
+ self._reported_100 = False
108
+ return
109
+ if code == 100:
110
+ if not self._reported_100:
111
+ self._reported_100 = True
112
+ self.log.warn("maintain.no_internet", note="本地网络未连接,等待恢复;不修复也不阻断")
113
+ return
114
+ self.escalate(code, reason or MEANING.get(code, ""))
115
+
116
+ # ---- 修复升级 ----
117
+
118
+ def _light_fix(self, code: int) -> list[str]:
119
+ """第一轮:不动文件的轻量处理。"""
120
+ ctl, done = self.ctl, []
121
+ if code == 600 and ctl.selector is not None:
122
+ new = ctl.switch_protocol("maintain", "当前协议链路失效")
123
+ if new:
124
+ done.append(f"切换协议为 {new}")
125
+ elif code == 606:
126
+ ctl.set_override(dns_strategy="ipv4_only")
127
+ done.append("DNS 改为只用 IPv4(IPv6 链路异常)")
128
+ elif code == 604:
129
+ ctl.set_override(dns_strategy="prefer_ipv6")
130
+ done.append("DNS 改为优先 IPv6(IPv4 链路异常)")
131
+ elif code in (400, 401):
132
+ ctl.clear_learned()
133
+ done.append("清除自动学到的名单")
134
+ return done
135
+
136
+ def escalate(self, code: int, reason: str) -> str:
137
+ """处理一个故障:修复 → 验证 → 修不好就阻断。返回 recovered / aborted / blocked / failed。"""
138
+ ctl, cfg = self.ctl, self.ctl.cfg
139
+ result = {"code": code, "reason": reason, "started_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
140
+ "attempts": [], "outcome": ""}
141
+ self.log.error("maintain.fault", code=code, meaning=MEANING.get(code, "代理进程无法维持"), reason=reason)
142
+ ctl.enter_repair(code)
143
+ outcome = "failed"
144
+ try:
145
+ attempts = 0 if code == 301 else cfg.maintain.repair_attempts # 301 直接阻断
146
+ for n in range(1, attempts + 1):
147
+ if self._stop.is_set() or get_desired(ctl.paths.desired) != RUNNING:
148
+ outcome = "aborted"
149
+ break
150
+ actions: list[str] = []
151
+ if n == 1 and code != PROXY_DOWN:
152
+ actions += self._light_fix(code)
153
+ else: # 自维持模块只用文件修复和内置配置修复
154
+ ctl.stop_module("proxy", "maintain")
155
+ for rep in (repair.repair_files(ctl.paths, self.log),
156
+ repair.repair_builtin(ctl.paths, self.log)):
157
+ actions += rep.actions + [f"未修好:{p}" for p in rep.problems]
158
+ ctl.clear_learned() # 内置配置修复清掉了磁盘上的名单,内存里的也要一起清
159
+ ctl.set_override(dns_strategy=None)
160
+ ok, why = ctl.restart_proxy("maintain", f"修复错误码 {code}(第 {n} 轮)")
161
+ actions.append("重启代理" + ("" if ok else f"失败:{why}"))
162
+ ready = ok and ctl.proxy.wait_ready(30)
163
+ seen = ctl.verify(cfg.monitor.recovery_threshold) if ready else PROXY_DOWN
164
+ result["attempts"].append({"round": n, "actions": actions, "code_after": seen})
165
+ self.log.warn("maintain.repair_round", round=n, actions=actions, code_after=seen)
166
+ if seen == OK:
167
+ outcome = "recovered"
168
+ break
169
+ if seen == 100: # 修复途中本地断网:不是代理的问题,不能据此阻断
170
+ outcome = "aborted"
171
+ break
172
+ code = seen if seen in MEANING or seen == PROXY_DOWN else code
173
+ if outcome == "failed":
174
+ if cfg.maintain.block_on_failure:
175
+ try:
176
+ block.engage(cfg, ctl.paths, code=code, reason=reason, log=self.log)
177
+ outcome = "blocked"
178
+ except NorainError as e:
179
+ # 阻断没有生效必须明确告诉用户:此时流量可能直连
180
+ self.log.error("maintain.block_failed", error=e.message, hint=e.hint)
181
+ osutil.popup("Norain:代理失效且阻断没有生效",
182
+ f"代理无法恢复(错误码 {code}),并且无法进入阻断模式:{e.message}\n"
183
+ "当前流量可能直连,请立即检查。")
184
+ ctl.request_shutdown(blocked=outcome == "blocked", code=code)
185
+ finally:
186
+ result["outcome"] = outcome
187
+ self.last_result = result
188
+ ctl.leave_repair(outcome)
189
+ self._pending = None
190
+ self.log.warn("maintain.fault_handled", code=code, outcome=outcome)
191
+ return outcome
192
+
193
+ # ---- 模块生命周期 ----
194
+
195
+ def _run(self) -> None:
196
+ interval = self.ctl.cfg.maintain.scan_interval_seconds
197
+ while not self._stop.wait(interval):
198
+ try:
199
+ self.tick()
200
+ except Exception as e: # noqa: BLE001 自维持自身不能因为一次扫描出错而退出
201
+ self.log.error("maintain.tick_failed", error=repr(e))
202
+
203
+ def start(self) -> None:
204
+ if self.alive():
205
+ return
206
+ self._stop.clear()
207
+ self._thread = threading.Thread(target=self._run, name="norain-maintain", daemon=True)
208
+ self._thread.start()
209
+
210
+ def stop(self) -> None:
211
+ self._stop.set()
212
+ if self._thread and self._thread is not threading.current_thread():
213
+ self._thread.join(5)
214
+
215
+ def alive(self) -> bool:
216
+ return bool(self._thread and self._thread.is_alive())
217
+
218
+ def status(self) -> dict:
219
+ return {"state": "running" if self.alive() else "stopped", "pulls": self.pulls,
220
+ "watchdog_alive": watchdog_alive(self.ctl.paths), "keepalive": self.ctl.keepalive,
221
+ "last_result": self.last_result}
222
+
223
+
224
+ # ---- 看门狗进程 ----------------------------------------------------------------
225
+
226
+ def _watchdog_pid(paths: Paths) -> int | None:
227
+ pid = (read_json(paths.watchdog_file) or {}).get("pid")
228
+ if not pid_alive(pid):
229
+ return None
230
+ try:
231
+ if "_watchdog" not in " ".join(psutil.Process(pid).cmdline()):
232
+ return None # PID 已被别的进程复用
233
+ except psutil.Error:
234
+ return None
235
+ return pid
236
+
237
+
238
+ def watchdog_alive(paths: Paths) -> bool:
239
+ return _watchdog_pid(paths) is not None
240
+
241
+
242
+ def spawn_watchdog(paths: Paths) -> None:
243
+ osutil.spawn_detached([osutil.python_exe(windowless=True), "-m", "norain", "_watchdog"],
244
+ log_file=paths.log_dir / "watchdog.out")
245
+
246
+
247
+ def kill_watchdog(paths: Paths) -> bool:
248
+ pid = _watchdog_pid(paths)
249
+ if pid is None:
250
+ paths.watchdog_file.unlink(missing_ok=True)
251
+ return False
252
+ try:
253
+ proc = psutil.Process(pid)
254
+ proc.terminate()
255
+ try:
256
+ proc.wait(5)
257
+ except psutil.TimeoutExpired:
258
+ proc.kill()
259
+ except psutil.Error:
260
+ pass
261
+ paths.watchdog_file.unlink(missing_ok=True)
262
+ return True
263
+
264
+
265
+ def watchdog_main(paths: Paths) -> int:
266
+ """看门狗主循环。内控制进程不在了就把它拉起;该停的时候自己退出。"""
267
+ from .model import load_config
268
+ other = _watchdog_pid(paths)
269
+ if other and other != os.getpid():
270
+ return EXIT_OK # 已经有一个看门狗
271
+ try:
272
+ cfg = load_config(paths.config)
273
+ paths = paths.with_log_dir(cfg.logging.directory)
274
+ interval = cfg.maintain.scan_interval_seconds
275
+ except NorainError:
276
+ interval = 5.0
277
+ log = Logger("watchdog", sink=RotatingFile(paths.log_file, max_bytes=20 << 20, keep=5), stderr=False)
278
+ write_json(paths.watchdog_file, {"pid": os.getpid(), "started_at": time.strftime("%Y-%m-%dT%H:%M:%S%z")})
279
+ pulls: collections.deque[float] = collections.deque()
280
+ log.info("watchdog.started", interval=interval)
281
+ try:
282
+ while True:
283
+ time.sleep(interval)
284
+ if (read_json(paths.watchdog_file) or {}).get("pid") != os.getpid():
285
+ return EXIT_OK # 被新的看门狗取代,或状态文件被清掉(卸载、停止)
286
+ if get_desired(paths.desired) != RUNNING:
287
+ log.info("watchdog.exit", reason="期望状态是 stopped")
288
+ return EXIT_OK
289
+ if block.is_active(paths):
290
+ log.info("watchdog.exit", reason="已进入阻断模式")
291
+ return EXIT_OK
292
+ if lock_holder(paths.lock) or runner_info(paths.runner):
293
+ continue
294
+ last = read_json(paths.last_error) or {}
295
+ if last.get("business_code") in (BIZ_CONFIG, BIZ_BINARY_MISSING):
296
+ log.error("watchdog.exit", reason="配置无效或缺少 sing-box,拉起也没用", last_error=last)
297
+ return EXIT_OK
298
+ now = time.monotonic()
299
+ while pulls and now - pulls[0] > PULL_WINDOW:
300
+ pulls.popleft()
301
+ if len(pulls) >= PULL_LIMIT:
302
+ log.error("watchdog.exit", reason=f"{PULL_WINDOW} 秒内已拉起 {PULL_LIMIT} 次仍然失败")
303
+ return EXIT_OK
304
+ pulls.append(now)
305
+ log.warn("watchdog.pull", target="controller")
306
+ osutil.spawn_detached([osutil.python_exe(windowless=True), "-m", "norain", "run"],
307
+ log_file=paths.log_dir / "daemon.out")
308
+ deadline = time.monotonic() + 30
309
+ while time.monotonic() < deadline and not runner_info(paths.runner):
310
+ time.sleep(0.5)
311
+ finally:
312
+ if (read_json(paths.watchdog_file) or {}).get("pid") == os.getpid():
313
+ paths.watchdog_file.unlink(missing_ok=True)