1panel-toolkit 0.3.0__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 (47) hide show
  1. 1panel_toolkit-0.3.0.dist-info/METADATA +407 -0
  2. 1panel_toolkit-0.3.0.dist-info/RECORD +47 -0
  3. 1panel_toolkit-0.3.0.dist-info/WHEEL +4 -0
  4. 1panel_toolkit-0.3.0.dist-info/entry_points.txt +2 -0
  5. 1panel_toolkit-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. p1toolkit/__init__.py +3 -0
  7. p1toolkit/checks/__init__.py +21 -0
  8. p1toolkit/checks/compose.py +188 -0
  9. p1toolkit/checks/forms.py +129 -0
  10. p1toolkit/checks/hygiene.py +73 -0
  11. p1toolkit/checks/i18n.py +140 -0
  12. p1toolkit/checks/lessons.py +111 -0
  13. p1toolkit/checks/structure.py +140 -0
  14. p1toolkit/checks/substance.py +55 -0
  15. p1toolkit/cli.py +890 -0
  16. p1toolkit/config.py +114 -0
  17. p1toolkit/dependencies.py +218 -0
  18. p1toolkit/deploy.py +302 -0
  19. p1toolkit/depth.py +414 -0
  20. p1toolkit/errors.py +18 -0
  21. p1toolkit/evidence.py +523 -0
  22. p1toolkit/fix.py +394 -0
  23. p1toolkit/gen.py +728 -0
  24. p1toolkit/lifecycle.py +143 -0
  25. p1toolkit/loader.py +110 -0
  26. p1toolkit/logo.py +174 -0
  27. p1toolkit/model.py +71 -0
  28. p1toolkit/net.py +81 -0
  29. p1toolkit/panel.py +154 -0
  30. p1toolkit/patterns/__init__.py +250 -0
  31. p1toolkit/patterns/catalog.py +271 -0
  32. p1toolkit/patterns/data/patterns.json +724 -0
  33. p1toolkit/patterns/extract.py +402 -0
  34. p1toolkit/remote.py +554 -0
  35. p1toolkit/report.py +96 -0
  36. p1toolkit/resolve/__init__.py +554 -0
  37. p1toolkit/resolve/analyze.py +329 -0
  38. p1toolkit/resolve/sources.py +306 -0
  39. p1toolkit/rules/__init__.py +99 -0
  40. p1toolkit/rules/data/decisions.yaml +132 -0
  41. p1toolkit/rules/data/dependencies.yaml +113 -0
  42. p1toolkit/rules/data/envkeys.yaml +19 -0
  43. p1toolkit/rules/data/form-design.yaml +59 -0
  44. p1toolkit/rules/data/i18n.yaml +354 -0
  45. p1toolkit/rules/data/lessons.yaml +84 -0
  46. p1toolkit/rules/data/store.yaml +171 -0
  47. p1toolkit/selftest.py +211 -0
p1toolkit/lifecycle.py ADDED
@@ -0,0 +1,143 @@
1
+ """Lifecycle scripts and first-run files (D09).
2
+
3
+ The most common "passes every check, crash-loops on start" failure is a
4
+ container that reads a config file out of a bind-mounted directory the package
5
+ shipped empty (lesson L001). Two spec features close that gap:
6
+
7
+ * ``config_files`` ships the template into the version directory, so the app
8
+ finds something to read and the user has something to edit.
9
+ * ``data_owner`` generates ``init.sh`` / ``upgrade.sh`` that create the mounted
10
+ directories and hand them to the user the container actually runs as
11
+ (``services[].user`` upstream, or ``data_owner`` when the image has no USER
12
+ but the app documents one).
13
+
14
+ Anything more app-specific is written verbatim: ``scripts: {init, upgrade,
15
+ uninstall}`` is the packager's text, not something the generator should guess.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from .errors import SpecError
25
+
26
+ SCRIPT_NAMES = ("init", "upgrade", "uninstall")
27
+ ENV_REF = re.compile(r"\$\{[^}]+\}")
28
+
29
+
30
+ def _normalise_script(name: str, text: str) -> str:
31
+ body = str(text).replace("\r\n", "\n").strip("\n")
32
+ if not body.startswith("#!"):
33
+ body = "#!/bin/bash\n" + body
34
+ return body + "\n"
35
+
36
+
37
+ def _host_mounts(spec: dict[str, Any]) -> list[str]:
38
+ hosts: list[str] = []
39
+ for service in spec.get("services") or []:
40
+ if not isinstance(service, dict):
41
+ continue
42
+ mounts = service.get("mounts")
43
+ if isinstance(mounts, list):
44
+ hosts.extend(
45
+ str(item.get("host"))
46
+ for item in mounts
47
+ if isinstance(item, dict) and item.get("host")
48
+ )
49
+ if service.get("mount_host"):
50
+ hosts.append(str(service["mount_host"]))
51
+ keep = []
52
+ for host in hosts:
53
+ if host.startswith("./") and host not in keep:
54
+ keep.append(host)
55
+ return keep
56
+
57
+
58
+ def owner_script(owner: str, hosts: list[str], purpose: str) -> str:
59
+ """``init.sh`` / ``upgrade.sh`` for a container that runs as a non-root user."""
60
+ listed = ", ".join(f'"{host}"' for host in hosts)
61
+ return _normalise_script(
62
+ "init",
63
+ f"""#!/bin/bash
64
+ # 由 1panel-toolkit 生成:容器以 {owner} 运行(见上游 Dockerfile/compose),
65
+ # 宿主机上的挂载目录必须属于它,否则容器写不进去({purpose})。
66
+ # 依据见包内 decision-audit.json 的 D07 条目。
67
+ set -euo pipefail
68
+
69
+ ROOT_DIR="$(cd "$(dirname "${{BASH_SOURCE[0]}}")/.." && pwd)"
70
+ DATA_DIRS=({listed})
71
+
72
+ for dir in "${{DATA_DIRS[@]}}"; do
73
+ target="${{ROOT_DIR}}/${{dir#./}}"
74
+ mkdir -p "${{target}}"
75
+ chown -R {owner} "${{target}}"
76
+ done
77
+
78
+ echo "data directories ready (owner {owner})"
79
+ """,
80
+ )
81
+
82
+
83
+ def build(
84
+ spec: dict[str, Any],
85
+ ) -> tuple[dict[str, str], list[tuple[str, str]], list[str], list[str]]:
86
+ """Return (scripts, extra files, warnings, notes)."""
87
+ warnings: list[str] = []
88
+ scripts: dict[str, str] = {}
89
+
90
+ declared = spec.get("scripts") or {}
91
+ if declared and not isinstance(declared, dict):
92
+ raise SpecError("spec.scripts 必须是对象,例如 {\"init\": \"...\"}")
93
+ for name, text in declared.items():
94
+ key = str(name)
95
+ if key not in SCRIPT_NAMES:
96
+ raise SpecError(f"spec.scripts.{key} 未知;可用的是 {list(SCRIPT_NAMES)}")
97
+ scripts[key] = _normalise_script(key, str(text))
98
+ # `init_script` predates `scripts`; keep the older specs working.
99
+ if spec.get("init_script") and "init" not in scripts:
100
+ scripts["init"] = _normalise_script("init", str(spec["init_script"]))
101
+
102
+ owner = str(spec.get("data_owner") or "").strip()
103
+ if owner:
104
+ hosts = _host_mounts(spec)
105
+ if not hosts:
106
+ warnings.append(
107
+ f"data_owner={owner} 但 spec 里没有相对挂载目录(./...),没有需要 chown 的目标"
108
+ )
109
+ else:
110
+ if "init" not in scripts:
111
+ scripts["init"] = owner_script(owner, hosts, "安装后、首次启动前执行")
112
+ if "upgrade" not in scripts:
113
+ scripts["upgrade"] = owner_script(owner, hosts, "升级后执行")
114
+ for host in hosts:
115
+ if ENV_REF.search(host):
116
+ warnings.append(
117
+ f"挂载路径 {host} 含变量,init.sh 只能按字面量创建目录;"
118
+ "请在脚本里按表单默认值展开"
119
+ )
120
+
121
+ files: list[tuple[str, str]] = []
122
+ for index, item in enumerate(spec.get("config_files") or []):
123
+ if not isinstance(item, dict) or not item.get("path"):
124
+ raise SpecError(f"config_files[{index}] 需要 path(相对版本目录,如 data/ov.conf)")
125
+ path = str(item["path"]).replace("\\", "/").lstrip("/")
126
+ if ".." in Path(path).parts:
127
+ raise SpecError(f"config_files[{index}].path 不能跳出版本目录:{path}")
128
+ content = str(item.get("content") or item.get("template") or "")
129
+ files.append((path, content.replace("\r\n", "\n").strip("\n") + "\n"))
130
+
131
+ notes: list[str] = []
132
+ if scripts.get("init"):
133
+ notes.append("自带 scripts/init.sh:安装前会执行,用来补目录/权限或校验配置文件")
134
+ if files:
135
+ notes.append(
136
+ "自带配置模板:"
137
+ + ", ".join(path for path, _ in files)
138
+ + "(README 的「首次启动」会提醒用户先编辑)"
139
+ )
140
+ return scripts, files, warnings, notes
141
+
142
+
143
+ __all__ = ["SCRIPT_NAMES", "build", "owner_script"]
p1toolkit/loader.py ADDED
@@ -0,0 +1,110 @@
1
+ """Read a 1Panel app package (or a spec) into the model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import yaml
9
+
10
+ from .model import Package, Version
11
+
12
+ TEXT_SUFFIXES = {".yml", ".yaml", ".sh", ".md", ".json", ".sample", ".conf", ".txt"}
13
+ SKIP_DIRS = {".git", "__pycache__", "node_modules", ".pytest_cache"}
14
+
15
+
16
+ class LoadError(Exception):
17
+ """Raised when a package cannot be read at all."""
18
+
19
+
20
+ def _read(path: Path) -> str:
21
+ return path.read_text(encoding="utf-8-sig", errors="replace")
22
+
23
+
24
+ def load_yaml(path: Path) -> dict[str, Any]:
25
+ try:
26
+ data = yaml.safe_load(_read(path))
27
+ except yaml.YAMLError as exc:
28
+ raise LoadError(f"{path}: invalid YAML: {exc}") from exc
29
+ if data is None:
30
+ return {}
31
+ if not isinstance(data, dict):
32
+ raise LoadError(f"{path}: expected a mapping at the top level")
33
+ return data
34
+
35
+
36
+ def iter_files(root: Path) -> dict[str, Path]:
37
+ """Map posix-style relative paths to absolute ones, skipping noise dirs."""
38
+ found: dict[str, Path] = {}
39
+ for path in sorted(root.rglob("*")):
40
+ if not path.is_file():
41
+ continue
42
+ if any(part in SKIP_DIRS for part in path.relative_to(root).parts):
43
+ continue
44
+ found[path.relative_to(root).as_posix()] = path
45
+ return found
46
+
47
+
48
+ def load_version(directory: Path) -> Version:
49
+ files = iter_files(directory)
50
+ data_path = directory / "data.yml"
51
+ compose_path = directory / "docker-compose.yml"
52
+ version = Version(
53
+ name=directory.name,
54
+ dir=directory,
55
+ data=load_yaml(data_path) if data_path.exists() else {},
56
+ compose_text=_read(compose_path) if compose_path.exists() else "",
57
+ files=files,
58
+ )
59
+ if version.compose_text:
60
+ try:
61
+ loaded = yaml.safe_load(version.compose_text) or {}
62
+ except yaml.YAMLError as exc:
63
+ raise LoadError(f"{compose_path}: invalid YAML: {exc}") from exc
64
+ version.compose = loaded if isinstance(loaded, dict) else {}
65
+ sample = directory / ".env.sample"
66
+ if sample.exists():
67
+ version.env_sample = _read(sample)
68
+ return version
69
+
70
+
71
+ def find_version_dirs(root: Path) -> list[Path]:
72
+ dirs = []
73
+ for child in sorted(root.iterdir()):
74
+ if not child.is_dir() or child.name in SKIP_DIRS:
75
+ continue
76
+ if (child / "docker-compose.yml").exists() or (child / "data.yml").exists():
77
+ dirs.append(child)
78
+ # `latest` first: it is the version the store shows by default.
79
+ dirs.sort(key=lambda p: (p.name != "latest", p.name))
80
+ return dirs
81
+
82
+
83
+ def load_package(root: Path | str) -> Package:
84
+ root = Path(root).resolve()
85
+ if not root.is_dir():
86
+ raise LoadError(f"not a directory: {root}")
87
+ data_path = root / "data.yml"
88
+ if not data_path.exists():
89
+ raise LoadError(f"{root}: no data.yml (not an app package root)")
90
+ package = Package(
91
+ root=root,
92
+ app=load_yaml(data_path),
93
+ app_text=_read(data_path),
94
+ files=iter_files(root),
95
+ )
96
+ package.versions = [load_version(d) for d in find_version_dirs(root)]
97
+ return package
98
+
99
+
100
+ def line_ending_issues(path: Path) -> str | None:
101
+ """Return a short description of a text-file hygiene problem, if any."""
102
+ if path.suffix.lower() not in TEXT_SUFFIXES and path.name != ".env.sample":
103
+ return None
104
+ raw = path.read_bytes()
105
+ if raw.startswith(b"\xef\xbb\xbf"):
106
+ return "UTF-8 BOM"
107
+ if b"\r\n" in raw:
108
+ return "CRLF line endings"
109
+ return None
110
+
p1toolkit/logo.py ADDED
@@ -0,0 +1,174 @@
1
+ """Minimal PNG handling, enough to bring a logo to the store's 180x180 canvas.
2
+
3
+ No Pillow dependency: the store logos are plain 8-bit RGB/RGBA PNGs, and the
4
+ operation is "scale down proportionally, then centre on a transparent canvas".
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import struct
10
+ import zlib
11
+ from dataclasses import dataclass
12
+
13
+
14
+ class LogoError(Exception):
15
+ pass
16
+
17
+
18
+ @dataclass
19
+ class Image:
20
+ width: int
21
+ height: int
22
+ channels: int # 3 = RGB, 4 = RGBA
23
+ pixels: bytearray # rows of width*channels bytes
24
+
25
+ def row(self, y: int) -> bytes:
26
+ start = y * self.width * self.channels
27
+ return bytes(self.pixels[start : start + self.width * self.channels])
28
+
29
+
30
+ def _chunks(raw: bytes):
31
+ offset = 8
32
+ while offset < len(raw):
33
+ length = struct.unpack(">I", raw[offset : offset + 4])[0]
34
+ tag = raw[offset + 4 : offset + 8]
35
+ data = raw[offset + 8 : offset + 8 + length]
36
+ yield tag, data
37
+ offset += 12 + length
38
+
39
+
40
+ def _paeth(a: int, b: int, c: int) -> int:
41
+ p = a + b - c
42
+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
43
+ if pa <= pb and pa <= pc:
44
+ return a
45
+ return b if pb <= pc else c
46
+
47
+
48
+ def decode_png(raw: bytes) -> Image:
49
+ if raw[:8] != b"\x89PNG\r\n\x1a\n":
50
+ raise LogoError("不是 PNG")
51
+ width = height = depth = colour = interlace = None
52
+ idat = bytearray()
53
+ palette = None
54
+ for tag, data in _chunks(raw):
55
+ if tag == b"IHDR":
56
+ width, height, depth, colour, _, _, interlace = struct.unpack(">IIBBBBB", data)
57
+ elif tag == b"IDAT":
58
+ idat += data
59
+ elif tag == b"PLTE":
60
+ palette = data
61
+ if depth != 8:
62
+ raise LogoError(f"只支持 8 位色深,实际 {depth}")
63
+ if interlace:
64
+ raise LogoError("不支持隔行扫描的 PNG")
65
+ if colour == 2:
66
+ channels = 3
67
+ elif colour == 6:
68
+ channels = 4
69
+ elif colour == 3 and palette:
70
+ channels = 3 # expand palette below
71
+ elif colour == 0:
72
+ channels = 1
73
+ else:
74
+ raise LogoError(f"不支持的色彩类型 {colour}")
75
+
76
+ data = zlib.decompress(bytes(idat))
77
+ stride = width * channels
78
+ out = bytearray(height * stride)
79
+ previous = bytearray(stride)
80
+ offset = 0
81
+ for y in range(height):
82
+ filter_type = data[offset]
83
+ offset += 1
84
+ line = bytearray(data[offset : offset + stride])
85
+ offset += stride
86
+ if filter_type == 1:
87
+ for i in range(channels, stride):
88
+ line[i] = (line[i] + line[i - channels]) & 0xFF
89
+ elif filter_type == 2:
90
+ for i in range(stride):
91
+ line[i] = (line[i] + previous[i]) & 0xFF
92
+ elif filter_type == 3:
93
+ for i in range(stride):
94
+ left = line[i - channels] if i >= channels else 0
95
+ line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF
96
+ elif filter_type == 4:
97
+ for i in range(stride):
98
+ left = line[i - channels] if i >= channels else 0
99
+ up_left = previous[i - channels] if i >= channels else 0
100
+ line[i] = (line[i] + _paeth(left, previous[i], up_left)) & 0xFF
101
+ elif filter_type != 0:
102
+ raise LogoError(f"未知的行过滤器 {filter_type}")
103
+ out[y * stride : (y + 1) * stride] = line
104
+ previous = line
105
+
106
+ if colour == 3 and palette:
107
+ rgb = bytearray(width * height * 3)
108
+ for index in range(width * height):
109
+ entry = out[index] * 3
110
+ rgb[index * 3 : index * 3 + 3] = palette[entry : entry + 3]
111
+ return Image(width, height, 3, rgb)
112
+ if colour == 0:
113
+ rgb = bytearray(width * height * 3)
114
+ for index in range(width * height):
115
+ grey = out[index]
116
+ rgb[index * 3 : index * 3 + 3] = bytes((grey, grey, grey))
117
+ return Image(width, height, 3, rgb)
118
+ return Image(width, height, channels, out)
119
+
120
+
121
+ def encode_png(image: Image) -> bytes:
122
+ def chunk(tag: bytes, data: bytes) -> bytes:
123
+ return (
124
+ struct.pack(">I", len(data))
125
+ + tag
126
+ + data
127
+ + struct.pack(">I", zlib.crc32(tag + data))
128
+ )
129
+
130
+ colour = 6 if image.channels == 4 else 2
131
+ raw = bytearray()
132
+ for y in range(image.height):
133
+ raw.append(0)
134
+ raw += image.row(y)
135
+ header = struct.pack(">IIBBBBB", image.width, image.height, 8, colour, 0, 0, 0)
136
+ return (
137
+ b"\x89PNG\r\n\x1a\n"
138
+ + chunk(b"IHDR", header)
139
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
140
+ + chunk(b"IEND", b"")
141
+ )
142
+
143
+
144
+ def _sample(image: Image, x: float, y: float) -> tuple[int, ...]:
145
+ sx = min(image.width - 1, max(0, int(x)))
146
+ sy = min(image.height - 1, max(0, int(y)))
147
+ start = (sy * image.width + sx) * image.channels
148
+ px = image.pixels[start : start + image.channels]
149
+ if image.channels == 3:
150
+ return (px[0], px[1], px[2], 255)
151
+ return (px[0], px[1], px[2], px[3])
152
+
153
+
154
+ def fit_square(raw: bytes, size: int = 180) -> bytes:
155
+ """Scale down proportionally and centre on a transparent canvas.
156
+
157
+ Never enlarges: a small logo keeps its pixels and gains transparency around
158
+ it, which is what the store's 180x180 slot expects.
159
+ """
160
+ image = decode_png(raw)
161
+ if image.width == size and image.height == size:
162
+ return raw
163
+ scale = min(size / image.width, size / image.height, 1.0)
164
+ target_w = max(1, int(round(image.width * scale)))
165
+ target_h = max(1, int(round(image.height * scale)))
166
+ canvas = bytearray(size * size * 4)
167
+ offset_x = (size - target_w) // 2
168
+ offset_y = (size - target_h) // 2
169
+ for y in range(target_h):
170
+ for x in range(target_w):
171
+ pixel = _sample(image, x / scale, y / scale)
172
+ index = ((y + offset_y) * size + (x + offset_x)) * 4
173
+ canvas[index : index + 4] = bytes(pixel)
174
+ return encode_png(Image(size, size, 4, canvas))
p1toolkit/model.py ADDED
@@ -0,0 +1,71 @@
1
+ """In-memory model of a 1Panel app package.
2
+
3
+ Two entry points feed this model: an existing package directory on disk
4
+ (``load_package``) and a canonical spec file (``load_spec``). Checks and
5
+ generators only ever talk to this model, never to raw YAML.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ @dataclass
16
+ class Version:
17
+ """One version directory of an app package (``latest``, ``1.2.3``, ...)."""
18
+
19
+ name: str
20
+ dir: Path
21
+ data: dict[str, Any] = field(default_factory=dict)
22
+ compose: dict[str, Any] = field(default_factory=dict)
23
+ compose_text: str = ""
24
+ env_sample: str = ""
25
+ files: dict[str, Path] = field(default_factory=dict)
26
+
27
+ @property
28
+ def additional(self) -> dict[str, Any]:
29
+ value = self.data.get("additionalProperties") or {}
30
+ return value if isinstance(value, dict) else {}
31
+
32
+ @property
33
+ def form_fields(self) -> list[dict[str, Any]]:
34
+ fields = self.additional.get("formFields") or []
35
+ return [f for f in fields if isinstance(f, dict)]
36
+
37
+ @property
38
+ def services(self) -> dict[str, Any]:
39
+ value = self.compose.get("services") or {}
40
+ return value if isinstance(value, dict) else {}
41
+
42
+
43
+ @dataclass
44
+ class Package:
45
+ """A full app package: root metadata plus one or more versions."""
46
+
47
+ root: Path
48
+ app: dict[str, Any] = field(default_factory=dict)
49
+ app_text: str = ""
50
+ versions: list[Version] = field(default_factory=list)
51
+ files: dict[str, Path] = field(default_factory=dict)
52
+
53
+ @property
54
+ def additional(self) -> dict[str, Any]:
55
+ value = self.app.get("additionalProperties") or {}
56
+ return value if isinstance(value, dict) else {}
57
+
58
+ @property
59
+ def key(self) -> str:
60
+ return str(self.additional.get("key") or self.root.name)
61
+
62
+ def version(self, name: str | None = None) -> Version | None:
63
+ if not self.versions:
64
+ return None
65
+ if name is None:
66
+ return self.versions[0]
67
+ for version in self.versions:
68
+ if version.name == name:
69
+ return version
70
+ return None
71
+
p1toolkit/net.py ADDED
@@ -0,0 +1,81 @@
1
+ """Port reachability classification.
2
+
3
+ A cloud security group turns a packaging question into a networking question:
4
+ a blocked port times out, while a reachable-but-unused port is refused
5
+ immediately. Knowing which is which keeps a firewall rule from being diagnosed
6
+ as a broken package (lesson L005).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import socket
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from dataclasses import dataclass
14
+
15
+ OPEN = "open"
16
+ CLOSED = "closed"
17
+ FILTERED = "filtered"
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class PortResult:
22
+ host: str
23
+ port: int
24
+ state: str
25
+ detail: str = ""
26
+
27
+ @property
28
+ def usable(self) -> bool:
29
+ """A port we can bind a new service to without touching the firewall."""
30
+ return self.state == CLOSED
31
+
32
+
33
+ def probe_port(host: str, port: int, timeout: float = 5.0) -> PortResult:
34
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
35
+ sock.settimeout(timeout)
36
+ try:
37
+ sock.connect((host, port))
38
+ except OSError as exc:
39
+ return classify(host, port, exc)
40
+ return PortResult(host, port, OPEN, "service accepted the connection")
41
+
42
+
43
+ def classify(host: str, port: int, exc: BaseException) -> PortResult:
44
+ """Map a connect failure onto the three states smoke tests care about.
45
+
46
+ A refusal proves the packet reached the host, so a firewall is not in the
47
+ way and the port is free to bind. Silence means something upstream dropped
48
+ it, which is a security-group question rather than a package question.
49
+ """
50
+ if isinstance(exc, ConnectionRefusedError):
51
+ return PortResult(host, port, CLOSED, "host reachable, nothing listening")
52
+ if isinstance(exc, socket.timeout):
53
+ return PortResult(host, port, FILTERED, "no reply; likely blocked upstream")
54
+ if isinstance(exc, OSError):
55
+ return PortResult(host, port, FILTERED, str(exc))
56
+ raise exc
57
+
58
+
59
+ def probe(host: str, ports: list[int], timeout: float = 5.0, workers: int = 16):
60
+ with ThreadPoolExecutor(max_workers=min(workers, max(len(ports), 1))) as pool:
61
+ results = list(pool.map(lambda p: probe_port(host, p, timeout), ports))
62
+ return sorted(results, key=lambda r: r.port)
63
+
64
+
65
+ def parse_ports(spec: str) -> list[int]:
66
+ """``8080``, ``10000-10010``, or a comma separated mix."""
67
+ ports: list[int] = []
68
+ for chunk in spec.split(","):
69
+ chunk = chunk.strip()
70
+ if not chunk:
71
+ continue
72
+ if "-" in chunk:
73
+ start, end = (int(part) for part in chunk.split("-", 1))
74
+ if start > end:
75
+ raise ValueError(f"invalid port range: {chunk}")
76
+ ports.extend(range(start, end + 1))
77
+ else:
78
+ ports.append(int(chunk))
79
+ if not ports:
80
+ raise ValueError("no ports given")
81
+ return ports