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/paths.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""服务端路径。启动时优先读环境变量,其次用默认路径(最初目标)。
|
|
2
|
+
|
|
3
|
+
| | Linux | Windows |
|
|
4
|
+
|---|---|---|
|
|
5
|
+
| 配置 | /etc/norain-server | %ProgramData%/norain-server |
|
|
6
|
+
| 状态 | /var/lib/norain-server | %ProgramData%/norain-server/state |
|
|
7
|
+
| 日志 | /var/log/norain-server | %ProgramData%/norain-server/log |
|
|
8
|
+
| sing-box | /usr/local/bin/sing-box | %ProgramFiles%/norain-server/sing-box.exe |
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Paths:
|
|
20
|
+
home: Path
|
|
21
|
+
config: Path
|
|
22
|
+
state: Path
|
|
23
|
+
log_dir: Path
|
|
24
|
+
log_dir_from_env: bool
|
|
25
|
+
singbox: str | None
|
|
26
|
+
platform: str = os.name
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def from_env(cls, env=None, platform: str | None = None) -> "Paths":
|
|
30
|
+
env = os.environ if env is None else env
|
|
31
|
+
platform = platform or os.name
|
|
32
|
+
if platform == "nt":
|
|
33
|
+
data = Path(env.get("ProgramData") or env.get("PROGRAMDATA") or "C:/ProgramData") / "norain-server"
|
|
34
|
+
d_home, d_state, d_log = data, data / "state", data / "log"
|
|
35
|
+
else:
|
|
36
|
+
d_home, d_state, d_log = (Path("/etc/norain-server"), Path("/var/lib/norain-server"),
|
|
37
|
+
Path("/var/log/norain-server"))
|
|
38
|
+
home = Path(env.get("NORAIN_SERVER_HOME") or d_home)
|
|
39
|
+
return cls(
|
|
40
|
+
home=home,
|
|
41
|
+
config=Path(env.get("NORAIN_SERVER_CONFIG") or home / "server.toml"),
|
|
42
|
+
state=Path(env.get("NORAIN_SERVER_STATE") or d_state),
|
|
43
|
+
log_dir=Path(env.get("NORAIN_SERVER_LOG") or d_log),
|
|
44
|
+
log_dir_from_env=bool(env.get("NORAIN_SERVER_LOG")),
|
|
45
|
+
singbox=env.get("NORAIN_SERVER_SINGBOX") or None,
|
|
46
|
+
platform=platform,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def with_log_dir(self, directory: str) -> "Paths":
|
|
50
|
+
"""server.toml 的 logging.directory 只在环境变量没有指定时生效。"""
|
|
51
|
+
if directory and not self.log_dir_from_env:
|
|
52
|
+
return Paths(self.home, self.config, self.state, Path(directory), False, self.singbox,
|
|
53
|
+
self.platform)
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def install_dir(self) -> Path:
|
|
58
|
+
"""sing-box 和启动器的安装目录。"""
|
|
59
|
+
if self.platform == "nt":
|
|
60
|
+
return Path(os.environ.get("ProgramFiles") or "C:/Program Files") / "norain-server"
|
|
61
|
+
return Path("/usr/local/bin")
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def default_singbox(self) -> Path:
|
|
65
|
+
return self.install_dir / ("sing-box.exe" if self.platform == "nt" else "sing-box")
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def reload_file(self) -> Path: return self.run_dir / "reload-request"
|
|
69
|
+
@property
|
|
70
|
+
def firewall_state(self) -> Path: return self.state / "firewall.json"
|
|
71
|
+
@property
|
|
72
|
+
def acme_dir(self) -> Path: return self.state / "acme"
|
|
73
|
+
@property
|
|
74
|
+
def install_record(self) -> Path: return self.state / "install.json"
|
|
75
|
+
@property
|
|
76
|
+
def cache_dir(self) -> Path: return self.state / "cache"
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def run_dir(self) -> Path: return self.state / "run"
|
|
80
|
+
@property
|
|
81
|
+
def current_json(self) -> Path: return self.run_dir / "sing-box.json"
|
|
82
|
+
@property
|
|
83
|
+
def meta_json(self) -> Path: return self.run_dir / "sing-box.json.meta.json"
|
|
84
|
+
@property
|
|
85
|
+
def backups(self) -> Path: return self.state / "backups"
|
|
86
|
+
@property
|
|
87
|
+
def desired(self) -> Path: return self.state / "desired-state.json"
|
|
88
|
+
@property
|
|
89
|
+
def lock(self) -> Path: return self.state / "op.lock"
|
|
90
|
+
@property
|
|
91
|
+
def runner(self) -> Path: return self.run_dir / "runner.json"
|
|
92
|
+
@property
|
|
93
|
+
def stop_file(self) -> Path: return self.run_dir / "stop-request"
|
|
94
|
+
@property
|
|
95
|
+
def last_error(self) -> Path: return self.state / "last-error.json"
|
|
96
|
+
@property
|
|
97
|
+
def tls_dir(self) -> Path: return self.state / "tls"
|
|
98
|
+
@property
|
|
99
|
+
def secrets_dir(self) -> Path: return self.home / "secrets"
|
|
100
|
+
@property
|
|
101
|
+
def log_file(self) -> Path: return self.log_dir / "norain-server.log"
|
norain_server/runner.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""守护模块:`norain-server run` 的前台守护进程。职责边界见 docs/decisions/0012 的修订。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from norain_core import singbox
|
|
8
|
+
from norain_core.errors import NorainError
|
|
9
|
+
from norain_core.migrate import migration_warnings
|
|
10
|
+
from norain_core.secrets import Secret
|
|
11
|
+
from norain_core.supervisor import Listener, Spec, Supervisor, check_ports_free, record_error
|
|
12
|
+
|
|
13
|
+
from . import cert as certmod
|
|
14
|
+
from . import generate
|
|
15
|
+
from .model import ServerConfig, load_config
|
|
16
|
+
from .paths import Paths
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Prepared:
|
|
21
|
+
cfg: ServerConfig
|
|
22
|
+
paths: Paths
|
|
23
|
+
secret: Secret
|
|
24
|
+
binary: singbox.BinaryInfo
|
|
25
|
+
cert: certmod.CertStatus
|
|
26
|
+
applied: generate.ApplyResult | None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def warnings(self) -> list[str]:
|
|
30
|
+
"""本次预检要展示给调用方的全部 warning:配置迁移 + 证书检查。"""
|
|
31
|
+
return migration_warnings(self.cfg) + self.cert.warnings
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def listeners(cfg: ServerConfig) -> list[Listener]:
|
|
35
|
+
out: list[Listener] = []
|
|
36
|
+
if cfg.protocols.hysteria2.enabled:
|
|
37
|
+
out.append((cfg.server.listen, "udp", cfg.protocols.hysteria2.port))
|
|
38
|
+
if cfg.protocols.trojan.enabled:
|
|
39
|
+
out.append((cfg.server.listen, "tcp", cfg.protocols.trojan.port))
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def locate_singbox(paths: Paths) -> singbox.BinaryInfo:
|
|
44
|
+
return singbox.inspect(singbox.locate(paths.singbox, defaults=(str(paths.default_singbox),)))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def need_tags(cfg: ServerConfig) -> set[str]:
|
|
48
|
+
tags = {"with_quic"} if cfg.protocols.hysteria2.enabled else set()
|
|
49
|
+
if cfg.tls.mode == "acme":
|
|
50
|
+
tags.add("with_acme")
|
|
51
|
+
return tags
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def tls_alpn01_ready(cfg: ServerConfig) -> bool:
|
|
55
|
+
"""TLS-ALPN-01 需要 443/tcp 上的 TLS 监听,目前只有 Trojan 能提供。"""
|
|
56
|
+
return cfg.protocols.trojan.enabled and cfg.protocols.trojan.port == 443
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def cert_status(cfg: ServerConfig, paths: Paths, *, tags: frozenset[str] | None = None,
|
|
60
|
+
service_running: bool = False,
|
|
61
|
+
tags_unknown: bool = False) -> certmod.CertStatus:
|
|
62
|
+
"""三种证书模式统一的检查入口。"""
|
|
63
|
+
if cfg.tls.mode == "acme":
|
|
64
|
+
return certmod.acme_status(cfg.server.domain, paths.acme_dir, tags=tags,
|
|
65
|
+
tags_unknown=tags_unknown,
|
|
66
|
+
service_running=service_running,
|
|
67
|
+
tls_alpn01=tls_alpn01_ready(cfg))
|
|
68
|
+
cert_path, key_path = generate.cert_paths(cfg, paths)
|
|
69
|
+
return certmod.check(cert_path, key_path, cfg.server.domain)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def firewall_ports(cfg: ServerConfig) -> list[tuple[str, int, str]]:
|
|
73
|
+
"""需要放行的 (协议, 端口, 用途)。只包含配置中启用的端口;acme 另需 80/tcp。"""
|
|
74
|
+
out: list[tuple[str, int, str]] = []
|
|
75
|
+
if cfg.protocols.hysteria2.enabled:
|
|
76
|
+
out.append(("udp", cfg.protocols.hysteria2.port, "hysteria2"))
|
|
77
|
+
if cfg.protocols.trojan.enabled:
|
|
78
|
+
out.append(("tcp", cfg.protocols.trojan.port, "trojan"))
|
|
79
|
+
if cfg.tls.mode == "acme" and ("tcp", 80) not in [(a, b) for a, b, _ in out]:
|
|
80
|
+
out.append(("tcp", 80, "acme"))
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def service_running(paths: Paths) -> bool:
|
|
85
|
+
from .service import pick_backend
|
|
86
|
+
try:
|
|
87
|
+
return pick_backend(paths).status().state == "running"
|
|
88
|
+
except Exception: # noqa: BLE001 查询失败时按未运行处理,只影响一条警告
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def prepare(paths: Paths, *, apply: bool = True) -> Prepared:
|
|
93
|
+
"""配置、秘密、证书、二进制的全部预检。apply=True 时生成并替换运行配置。"""
|
|
94
|
+
cfg = load_config(paths.config)
|
|
95
|
+
paths = paths.with_log_dir(cfg.logging.directory)
|
|
96
|
+
secret = generate.resolve_secret(cfg)
|
|
97
|
+
info = locate_singbox(paths)
|
|
98
|
+
singbox.require(info, need_tags=need_tags(cfg))
|
|
99
|
+
status = cert_status(cfg, paths, tags=info.tags, service_running=service_running(paths))
|
|
100
|
+
certmod.raise_for_mode(cfg.tls.mode, status)
|
|
101
|
+
if cfg.tls.mode == "acme":
|
|
102
|
+
paths.acme_dir.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
applied = generate.apply(cfg, secret, paths, info.path) if apply else None
|
|
104
|
+
return Prepared(cfg, paths, secret, info, status, applied)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def run_foreground(paths: Paths) -> int:
|
|
108
|
+
try:
|
|
109
|
+
prep = prepare(paths)
|
|
110
|
+
check_ports_free(listeners(prep.cfg))
|
|
111
|
+
except NorainError as e:
|
|
112
|
+
record_error(paths.last_error, e.business_code, e.message)
|
|
113
|
+
raise
|
|
114
|
+
cfg, p = prep.cfg, prep.paths
|
|
115
|
+
return Supervisor(Spec(
|
|
116
|
+
binary=prep.binary.path, config_json=p.current_json, config_version=prep.applied.version,
|
|
117
|
+
listeners=listeners(cfg), check_interval=cfg.service.check_interval_seconds,
|
|
118
|
+
restart_limit=cfg.service.restart_limit, backoff=cfg.service.restart_backoff_seconds,
|
|
119
|
+
log_file=p.log_file, log_max_bytes=cfg.logging.max_size_mb * 1024 * 1024,
|
|
120
|
+
log_keep=cfg.logging.retain_files, log_level=cfg.logging.level,
|
|
121
|
+
runner_file=p.runner, last_error_file=p.last_error, stop_file=p.stop_file,
|
|
122
|
+
reload_file=p.reload_file,
|
|
123
|
+
)).run()
|
norain_server/service.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""服务端的两种后端。
|
|
2
|
+
|
|
3
|
+
- SystemdBackend:已安装 norain-server.service 时使用(见 deploy/)。
|
|
4
|
+
- DetachedBackend:没有 systemd 单元时,直接在后台启动 `norain-server run`。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
from norain_core import osutil
|
|
15
|
+
from norain_core.daemonctl import DetachedBackend, ServiceStatus, runner_info
|
|
16
|
+
from norain_core.errors import EXIT_EXTERNAL, EXIT_PERMISSION, NorainError
|
|
17
|
+
from norain_core.redact import redact
|
|
18
|
+
|
|
19
|
+
from .paths import Paths
|
|
20
|
+
|
|
21
|
+
UNIT = "norain-server.service"
|
|
22
|
+
Run = Callable[[list[str]], subprocess.CompletedProcess]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _default_run(args: list[str]) -> subprocess.CompletedProcess:
|
|
26
|
+
return osutil.run(args) # 隐藏控制台窗口;命令不存在或超时时返回非零退出码而不是抛异常
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def detached(paths: Paths) -> DetachedBackend:
|
|
30
|
+
return DetachedBackend(module="norain_server", runner_file=paths.runner,
|
|
31
|
+
last_error_file=paths.last_error, stop_file=paths.stop_file,
|
|
32
|
+
log_dir=paths.log_dir)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SystemdBackend:
|
|
36
|
+
name = "systemd"
|
|
37
|
+
|
|
38
|
+
def __init__(self, paths: Paths, run: Run = _default_run) -> None:
|
|
39
|
+
self.paths, self._run = paths, run
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def available(run: Run = _default_run) -> bool:
|
|
43
|
+
if not shutil.which("systemctl"):
|
|
44
|
+
return False
|
|
45
|
+
try:
|
|
46
|
+
proc = run(["systemctl", "list-unit-files", UNIT, "--no-legend"])
|
|
47
|
+
except (OSError, subprocess.SubprocessError):
|
|
48
|
+
return False
|
|
49
|
+
return proc.returncode == 0 and UNIT in proc.stdout
|
|
50
|
+
|
|
51
|
+
def _ctl(self, *args: str) -> None:
|
|
52
|
+
proc = self._run(["systemctl", *args, UNIT])
|
|
53
|
+
if proc.returncode != 0:
|
|
54
|
+
msg = redact(proc.stderr.strip() or proc.stdout.strip())
|
|
55
|
+
denied = "ccess denied" in msg or "authentication" in msg.lower()
|
|
56
|
+
raise NorainError(f"systemctl {' '.join(args)} 失败:{msg}",
|
|
57
|
+
exit_code=EXIT_PERMISSION if denied else EXIT_EXTERNAL,
|
|
58
|
+
module="daemon", hint="用 root 或 sudo 运行" if denied else "")
|
|
59
|
+
|
|
60
|
+
def start(self, *, timeout: float = 20.0) -> None:
|
|
61
|
+
self._run(["systemctl", "reset-failed", UNIT])
|
|
62
|
+
self._ctl("start")
|
|
63
|
+
|
|
64
|
+
def stop(self, *, timeout: float = 20.0) -> None:
|
|
65
|
+
self._ctl("stop")
|
|
66
|
+
|
|
67
|
+
def status(self) -> ServiceStatus:
|
|
68
|
+
proc = self._run(["systemctl", "show", UNIT, "-p", "ActiveState,MainPID,NRestarts"])
|
|
69
|
+
props = dict(line.split("=", 1) for line in proc.stdout.splitlines() if "=" in line)
|
|
70
|
+
active = props.get("ActiveState", "inactive")
|
|
71
|
+
state = {"active": "running", "activating": "running", "failed": "failed"}.get(active, "stopped")
|
|
72
|
+
info = runner_info(self.paths.runner)
|
|
73
|
+
return ServiceStatus(self.name, state, int(props.get("MainPID") or 0) or None,
|
|
74
|
+
info.get("child_pid"), info.get("restarts", 0),
|
|
75
|
+
int(props.get("NRestarts") or 0))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def pick_backend(paths: Paths):
|
|
79
|
+
if os.environ.get("NORAIN_SERVER_BACKEND") == "detached" or os.name == "nt":
|
|
80
|
+
return detached(paths) # Windows:开机计划任务只负责拉起 `run --if-desired`
|
|
81
|
+
if SystemdBackend.available():
|
|
82
|
+
return SystemdBackend(paths)
|
|
83
|
+
return detached(paths)
|