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.
- 1panel_toolkit-0.3.0.dist-info/METADATA +407 -0
- 1panel_toolkit-0.3.0.dist-info/RECORD +47 -0
- 1panel_toolkit-0.3.0.dist-info/WHEEL +4 -0
- 1panel_toolkit-0.3.0.dist-info/entry_points.txt +2 -0
- 1panel_toolkit-0.3.0.dist-info/licenses/LICENSE +21 -0
- p1toolkit/__init__.py +3 -0
- p1toolkit/checks/__init__.py +21 -0
- p1toolkit/checks/compose.py +188 -0
- p1toolkit/checks/forms.py +129 -0
- p1toolkit/checks/hygiene.py +73 -0
- p1toolkit/checks/i18n.py +140 -0
- p1toolkit/checks/lessons.py +111 -0
- p1toolkit/checks/structure.py +140 -0
- p1toolkit/checks/substance.py +55 -0
- p1toolkit/cli.py +890 -0
- p1toolkit/config.py +114 -0
- p1toolkit/dependencies.py +218 -0
- p1toolkit/deploy.py +302 -0
- p1toolkit/depth.py +414 -0
- p1toolkit/errors.py +18 -0
- p1toolkit/evidence.py +523 -0
- p1toolkit/fix.py +394 -0
- p1toolkit/gen.py +728 -0
- p1toolkit/lifecycle.py +143 -0
- p1toolkit/loader.py +110 -0
- p1toolkit/logo.py +174 -0
- p1toolkit/model.py +71 -0
- p1toolkit/net.py +81 -0
- p1toolkit/panel.py +154 -0
- p1toolkit/patterns/__init__.py +250 -0
- p1toolkit/patterns/catalog.py +271 -0
- p1toolkit/patterns/data/patterns.json +724 -0
- p1toolkit/patterns/extract.py +402 -0
- p1toolkit/remote.py +554 -0
- p1toolkit/report.py +96 -0
- p1toolkit/resolve/__init__.py +554 -0
- p1toolkit/resolve/analyze.py +329 -0
- p1toolkit/resolve/sources.py +306 -0
- p1toolkit/rules/__init__.py +99 -0
- p1toolkit/rules/data/decisions.yaml +132 -0
- p1toolkit/rules/data/dependencies.yaml +113 -0
- p1toolkit/rules/data/envkeys.yaml +19 -0
- p1toolkit/rules/data/form-design.yaml +59 -0
- p1toolkit/rules/data/i18n.yaml +354 -0
- p1toolkit/rules/data/lessons.yaml +84 -0
- p1toolkit/rules/data/store.yaml +171 -0
- p1toolkit/selftest.py +211 -0
p1toolkit/remote.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
"""Run a package on a real 1Panel host over SSH and see whether it survives.
|
|
2
|
+
|
|
3
|
+
Static checks and generated YAML cannot tell you that the container starts,
|
|
4
|
+
that the port answers, or that the app finds its config file. This module
|
|
5
|
+
uploads one version directory to a scratch path on the host, brings it up with
|
|
6
|
+
the values the install form would have produced, probes it, collects the logs
|
|
7
|
+
and then cleans up.
|
|
8
|
+
|
|
9
|
+
Root SSH is used on purpose: 1Panel's local apps live at
|
|
10
|
+
``/opt/1panel/resource/apps/local/<key>`` and the smoke test needs Docker. The
|
|
11
|
+
scratch copy is deliberately separate from that directory so a test can never
|
|
12
|
+
overwrite a package the user already installed.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import io
|
|
18
|
+
import re
|
|
19
|
+
import shlex
|
|
20
|
+
import subprocess
|
|
21
|
+
import tarfile
|
|
22
|
+
import time
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from . import rules
|
|
27
|
+
from .loader import load_version
|
|
28
|
+
from .model import Version
|
|
29
|
+
|
|
30
|
+
SMOKE_ROOT = "/tmp/p1-smoke"
|
|
31
|
+
DEFAULT_TIMEOUT = 420
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RemoteError(Exception):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class SshTarget:
|
|
40
|
+
host: str
|
|
41
|
+
user: str = "root"
|
|
42
|
+
key_path: str = ""
|
|
43
|
+
port: int = 22
|
|
44
|
+
timeout: float = 60.0
|
|
45
|
+
|
|
46
|
+
def base_args(self) -> list[str]:
|
|
47
|
+
args = [
|
|
48
|
+
"ssh",
|
|
49
|
+
"-o",
|
|
50
|
+
"BatchMode=yes",
|
|
51
|
+
"-o",
|
|
52
|
+
"StrictHostKeyChecking=accept-new",
|
|
53
|
+
"-o",
|
|
54
|
+
f"ConnectTimeout={int(self.timeout)}",
|
|
55
|
+
"-p",
|
|
56
|
+
str(self.port),
|
|
57
|
+
]
|
|
58
|
+
if self.key_path:
|
|
59
|
+
args += ["-i", self.key_path]
|
|
60
|
+
args.append(f"{self.user}@{self.host}")
|
|
61
|
+
return args
|
|
62
|
+
|
|
63
|
+
def run(
|
|
64
|
+
self, command: str, input_bytes: bytes | None = None, timeout: float | None = None
|
|
65
|
+
) -> tuple[int, str, str]:
|
|
66
|
+
try:
|
|
67
|
+
completed = subprocess.run(
|
|
68
|
+
self.base_args() + [command],
|
|
69
|
+
input=input_bytes,
|
|
70
|
+
capture_output=True,
|
|
71
|
+
timeout=timeout or self.timeout,
|
|
72
|
+
)
|
|
73
|
+
except FileNotFoundError as exc:
|
|
74
|
+
raise RemoteError("ssh 客户端不可用,请确认 PATH 中有 ssh") from exc
|
|
75
|
+
except subprocess.TimeoutExpired as exc:
|
|
76
|
+
raise RemoteError(f"ssh 命令超时({timeout or self.timeout}s): {command}") from exc
|
|
77
|
+
out = completed.stdout.decode("utf-8", errors="replace")
|
|
78
|
+
err = completed.stderr.decode("utf-8", errors="replace")
|
|
79
|
+
return completed.returncode, out, err
|
|
80
|
+
|
|
81
|
+
def must(self, command: str, timeout: float | None = None) -> str:
|
|
82
|
+
code, out, err = self.run(command, timeout=timeout)
|
|
83
|
+
if code != 0:
|
|
84
|
+
raise RemoteError(f"remote command failed ({code}): {command}\n{err.strip()[:400]}")
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# --------------------------------------------------------------------------
|
|
89
|
+
# environment
|
|
90
|
+
# --------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class HostFacts:
|
|
95
|
+
hostname: str = ""
|
|
96
|
+
os_release: str = ""
|
|
97
|
+
docker: str = ""
|
|
98
|
+
compose: str = ""
|
|
99
|
+
mem_available_mb: int = 0
|
|
100
|
+
disk_free_gb: float = 0.0
|
|
101
|
+
cpus: int = 0
|
|
102
|
+
used_ports: list[int] = field(default_factory=list)
|
|
103
|
+
local_apps: list[str] = field(default_factory=list)
|
|
104
|
+
|
|
105
|
+
def free(self, candidates: list[int]) -> list[int]:
|
|
106
|
+
return [port for port in candidates if port not in self.used_ports]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _first_float(text: str) -> float:
|
|
110
|
+
match = re.search(r"[\d.]+", text)
|
|
111
|
+
return float(match.group()) if match else 0.0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# One round trip, one line per fact. Keep the separators stable: the parser
|
|
115
|
+
# below indexes into the output.
|
|
116
|
+
# Every fact carries its own label so a command that prints nothing cannot
|
|
117
|
+
# shift the following lines.
|
|
118
|
+
HOST_SCRIPT = "\n".join(
|
|
119
|
+
[
|
|
120
|
+
'echo "hostname:$(hostname)"',
|
|
121
|
+
"echo \"os:$(grep PRETTY_NAME /etc/os-release | cut -d= -f2-)\"",
|
|
122
|
+
'echo "docker:$(docker --version 2>/dev/null)"',
|
|
123
|
+
'echo "compose:$(docker compose version 2>/dev/null | head -1)"',
|
|
124
|
+
"echo \"mem:$(free -m | awk '/Mem:/{print $7}')\"",
|
|
125
|
+
"echo \"disk:$(df -BG / | awk 'NR==2{print $4}')\"",
|
|
126
|
+
'echo "cpus:$(nproc)"',
|
|
127
|
+
# column 4 is the local address:port; without it sed strips to the peer column
|
|
128
|
+
"echo \"ports:$(ss -lnt 2>/dev/null | awk 'NR>1{print $4}' | sed 's/.*://' "
|
|
129
|
+
"| sort -n -u | paste -sd,)\"",
|
|
130
|
+
'echo "apps:$(ls /opt/1panel/resource/apps/local 2>/dev/null | paste -sd,)"',
|
|
131
|
+
]
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def check_host(target: SshTarget) -> HostFacts:
|
|
136
|
+
out = target.must(HOST_SCRIPT)
|
|
137
|
+
fields: dict[str, str] = {}
|
|
138
|
+
for line in out.splitlines():
|
|
139
|
+
key, _, value = line.partition(":")
|
|
140
|
+
key = key.strip().lower()
|
|
141
|
+
if key:
|
|
142
|
+
fields[key] = value.strip().strip('"')
|
|
143
|
+
ports = [int(p) for p in fields.get("ports", "").split(",") if p.strip().isdigit()]
|
|
144
|
+
apps = [a for a in fields.get("apps", "").split(",") if a.strip()]
|
|
145
|
+
return HostFacts(
|
|
146
|
+
hostname=fields.get("hostname", ""),
|
|
147
|
+
os_release=fields.get("os", ""),
|
|
148
|
+
docker=fields.get("docker", ""),
|
|
149
|
+
compose=fields.get("compose", ""),
|
|
150
|
+
mem_available_mb=int(_first_float(fields.get("mem", ""))),
|
|
151
|
+
disk_free_gb=_first_float(fields.get("disk", "")),
|
|
152
|
+
cpus=int(_first_float(fields.get("cpus", ""))),
|
|
153
|
+
used_ports=sorted(set(ports)),
|
|
154
|
+
local_apps=sorted(set(apps)),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# --------------------------------------------------------------------------
|
|
159
|
+
# env rendering
|
|
160
|
+
# --------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def render_env(version: Version, overrides: dict[str, str], container_name: str) -> str:
|
|
164
|
+
"""Recreate the .env that 1Panel would write from the install form."""
|
|
165
|
+
values: dict[str, str] = {}
|
|
166
|
+
for field in version.form_fields:
|
|
167
|
+
key = str(field.get("envKey") or "")
|
|
168
|
+
if not key:
|
|
169
|
+
continue
|
|
170
|
+
default = field.get("default")
|
|
171
|
+
values[key] = "" if default is None else str(default)
|
|
172
|
+
values["CONTAINER_NAME"] = container_name
|
|
173
|
+
values.update(overrides)
|
|
174
|
+
order = [str(f.get("envKey")) for f in version.form_fields if f.get("envKey")]
|
|
175
|
+
lines = ["# generated by p1 remote smoke — not the panel's own .env"]
|
|
176
|
+
for key in order + [k for k in values if k not in order]:
|
|
177
|
+
lines.append(f"{key}={values[key]}")
|
|
178
|
+
return "\n".join(lines) + "\n"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def port_fields(version: Version) -> list[str]:
|
|
182
|
+
return [
|
|
183
|
+
str(field.get("envKey"))
|
|
184
|
+
for field in version.form_fields
|
|
185
|
+
if str(field.get("envKey") or "").startswith("PANEL_APP_PORT_")
|
|
186
|
+
]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# --------------------------------------------------------------------------
|
|
190
|
+
# smoke test
|
|
191
|
+
# --------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass
|
|
195
|
+
class SmokeResult:
|
|
196
|
+
ok: bool
|
|
197
|
+
stage: str
|
|
198
|
+
detail: str = ""
|
|
199
|
+
logs: str = ""
|
|
200
|
+
lessons: list[dict] = field(default_factory=list)
|
|
201
|
+
container_states: list[str] = field(default_factory=list)
|
|
202
|
+
published_ports: list[str] = field(default_factory=list)
|
|
203
|
+
probe: str = ""
|
|
204
|
+
remote_dir: str = ""
|
|
205
|
+
kept: bool = False
|
|
206
|
+
unverified: list[str] = field(default_factory=list)
|
|
207
|
+
health: list[str] = field(default_factory=list)
|
|
208
|
+
outcome: str = "pass" # pass | needs-input | fail
|
|
209
|
+
needs_input: list[str] = field(default_factory=list)
|
|
210
|
+
|
|
211
|
+
def render(self) -> str:
|
|
212
|
+
label = {"pass": "PASS", "needs-input": "PENDING", "fail": "FAIL"}.get(
|
|
213
|
+
self.outcome, "FAIL"
|
|
214
|
+
)
|
|
215
|
+
lines = [f"{label} {self.stage}"]
|
|
216
|
+
if self.detail:
|
|
217
|
+
lines.append(f" {self.detail}")
|
|
218
|
+
if self.container_states:
|
|
219
|
+
lines.append(" 容器: " + "; ".join(self.container_states))
|
|
220
|
+
if self.published_ports:
|
|
221
|
+
lines.append(" 端口: " + ", ".join(self.published_ports))
|
|
222
|
+
if self.probe:
|
|
223
|
+
lines.append(f" 探针: {self.probe}")
|
|
224
|
+
if self.health:
|
|
225
|
+
lines.append(" 健康: " + ", ".join(self.health))
|
|
226
|
+
if self.remote_dir:
|
|
227
|
+
lines.append(f" 远端目录: {self.remote_dir}{'(保留)' if self.kept else '(已清理)'}")
|
|
228
|
+
for item in self.unverified:
|
|
229
|
+
lines.append(f" 未验证: {item}")
|
|
230
|
+
for item in self.needs_input:
|
|
231
|
+
lines.append(f" 待填: {item}")
|
|
232
|
+
for lesson in self.lessons:
|
|
233
|
+
lines.append(
|
|
234
|
+
f" 经验 {lesson.get('id')}: {lesson.get('title')} → {lesson.get('fix')}"
|
|
235
|
+
)
|
|
236
|
+
if not self.ok and self.logs:
|
|
237
|
+
lines.append(" --- 日志尾部 ---")
|
|
238
|
+
for line in self.logs.strip().splitlines()[-25:]:
|
|
239
|
+
lines.append(f" | {line}")
|
|
240
|
+
return "\n".join(lines)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
LOG_SIGNATURES = (
|
|
244
|
+
("FileNotFoundError", "L001"),
|
|
245
|
+
("No such file or directory", "L001"),
|
|
246
|
+
("configuration requires", "L001"),
|
|
247
|
+
("config file", "L001"),
|
|
248
|
+
("permission denied", "L004"),
|
|
249
|
+
("Permission denied", "L004"),
|
|
250
|
+
("connection refused", "L002"),
|
|
251
|
+
("Connection refused", "L002"),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def match_lessons(logs: str) -> list[dict]:
|
|
256
|
+
hits: list[dict] = []
|
|
257
|
+
for needle, lesson_id in LOG_SIGNATURES:
|
|
258
|
+
if needle in logs and not any(item.get("id") == lesson_id for item in hits):
|
|
259
|
+
for lesson in rules.lessons():
|
|
260
|
+
if lesson.get("id") == lesson_id:
|
|
261
|
+
hits.append(lesson)
|
|
262
|
+
break
|
|
263
|
+
return hits
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# Missing user-supplied credentials are not a packaging defect: the install form
|
|
267
|
+
# deliberately ships no default for a secret. Telling the two apart stops a
|
|
268
|
+
# smoke run from sending someone hunting for a bug that is not there.
|
|
269
|
+
NEEDS_INPUT_SIGNATURES = (
|
|
270
|
+
"requires 'api_key' to be set",
|
|
271
|
+
"'api_key' to be set",
|
|
272
|
+
"API key is required",
|
|
273
|
+
"Credential",
|
|
274
|
+
"credential",
|
|
275
|
+
"Please set",
|
|
276
|
+
"must be set",
|
|
277
|
+
"secret is required",
|
|
278
|
+
"no API key",
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def needs_user_input(logs: str) -> list[str]:
|
|
283
|
+
found: list[str] = []
|
|
284
|
+
for needle in NEEDS_INPUT_SIGNATURES:
|
|
285
|
+
for line in logs.splitlines():
|
|
286
|
+
if needle in line:
|
|
287
|
+
text = line.strip()
|
|
288
|
+
if text and text not in found:
|
|
289
|
+
found.append(text[:160])
|
|
290
|
+
break
|
|
291
|
+
return found[:4]
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _tarball(directory: Path) -> bytes:
|
|
295
|
+
buffer = io.BytesIO()
|
|
296
|
+
with tarfile.open(fileobj=buffer, mode="w:gz") as archive:
|
|
297
|
+
for path in sorted(directory.rglob("*")):
|
|
298
|
+
if any(part in {".git", "__pycache__"} for part in path.parts):
|
|
299
|
+
continue
|
|
300
|
+
archive.add(path, arcname=path.relative_to(directory).as_posix())
|
|
301
|
+
return buffer.getvalue()
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def smoke(
|
|
305
|
+
target: SshTarget,
|
|
306
|
+
package_root: Path,
|
|
307
|
+
version_name: str | None = None,
|
|
308
|
+
ports: list[int] | None = None,
|
|
309
|
+
overrides: dict[str, str] | None = None,
|
|
310
|
+
timeout: int = DEFAULT_TIMEOUT,
|
|
311
|
+
ready_timeout: int = 90,
|
|
312
|
+
keep: bool = False,
|
|
313
|
+
prune_image: bool = False,
|
|
314
|
+
key: str | None = None,
|
|
315
|
+
) -> SmokeResult:
|
|
316
|
+
"""Upload one version, bring it up, probe it, tear it down."""
|
|
317
|
+
version = load_version(
|
|
318
|
+
package_root / version_name if version_name else package_root / "latest"
|
|
319
|
+
)
|
|
320
|
+
if not version.dir.exists():
|
|
321
|
+
candidates = sorted(p.name for p in package_root.iterdir() if p.is_dir())
|
|
322
|
+
raise RemoteError(f"找不到版本目录 {version_name or 'latest'};可选:{candidates}")
|
|
323
|
+
if not version.compose_text:
|
|
324
|
+
raise RemoteError(f"{version.dir} 没有 docker-compose.yml")
|
|
325
|
+
|
|
326
|
+
app_key = key or package_root.name
|
|
327
|
+
container_name = f"{app_key}-smoke"
|
|
328
|
+
overrides = dict(overrides or {})
|
|
329
|
+
fields = port_fields(version)
|
|
330
|
+
for index, value in enumerate(ports or []):
|
|
331
|
+
if index < len(fields):
|
|
332
|
+
overrides[fields[index]] = str(value)
|
|
333
|
+
env_text = render_env(version, overrides, container_name)
|
|
334
|
+
unverified = _unverifiable(version, overrides)
|
|
335
|
+
|
|
336
|
+
remote_dir = f"{SMOKE_ROOT}/{app_key}"
|
|
337
|
+
stage = "prepare"
|
|
338
|
+
try:
|
|
339
|
+
# A previous failed run may have kept its container: tear that down first
|
|
340
|
+
# so this run's logs and port state are its own.
|
|
341
|
+
target.must(
|
|
342
|
+
f"cd {shlex.quote(remote_dir)} 2>/dev/null && "
|
|
343
|
+
"docker compose down -v --remove-orphans >/dev/null 2>&1; "
|
|
344
|
+
f"docker ps -aq --filter name={shlex.quote(container_name)} "
|
|
345
|
+
"| xargs -r docker rm -f >/dev/null 2>&1; "
|
|
346
|
+
f"rm -rf {shlex.quote(remote_dir)} && mkdir -p {shlex.quote(remote_dir)}"
|
|
347
|
+
)
|
|
348
|
+
# Upload the compose file plus everything the package ships next to it,
|
|
349
|
+
# and the .env the install form would have produced.
|
|
350
|
+
payload = _tarball(Path(version.dir))
|
|
351
|
+
code, _, err = target.run(
|
|
352
|
+
f"tar -xzf - -C {shlex.quote(remote_dir)}", input_bytes=payload, timeout=timeout
|
|
353
|
+
)
|
|
354
|
+
if code != 0:
|
|
355
|
+
raise RemoteError(f"上传失败: {err.strip()[:300]}")
|
|
356
|
+
code, out, err = target.run(
|
|
357
|
+
f"cat > {shlex.quote(remote_dir + '/.env')}",
|
|
358
|
+
input_bytes=env_text.encode("utf-8"),
|
|
359
|
+
)
|
|
360
|
+
if code != 0:
|
|
361
|
+
raise RemoteError(f"写入 .env 失败: {err.strip()[:300]}")
|
|
362
|
+
|
|
363
|
+
stage = "pull & up"
|
|
364
|
+
# `A && B || C && D` groups as `((A && B) || C) && D`, so the fallback
|
|
365
|
+
# would run even after a successful `--wait`, and a failure in the
|
|
366
|
+
# fallback would report the successful path as broken.
|
|
367
|
+
compose = f"cd {shlex.quote(remote_dir)} && docker compose"
|
|
368
|
+
code, out, err = target.run(
|
|
369
|
+
f"({compose} up -d --wait 2>&1) || ({compose} up -d 2>&1)",
|
|
370
|
+
timeout=timeout,
|
|
371
|
+
)
|
|
372
|
+
up_output = (out or "") + (err or "")
|
|
373
|
+
if code != 0:
|
|
374
|
+
logs = _logs(target, remote_dir)
|
|
375
|
+
combined = logs + up_output
|
|
376
|
+
missing = needs_user_input(combined)
|
|
377
|
+
return SmokeResult(
|
|
378
|
+
ok=False,
|
|
379
|
+
stage="up",
|
|
380
|
+
detail=up_output.strip().splitlines()[-1] if up_output.strip() else "",
|
|
381
|
+
logs=logs,
|
|
382
|
+
lessons=match_lessons(combined),
|
|
383
|
+
remote_dir=remote_dir,
|
|
384
|
+
kept=True,
|
|
385
|
+
outcome="needs-input" if missing else "fail",
|
|
386
|
+
needs_input=missing,
|
|
387
|
+
unverified=unverified,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
stage = "probe"
|
|
391
|
+
states, published, probe, probe_ok, health = _wait_ready(
|
|
392
|
+
target, remote_dir, ready_timeout
|
|
393
|
+
)
|
|
394
|
+
logs = _logs(target, remote_dir)
|
|
395
|
+
lessons = match_lessons(logs)
|
|
396
|
+
running = bool(states) and all(
|
|
397
|
+
"running" in state and "unhealthy" not in state for state in states
|
|
398
|
+
)
|
|
399
|
+
ok = running and probe_ok
|
|
400
|
+
missing = needs_user_input(logs)
|
|
401
|
+
result = SmokeResult(
|
|
402
|
+
ok=ok,
|
|
403
|
+
stage=stage,
|
|
404
|
+
detail="" if ok else "容器或端口未达到预期",
|
|
405
|
+
logs=logs,
|
|
406
|
+
lessons=lessons,
|
|
407
|
+
container_states=states,
|
|
408
|
+
published_ports=published,
|
|
409
|
+
probe=probe,
|
|
410
|
+
remote_dir=remote_dir,
|
|
411
|
+
kept=keep or not ok,
|
|
412
|
+
unverified=unverified,
|
|
413
|
+
health=health,
|
|
414
|
+
outcome="pass" if ok else ("needs-input" if missing else "fail"),
|
|
415
|
+
needs_input=[] if ok else missing,
|
|
416
|
+
)
|
|
417
|
+
except RemoteError as exc:
|
|
418
|
+
return SmokeResult(ok=False, stage=stage, detail=str(exc), remote_dir=remote_dir)
|
|
419
|
+
|
|
420
|
+
if not result.kept:
|
|
421
|
+
_teardown(target, remote_dir, prune_image=prune_image)
|
|
422
|
+
return result
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _unverifiable(version: Version, overrides: dict[str, str]) -> list[str]:
|
|
426
|
+
"""Panel-managed dependencies that a standalone run cannot satisfy.
|
|
427
|
+
|
|
428
|
+
A package that selects a database through the install form gets its host
|
|
429
|
+
from the panel, not from a form default. Running it outside 1Panel therefore
|
|
430
|
+
proves the container starts, but says nothing about the dependency.
|
|
431
|
+
"""
|
|
432
|
+
text = version.compose_text
|
|
433
|
+
notes: list[str] = []
|
|
434
|
+
for env_key, label in (
|
|
435
|
+
("PANEL_DB_HOST", "面板托管的数据库"),
|
|
436
|
+
("REDIS_HOST", "面板托管的 Redis"),
|
|
437
|
+
("PANEL_REDIS_ROOT_PASSWORD", "面板 Redis 密码"),
|
|
438
|
+
):
|
|
439
|
+
if f"${{{env_key}}}" in text and not overrides.get(env_key):
|
|
440
|
+
notes.append(f"{label}({env_key})在独立冒烟里为空,连接性未验证")
|
|
441
|
+
return notes
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _states(target: SshTarget, remote_dir: str) -> tuple[list[str], list[str]]:
|
|
445
|
+
out = target.must(
|
|
446
|
+
f"cd {shlex.quote(remote_dir)} && docker compose ps --format "
|
|
447
|
+
"'{{.Name}} {{.State}} {{.Status}} | {{.Ports}}' 2>/dev/null || true"
|
|
448
|
+
)
|
|
449
|
+
states: list[str] = []
|
|
450
|
+
ports: list[str] = []
|
|
451
|
+
for line in out.splitlines():
|
|
452
|
+
line = line.strip()
|
|
453
|
+
if not line:
|
|
454
|
+
continue
|
|
455
|
+
states.append(line.split("|")[0].strip())
|
|
456
|
+
for mapping in re.findall(r"0\.0\.0\.0:(\d+)->(\d+)", line):
|
|
457
|
+
ports.append(f"{mapping[0]}->{mapping[1]}")
|
|
458
|
+
return states, ports
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _wait_ready(
|
|
462
|
+
target: SshTarget, remote_dir: str, ready_timeout: int
|
|
463
|
+
) -> tuple[list[str], list[str], str, bool, list[str]]:
|
|
464
|
+
"""Poll until the port answers, the container dies, or time runs out.
|
|
465
|
+
|
|
466
|
+
A bound port is not readiness: an app can listen for seconds before it
|
|
467
|
+
serves anything. So an HTTP answer is the strong signal, and a bare TCP
|
|
468
|
+
listen only counts when the image's own healthcheck agrees.
|
|
469
|
+
"""
|
|
470
|
+
deadline = time.time() + ready_timeout
|
|
471
|
+
states: list[str] = []
|
|
472
|
+
published: list[str] = []
|
|
473
|
+
health: list[str] = []
|
|
474
|
+
probe = "尚未探测"
|
|
475
|
+
probe_ok = False
|
|
476
|
+
while True:
|
|
477
|
+
states, published = _states(target, remote_dir)
|
|
478
|
+
health = _health(target, remote_dir)
|
|
479
|
+
probe, probe_ok, kind = _probe(target, published)
|
|
480
|
+
healthy = bool(health) and all(item in {"healthy", "none"} for item in health)
|
|
481
|
+
if probe_ok and kind == "http":
|
|
482
|
+
break
|
|
483
|
+
if probe_ok and kind == "tcp" and healthy and health:
|
|
484
|
+
break
|
|
485
|
+
if states and all(
|
|
486
|
+
"exited" in state or "unhealthy" in state or "dead" in state
|
|
487
|
+
for state in states
|
|
488
|
+
):
|
|
489
|
+
break
|
|
490
|
+
if time.time() >= deadline:
|
|
491
|
+
break
|
|
492
|
+
time.sleep(5)
|
|
493
|
+
# Accept the weaker TCP evidence only when nothing contradicts it.
|
|
494
|
+
final_ok = probe_ok and (
|
|
495
|
+
"http" in probe or (bool(health) and all(item != "unhealthy" for item in health))
|
|
496
|
+
)
|
|
497
|
+
return states, published, probe, final_ok, health
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _health(target: SshTarget, remote_dir: str) -> list[str]:
|
|
501
|
+
out = target.must(
|
|
502
|
+
f"cd {shlex.quote(remote_dir)} && "
|
|
503
|
+
"ids=$(docker compose ps -q 2>/dev/null); "
|
|
504
|
+
"[ -z \"$ids\" ] && exit 0; "
|
|
505
|
+
"docker inspect --format "
|
|
506
|
+
"'{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' $ids 2>/dev/null || true"
|
|
507
|
+
)
|
|
508
|
+
return [line.strip() for line in out.splitlines() if line.strip()]
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _first_http_code(raw: str) -> int | None:
|
|
512
|
+
"""curl prints exactly one three digit code; be defensive about wrappers."""
|
|
513
|
+
for candidate in reversed(re.findall(r"\b(\d{3})\b", raw)):
|
|
514
|
+
code = int(candidate)
|
|
515
|
+
if 100 <= code <= 599:
|
|
516
|
+
return code
|
|
517
|
+
return None
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _probe(target: SshTarget, published: list[str]) -> tuple[str, bool, str]:
|
|
521
|
+
if not published:
|
|
522
|
+
return "没有发布端口,跳过连通性探测", True, "none"
|
|
523
|
+
host_port = published[0].split("->")[0]
|
|
524
|
+
raw = target.must(
|
|
525
|
+
f"curl -s -o /dev/null -m 12 -w '%{{http_code}} rc=%{{exitcode}}' "
|
|
526
|
+
f"http://127.0.0.1:{host_port}/ 2>/dev/null || echo 'curl-failed'"
|
|
527
|
+
).strip()
|
|
528
|
+
code = _first_http_code(raw)
|
|
529
|
+
if code is not None and "curl-failed" not in raw:
|
|
530
|
+
return f"http://127.0.0.1:{host_port}/ -> HTTP {code}", code < 500, "http"
|
|
531
|
+
# Not HTTP, or nothing answered: fall back to a plain TCP check.
|
|
532
|
+
tcp = target.must(
|
|
533
|
+
f"timeout 5 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/{host_port}' "
|
|
534
|
+
"&& echo OPEN || echo CLOSED"
|
|
535
|
+
).strip()
|
|
536
|
+
if tcp == "OPEN":
|
|
537
|
+
return f"127.0.0.1:{host_port} 端口已监听(尚未有 HTTP 响应)", True, "tcp"
|
|
538
|
+
return f"127.0.0.1:{host_port} 没有任何响应({raw[:40]})", False, "none"
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _logs(target: SshTarget, remote_dir: str) -> str:
|
|
542
|
+
out = target.must(
|
|
543
|
+
f"cd {shlex.quote(remote_dir)} && docker compose logs --tail=120 2>&1 | tail -160 || true"
|
|
544
|
+
)
|
|
545
|
+
return out
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _teardown(target: SshTarget, remote_dir: str, prune_image: bool = False) -> None:
|
|
549
|
+
rmi = " --rmi all" if prune_image else ""
|
|
550
|
+
target.run(
|
|
551
|
+
f"cd {shlex.quote(remote_dir)} && docker compose down -v --remove-orphans{rmi} "
|
|
552
|
+
">/dev/null 2>&1; "
|
|
553
|
+
f"rm -rf {shlex.quote(remote_dir)}"
|
|
554
|
+
)
|
p1toolkit/report.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Issue collection and rendering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
FAIL = "fail"
|
|
10
|
+
WARN = "warn"
|
|
11
|
+
INFO = "info"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Issue:
|
|
16
|
+
rule_id: str
|
|
17
|
+
level: str
|
|
18
|
+
message: str
|
|
19
|
+
file: str | None = None
|
|
20
|
+
line: int | None = None
|
|
21
|
+
|
|
22
|
+
def render(self) -> str:
|
|
23
|
+
location = ""
|
|
24
|
+
if self.file:
|
|
25
|
+
location = f" [{self.file}{':' + str(self.line) if self.line else ''}]"
|
|
26
|
+
return f"{self.level.upper():4s} {self.rule_id}{location} {self.message}"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Report:
|
|
31
|
+
target: str
|
|
32
|
+
issues: list[Issue] = None # type: ignore[assignment]
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
if self.issues is None:
|
|
36
|
+
self.issues = []
|
|
37
|
+
|
|
38
|
+
def add(
|
|
39
|
+
self,
|
|
40
|
+
rule_id: str,
|
|
41
|
+
level: str,
|
|
42
|
+
message: str,
|
|
43
|
+
file: str | Path | None = None,
|
|
44
|
+
line: int | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
self.issues.append(
|
|
47
|
+
Issue(rule_id, level, message, str(file) if file else None, line)
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def fail(self, rule_id: str, message: str, file=None, line: int | None = None) -> None:
|
|
51
|
+
self.add(rule_id, FAIL, message, file, line)
|
|
52
|
+
|
|
53
|
+
def warn(self, rule_id: str, message: str, file=None, line: int | None = None) -> None:
|
|
54
|
+
self.add(rule_id, WARN, message, file, line)
|
|
55
|
+
|
|
56
|
+
def info(self, rule_id: str, message: str, file=None, line: int | None = None) -> None:
|
|
57
|
+
self.add(rule_id, INFO, message, file, line)
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def failures(self) -> list[Issue]:
|
|
61
|
+
return [i for i in self.issues if i.level == FAIL]
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def warnings(self) -> list[Issue]:
|
|
65
|
+
return [i for i in self.issues if i.level == WARN]
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def ok(self) -> bool:
|
|
69
|
+
return not self.failures
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict:
|
|
72
|
+
return {
|
|
73
|
+
"target": self.target,
|
|
74
|
+
"ok": self.ok,
|
|
75
|
+
"counts": {
|
|
76
|
+
"fail": len(self.failures),
|
|
77
|
+
"warn": len(self.warnings),
|
|
78
|
+
"info": len([i for i in self.issues if i.level == INFO]),
|
|
79
|
+
},
|
|
80
|
+
"issues": [asdict(i) for i in self.issues],
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
def render(self, fmt: str = "text") -> str:
|
|
84
|
+
if fmt == "json":
|
|
85
|
+
return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
|
|
86
|
+
lines = [f"# {self.target}"]
|
|
87
|
+
if not self.issues:
|
|
88
|
+
lines.append("OK no issues")
|
|
89
|
+
return "\n".join(lines)
|
|
90
|
+
for issue in sorted(self.issues, key=lambda i: (i.level != FAIL, i.rule_id)):
|
|
91
|
+
lines.append(issue.render())
|
|
92
|
+
counts = self.to_dict()["counts"]
|
|
93
|
+
lines.append(
|
|
94
|
+
f"-> {counts['fail']} fail, {counts['warn']} warn, {counts['info']} info"
|
|
95
|
+
)
|
|
96
|
+
return "\n".join(lines)
|