Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Retry Docker kernel startup checks and preserve failure logs

Danielbb0ec25fcb9d
diff --git a/.github/workflows/dockerimage.yml b/.github/workflows/dockerimage.yml
index b8cf168521..be7cf17ccd 100644
--- a/.github/workflows/dockerimage.yml
+++ b/.github/workflows/dockerimage.yml
@@ -231,6 +231,7 @@ jobs:
${{ runner.temp }}/docker-build.log
${{ runner.temp }}/docker-metadata.json
${{ runner.temp }}/docker-verification/report.json
+ ${{ runner.temp }}/docker-verification/diagnostics
if-no-files-found: ignore
cache:
diff --git a/scripts/test_docker_release.py b/scripts/test_docker_release.py
index 97ce2a0c2b..1543748a09 100644
--- a/scripts/test_docker_release.py
+++ b/scripts/test_docker_release.py
@@ -1,7 +1,10 @@
"""Docker 发布验收、manifest 校验和缓存日志的回归测试,不构建镜像。"""
import copy
+import contextlib
+import http.client
import importlib.util
+import io
import json
import os
from pathlib import Path
@@ -9,7 +12,7 @@ import shutil
import subprocess
import tempfile
import unittest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
def module(name, file):
@@ -166,6 +169,85 @@ class PublishTests(unittest.TestCase):
self.assertEqual(commands.call_args_list[-1].args[0][-1], cleanup[0][-1] + "-workspace")
+class NotebookStartupTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.diagnostics = Path(self.temp.name) / "diagnostics"
+ self.running = "true"
+
+ def command(self, arguments, **kwargs):
+ output = ""
+ if arguments[:2] == ["docker", "logs"]:
+ output = "kernel startup log\n"
+ elif arguments[:2] == ["docker", "inspect"]:
+ if "{{.State.Running}}" in arguments:
+ output = self.running
+ elif "{{json .State}}" in arguments:
+ output = json.dumps({"Running": self.running == "true", "ExitCode": 1})
+ else:
+ output = json.dumps([{"NetworkSettings": {"Ports": {"6806/tcp": [{"HostPort": "12345"}]}}}])
+ return subprocess.CompletedProcess(arguments, 0, output, "")
+
+ def test_startup_reset_and_early_disconnect_are_retried_until_ready(self):
+ responses = [ConnectionResetError("reset before ready"), http.client.RemoteDisconnected("not ready"),
+ {"progress": 40}, {"progress": 100}, "3.8.7", {"notebook": {"id": "box"}},
+ "block", {"kramdown": "Docker OCR smoke 123"}]
+ fail_ocr = Mock()
+ with patch.object(release, "run", side_effect=self.command), \
+ patch.object(release, "request", side_effect=responses) as request, patch.object(release.time, "sleep") as sleep:
+ release.verify_notebook(IMAGE, "linux/amd64", "3.8.7", 240, fail_ocr, self.diagnostics)
+ self.assertEqual(sleep.call_count, 3)
+ fail_ocr.assert_called_once()
+ endpoints = [call.args[1] for call in request.call_args_list]
+ self.assertEqual(endpoints[:4], ["/api/system/bootProgress"] * 4)
+ self.assertEqual(endpoints.count("/api/notebook/createNotebook"), 1)
+ self.assertFalse(self.diagnostics.exists())
+
+ def test_persistent_reset_times_out_with_diagnostics_and_never_writes_notebook(self):
+ fail_ocr = Mock()
+ with patch.object(release, "run", side_effect=self.command) as run, \
+ patch.object(release, "request", side_effect=ConnectionResetError("still resetting")) as request, \
+ patch.object(release.time, "monotonic", side_effect=[0, 0, 11]), \
+ patch.object(release.time, "sleep"), contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaisesRegex(TimeoutError, "still resetting"):
+ release.verify_notebook(IMAGE, "linux/amd64", "3.8.7", 10, fail_ocr, self.diagnostics)
+ fail_ocr.assert_not_called()
+ self.assertTrue(all(call.args[1] == "/api/system/bootProgress" for call in request.call_args_list))
+ self.assertEqual(self.diagnostics.joinpath("kernel.log").read_text(encoding="utf-8"), "kernel startup log\n")
+ self.assertTrue(self.diagnostics.joinpath("kernel-state.json").is_file())
+ self.assertEqual(run.call_args_list[-1].args[0][:3], ["docker", "volume", "rm"])
+
+ def test_exited_kernel_fails_immediately_and_keeps_exit_state(self):
+ self.running = "false"
+ with patch.object(release, "run", side_effect=self.command), \
+ patch.object(release, "request", side_effect=ConnectionResetError("reset")), \
+ patch.object(release.time, "sleep") as sleep, contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaisesRegex(RuntimeError, "stopped before booting"):
+ release.verify_notebook(IMAGE, "linux/amd64", "3.8.7", 240, Mock(), self.diagnostics)
+ sleep.assert_not_called()
+ self.assertFalse(json.loads(self.diagnostics.joinpath("kernel-state.json").read_text())["Running"])
+
+ def test_connection_failure_after_ready_does_not_retry_notebook_mutations(self):
+ responses = [{"progress": 100}, "3.8.7", ConnectionResetError("write failed")]
+ with patch.object(release, "run", side_effect=self.command), \
+ patch.object(release, "request", side_effect=responses) as request, contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaisesRegex(ConnectionResetError, "write failed"):
+ release.verify_notebook(IMAGE, "linux/amd64", "3.8.7", 240, Mock(), self.diagnostics)
+ self.assertEqual([call.args[1] for call in request.call_args_list].count("/api/notebook/createNotebook"), 1)
+
+ def test_diagnostic_collection_failure_preserves_original_verification_error(self):
+ def command(arguments, **kwargs):
+ if arguments[:2] == ["docker", "logs"] or "{{json .State}}" in arguments:
+ raise OSError("diagnostic unavailable")
+ return self.command(arguments, **kwargs)
+ with patch.object(release, "run", side_effect=command), \
+ patch.object(release, "request", side_effect=[{"progress": 100}, "wrong version"]), \
+ contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaisesRegex(ValueError, "version differs"):
+ release.verify_notebook(IMAGE, "linux/amd64", "3.8.7", 240, Mock(), self.diagnostics)
+
+
class PlatformReleaseTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
diff --git a/scripts/verify-docker-release.py b/scripts/verify-docker-release.py
index bfbfbf4c38..2445f85f4e 100644
--- a/scripts/verify-docker-release.py
+++ b/scripts/verify-docker-release.py
@@ -74,7 +74,7 @@ def request(base, endpoint, token, payload=None):
return result["data"]
-def verify_notebook(image, platform, version, timeout, fail_ocr):
+def verify_notebook(image, platform, version, timeout, fail_ocr, diagnostics=None):
# 只使用本次测试创建的容器和卷,所有读写均发生在临时工作空间。
name = "siyuan-docker-smoke-" + uuid.uuid4().hex
volume, token = name + "-workspace", uuid.uuid4().hex
@@ -91,17 +91,19 @@ def verify_notebook(image, platform, version, timeout, fail_ocr):
bindings = json.loads(run(["docker", "inspect", name]).stdout)[0]["NetworkSettings"]["Ports"]["6806/tcp"]
base = "http://127.0.0.1:" + bindings[0]["HostPort"]
deadline = time.monotonic() + timeout
+ last_error = ""
while True:
try:
progress = request(base, "/api/system/bootProgress", token)
if progress["progress"] == 100:
break
- except (urllib.error.URLError, TimeoutError, ValueError):
- pass
+ except (urllib.error.URLError, TimeoutError, ConnectionError, ValueError) as error:
+ # 端口转发已建立但内核尚未就绪时,HTTP 请求可能被重置或提前断开。
+ last_error = str(error)
if time.monotonic() >= deadline:
- raise TimeoutError(f"Kernel did not boot: {platform}\n" + run(["docker", "logs", name]).stdout)
+ raise TimeoutError(f"Kernel did not boot: {platform}; last response: {last_error}")
if run(["docker", "inspect", "--format", "{{.State.Running}}", name]).stdout.strip() != "true":
- raise RuntimeError("Kernel stopped before booting\n" + run(["docker", "logs", name]).stdout)
+ raise RuntimeError("Kernel stopped before booting")
time.sleep(2)
if request(base, "/api/system/version", token) != version:
raise ValueError("HTTP kernel version differs from release version")
@@ -112,12 +114,26 @@ def verify_notebook(image, platform, version, timeout, fail_ocr):
data = request(base, "/api/block/getBlockKramdown", token, {"id": block})
if "Docker OCR smoke 123" not in data["kramdown"]:
raise ValueError("Notebook write/read verification failed")
+ except Exception:
+ # 删除临时容器前保留启动日志和退出状态,采集失败不能覆盖原始验收错误。
+ for filename, command in (("kernel.log", ["docker", "logs", name]),
+ ("kernel-state.json", ["docker", "inspect", "--format", "{{json .State}}", name])):
+ try:
+ result = run(command, check=False, timeout=30)
+ output = result.stdout + result.stderr
+ print(f"{platform} {filename}:\n{output}", flush=True)
+ if diagnostics is not None:
+ diagnostics.mkdir(parents=True, exist_ok=True)
+ (diagnostics / filename).write_text(output, encoding="utf-8")
+ except Exception as error:
+ print(f"Unable to collect {filename}: {error}", flush=True)
+ raise
finally:
run(["docker", "rm", "-f", name], check=False)
run(["docker", "volume", "rm", volume], check=False)
-def verify_platform(repository, digest, platform, version, fixtures, timeout):
+def verify_platform(repository, digest, platform, version, fixtures, timeout, diagnostics=None):
started = time.monotonic()
image = repository + "@" + digest
architecture = platform.split("/")[1]
@@ -154,7 +170,7 @@ def verify_platform(repository, digest, platform, version, fixtures, timeout):
raise ValueError("Missing OCR runtime did not produce the expected failure")
checks.append("worker-failure")
- verify_notebook(image, platform, version, timeout, fail_ocr)
+ verify_notebook(image, platform, version, timeout, fail_ocr, diagnostics)
checks.append("notebook")
finally:
run(["docker", "rm", "-f", worker_name], check=False)
@@ -174,7 +190,9 @@ def verify(image, version, fixtures, report_path, timeout, *, platform=None, pro
try:
for platform in expected:
print(f"Verifying {platform} in Docker", flush=True)
- report["platforms"].append(verify_platform(repository, index[platform], platform, version, fixtures, timeout))
+ diagnostics = report_path.parent / "diagnostics" / platform.replace("/", "-")
+ report["platforms"].append(verify_platform(repository, index[platform], platform, version, fixtures, timeout,
+ diagnostics=diagnostics))
report["status"] = "passed"
except Exception as error:
report.update(status="failed", error=str(error))