Skip to content

<fix>[kvm]: decouple TLS cert detection from libvirtd restart toggle#3866

Open
zstack-robot-2 wants to merge 1 commit into5.5.16from
sync/yingzhe.hu/fix/ZSTAC-84446-reopen
Open

<fix>[kvm]: decouple TLS cert detection from libvirtd restart toggle#3866
zstack-robot-2 wants to merge 1 commit into5.5.16from
sync/yingzhe.hu/fix/ZSTAC-84446-reopen

Conversation

@zstack-robot-2
Copy link
Copy Markdown
Collaborator

Resolves: ZSTAC-84446

Change-Id: I9bed31c0cefddd6ed11f59cd13e36eb1c2abc029

sync from gitlab !9741

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 27, 2026

演练

在启用 LIBVIRT_TLS_ENABLED 时始终进行 TLS 证书/SAN 检测(以最佳努力方式处理错误),并新增 KVMHostUtils.shouldForceTlsRedeploy(...) 决策以决定是否在部署时强制 ansible 重跑并重启 libvirtd。

变更

Cohort / File(s) Summary
KVM 主机连接与部署逻辑
plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java
将证书/SAN 检测从依赖 RECONNECT_HOST_RESTART_LIBVIRTD_SERVICE 中解耦:只要 LIBVIRT_TLS_ENABLED 生效即执行检测,检测中遇到 SSH/openssl/证书解析错误记录为警告并继续;部署阶段改为调用 KVMHostUtils.shouldForceTlsRedeploy(...) 决定是否强制 ansible 重跑并设置 deployArguments.restartLibvirtd,若不允许则跳过强制并记录信息。
重部署决策工具
plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java
新增 public static boolean shouldForceTlsRedeploy(boolean needDeployTlsCert, boolean allowRestartLibvirtd, boolean isNewAdded),封装是否应在需要部署 TLS 证书时强制触发 redeploy/restart 的判断(不需部署时返回 false;需部署时仅在允许重启或为新加入主机时返回 true)。
单元测试
test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java
新增四个 JUnit 测试覆盖 shouldForceTlsRedeploy:不需部署短路、允许重启触发、新增主机触发、重连但禁止重启时跳过。

评估代码审核工作量

🎯 3 (中等) | ⏱️ ~20 分钟

🐰 兔儿轻踏机房间,
证书窥视不再等闲,
策略一言定重启,
新主机欢跃入队列,
测试守护细心看。

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed PR标题遵循了[scope]: 格式,长度为68字符(≤72),清晰准确地描述了核心变更内容。
Description check ✅ Passed PR描述包含了JIRA问题号(ZSTAC-84446)和GitLab同步参考(!9741),与代码变更相关联。
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch sync/yingzhe.hu/fix/ZSTAC-84446-reopen

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ast-grep (0.42.1)
plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java (1)

143-145: 建议把多布尔入参改成语义化类型,降低调用歧义

Line [143-145] 的方法签名使用了 3 个布尔参数,调用点会出现 true/false/true 这类“位置语义”问题,后续维护和扩展风险较高。建议改成枚举(或拆分成场景化方法)。

♻️ 示例改法
+    public enum HostConnectScene {
+        NEW_ADD,
+        RECONNECT
+    }
+
     public static boolean shouldForceTlsRedeploy(boolean needDeployTlsCert,
                                                  boolean allowRestartLibvirtd,
-                                                 boolean isNewAdded) {
+                                                 HostConnectScene scene) {
         if (!needDeployTlsCert) {
             return false;
         }
-        return allowRestartLibvirtd || isNewAdded;
+        return allowRestartLibvirtd || scene == HostConnectScene.NEW_ADD;
     }

As per coding guidelines, “避免使用布尔型参数造成含义不明确。例如建议拆分函数或使用枚举表达操作类型”。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java` around lines 143 -
145, The method KVMHostUtils.shouldForceTlsRedeploy currently takes three
boolean flags (needDeployTlsCert, allowRestartLibvirtd, isNewAdded) which causes
call-site ambiguity; replace the boolean parameters with a semantic type (e.g.,
an enum like TlsRedeployReason or a small value-object) or split into explicit
methods (e.g., shouldForceTlsRedeployForNewHost,
shouldForceTlsRedeployWithRestartPermission) and update all callers to pass the
enum/value-object or call the new methods; ensure the new enum/value-object
exposes clear names for each condition and update the method signature and
internal logic in shouldForceTlsRedeploy accordingly so callers no longer pass
positional true/false values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java`:
- Around line 143-145: The method KVMHostUtils.shouldForceTlsRedeploy currently
takes three boolean flags (needDeployTlsCert, allowRestartLibvirtd, isNewAdded)
which causes call-site ambiguity; replace the boolean parameters with a semantic
type (e.g., an enum like TlsRedeployReason or a small value-object) or split
into explicit methods (e.g., shouldForceTlsRedeployForNewHost,
shouldForceTlsRedeployWithRestartPermission) and update all callers to pass the
enum/value-object or call the new methods; ensure the new enum/value-object
exposes clear names for each condition and update the method signature and
internal logic in shouldForceTlsRedeploy accordingly so callers no longer pass
positional true/false values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: http://open.zstack.ai:20001/code-reviews/zstack-cloud.yaml (via .coderabbit.yaml)

Review profile: CHILL

Plan: Pro

Run ID: 392c51ce-a26b-47d8-80bb-87568a29f7d7

📥 Commits

Reviewing files that changed from the base of the PR and between e693653 and 1b6b10c.

📒 Files selected for processing (3)
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java
  • test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java

@MatheMatrix MatheMatrix force-pushed the sync/yingzhe.hu/fix/ZSTAC-84446-reopen branch from 1b6b10c to 3309397 Compare April 27, 2026 09:29
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java (1)

177-199: 测试方法名建议改为 lowerCamelCase 以符合 Java 规范。

shouldForceTlsRedeploy_noNeedNeverForces 等方法名含下划线,建议统一改成 shouldForceTlsRedeployNoNeedNeverForces 这类 lowerCamelCase。

✏️ 建议修改
-    public void shouldForceTlsRedeploy_noNeedNeverForces() {
+    public void shouldForceTlsRedeployNoNeedNeverForces() {
@@
-    public void shouldForceTlsRedeploy_allowRestartForces() {
+    public void shouldForceTlsRedeployAllowRestartForces() {
@@
-    public void shouldForceTlsRedeploy_newAddedForces() {
+    public void shouldForceTlsRedeployNewAddedForces() {
@@
-    public void shouldForceTlsRedeploy_reconnectWithoutRestartSkips() {
+    public void shouldForceTlsRedeployReconnectWithoutRestartSkips() {

As per coding guidelines, “方法名、参数名、成员变量和局部变量:使用 lowerCamelCase 风格。”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java` around lines
177 - 199, The test method names use underscores and should be converted to
lowerCamelCase to match Java conventions: rename
shouldForceTlsRedeploy_noNeedNeverForces ->
shouldForceTlsRedeployNoNeedNeverForces,
shouldForceTlsRedeploy_allowRestartForces ->
shouldForceTlsRedeployAllowRestartForces, shouldForceTlsRedeploy_newAddedForces
-> shouldForceTlsRedeployNewAddedForces, and
shouldForceTlsRedeploy_reconnectWithoutRestartSkips ->
shouldForceTlsRedeployReconnectWithoutRestartSkips (update the method
declarations and any references or test runners accordingly) in the
KVMHostUtilsTest class so all test method names follow lowerCamelCase.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java`:
- Around line 5719-5722: 当前 TLS 证书探测在 connectHook 中直接调用 collectHostIps(...)
并可能抛出异常或返回异常值,导致整个重连流程失败;请将整段探测逻辑按
KvmSecureBootExtensions.syncVmHostFilesFromHost 的模式用 try/catch 包裹,捕获所有异常并在 catch
中记录告警日志(说明是 TLS 探测失败及相关主机信息),然后无条件调用 trigger.next(),保持 NEED_DEPLOY_TLS_CERT
为最佳努力语义且不阻塞 connectHook 的继续执行;确保引用方法名 collectHostIps、标志 NEED_DEPLOY_TLS_CERT
和触发器 trigger.next() 以便准确定位修改位置。

---

Nitpick comments:
In `@test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java`:
- Around line 177-199: The test method names use underscores and should be
converted to lowerCamelCase to match Java conventions: rename
shouldForceTlsRedeploy_noNeedNeverForces ->
shouldForceTlsRedeployNoNeedNeverForces,
shouldForceTlsRedeploy_allowRestartForces ->
shouldForceTlsRedeployAllowRestartForces, shouldForceTlsRedeploy_newAddedForces
-> shouldForceTlsRedeployNewAddedForces, and
shouldForceTlsRedeploy_reconnectWithoutRestartSkips ->
shouldForceTlsRedeployReconnectWithoutRestartSkips (update the method
declarations and any references or test runners accordingly) in the
KVMHostUtilsTest class so all test method names follow lowerCamelCase.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: http://open.zstack.ai:20001/code-reviews/zstack-cloud.yaml (via .coderabbit.yaml)

Review profile: CHILL

Plan: Pro

Run ID: 25d2616a-9a0c-48f1-9283-628d0de8cd7e

📥 Commits

Reviewing files that changed from the base of the PR and between 1b6b10c and 3309397.

📒 Files selected for processing (3)
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java
  • test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java

Comment thread plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java
Resolves: ZSTAC-84446

Change-Id: I9bed31c0cefddd6ed11f59cd13e36eb1c2abc029
@MatheMatrix MatheMatrix force-pushed the sync/yingzhe.hu/fix/ZSTAC-84446-reopen branch from 3309397 to ad8a4c5 Compare April 27, 2026 10:29
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java (1)

177-199: 测试方法名应遵循 lowerCamelCase 规范。

当前四个测试方法名包含下划线:

  • shouldForceTlsRedeploy_noNeedNeverForces
  • shouldForceTlsRedeploy_allowRestartForces
  • shouldForceTlsRedeploy_newAddedForces
  • shouldForceTlsRedeploy_reconnectWithoutRestartSkips

建议改为 shouldForceTlsRedeployNoNeedNeverForcesshouldForceTlsRedeployAllowRestartForces 等纯 lowerCamelCase 形式,以符合编码指南中对方法命名的要求。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java` around lines
177 - 199, The test method names use underscores and must be converted to
lowerCamelCase; rename the four methods
shouldForceTlsRedeploy_noNeedNeverForces,
shouldForceTlsRedeploy_allowRestartForces,
shouldForceTlsRedeploy_newAddedForces, and
shouldForceTlsRedeploy_reconnectWithoutRestartSkips to
shouldForceTlsRedeployNoNeedNeverForces,
shouldForceTlsRedeployAllowRestartForces, shouldForceTlsRedeployNewAddedForces,
and shouldForceTlsRedeployReconnectWithoutRestartSkips respectively, updating
their declarations and any references (e.g., in test runners or IDE
configurations) so the `@Test` methods in KVMHostUtilsTest compile and run under
the project’s lowerCamelCase naming convention.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java`:
- Around line 5741-5759: The certIpList returned by KVMHostUtils.collectHostIps
is used raw (split(",")) which can produce empty or whitespace entries and cause
false positives in the SAN comparison; normalize and filter it before use: split
certIpList, trim each entry, remove empty strings, rebuild certIpList (or a
canonicalList) and set data.put("TLS_DETECTED_IPS", canonicalList) and use that
canonicalList to populate allIps; keep using parseSanIps(...) and the existing
needDeploy logic but compare against the cleaned allIps to avoid unnecessary
redeploys.

---

Nitpick comments:
In `@test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java`:
- Around line 177-199: The test method names use underscores and must be
converted to lowerCamelCase; rename the four methods
shouldForceTlsRedeploy_noNeedNeverForces,
shouldForceTlsRedeploy_allowRestartForces,
shouldForceTlsRedeploy_newAddedForces, and
shouldForceTlsRedeploy_reconnectWithoutRestartSkips to
shouldForceTlsRedeployNoNeedNeverForces,
shouldForceTlsRedeployAllowRestartForces, shouldForceTlsRedeployNewAddedForces,
and shouldForceTlsRedeployReconnectWithoutRestartSkips respectively, updating
their declarations and any references (e.g., in test runners or IDE
configurations) so the `@Test` methods in KVMHostUtilsTest compile and run under
the project’s lowerCamelCase naming convention.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: http://open.zstack.ai:20001/code-reviews/zstack-cloud.yaml (via .coderabbit.yaml)

Review profile: CHILL

Plan: Pro

Run ID: 5c0be66c-e4d3-4e34-9989-f986ca61035a

📥 Commits

Reviewing files that changed from the base of the PR and between 3309397 and ad8a4c5.

📒 Files selected for processing (3)
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java
  • test/src/test/java/org/zstack/test/kvm/KVMHostUtilsTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugin/kvm/src/main/java/org/zstack/kvm/KVMHostUtils.java

Comment on lines +5741 to +5759
String certIpList = KVMHostUtils.collectHostIps(
sshShell, self.getUuid(), managementIp);
List<String> allIps = new ArrayList<>(Arrays.asList(certIpList.split(",")));
// Save detected IPs so apply-ansible-playbook can union with
// EXTRA_IPS without running a second SSH.
data.put("TLS_DETECTED_IPS", certIpList);

SshResult sanResult = sshShell.runCommand(
"openssl x509 -in /etc/pki/libvirt/servercert.pem -noout -ext subjectAltName 2>/dev/null");

boolean needDeploy = false;
if (sanResult.isSshFailure() || sanResult.getReturnCode() != 0
|| sanResult.getStdout() == null || sanResult.getStdout().trim().isEmpty()) {
logger.info(String.format("TLS cert not found or unreadable on host[uuid:%s], need deploy", self.getUuid()));
needDeploy = true;
} else {
Set<String> sanIps = parseSanIps(sanResult.getStdout());
for (String ip : allIps) {
if (!sanIps.contains(ip)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

先规范化 certIpList,否则这里会误判需要重部署。

Line 5743 直接 split(",") 后没有 trim/过滤空值。只要 collectHostIps(...) 的返回里带空格、尾逗号,或者是空串,后面的 SAN 对比就可能把 NEED_DEPLOY_TLS_CERT 错误置为 true

🛠️ 建议修改
-                            List<String> allIps = new ArrayList<>(Arrays.asList(certIpList.split(",")));
+                            List<String> allIps = Arrays.stream(certIpList.split(","))
+                                    .map(String::trim)
+                                    .filter(StringUtils::isNotBlank)
+                                    .collect(Collectors.toList());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/kvm/src/main/java/org/zstack/kvm/KVMHost.java` around lines 5741 -
5759, The certIpList returned by KVMHostUtils.collectHostIps is used raw
(split(",")) which can produce empty or whitespace entries and cause false
positives in the SAN comparison; normalize and filter it before use: split
certIpList, trim each entry, remove empty strings, rebuild certIpList (or a
canonicalList) and set data.put("TLS_DETECTED_IPS", canonicalList) and use that
canonicalList to populate allIps; keep using parseSanIps(...) and the existing
needDeploy logic but compare against the cleaned allIps to avoid unnecessary
redeploys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants