-
Notifications
You must be signed in to change notification settings - Fork 0
<fix>[compute]: <description #3183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: zsv_4.10.28
Are you sure you want to change the base?
Conversation
Walkthrough在 VmInstanceBase.java 中,替换了原先 APIRecoverVmInstanceMsg 的占位恢复处理器,新增了内部静态类 VmMetadata;新处理器从当前记录收集虚拟机、卷、网卡、快照与快照组元数据,将其序列化为 JSON 并写入日志。还添加了若干快照相关的导入。 Changes
Sequence Diagram(s)sequenceDiagram
participant API as APIRecoverVmInstanceMsg
participant Handler as VmInstanceBase.handler()
participant DB as Database/DAOs
participant Serializer as JSON Serializer
participant Logger as Logger
API->>Handler: invoke recovery request
Handler->>DB: query VM, volumes, NICs, snapshots, snapshot-groups
DB-->>Handler: return records
Handler->>Serializer: assemble VmMetadata -> serialize JSON
Serializer-->>Handler: JSON payload
Handler->>Logger: log metadata JSON
Logger-->>API: ack (logged)
📊 代码审查工作量评估🎯 2 (Simple) | ⏱️ ~10 分钟 概览在 VmInstanceBase.java 中,用新的内联实现替换了 APIRecoverVmInstanceMsg 的占位符恢复处理器。新实现引入了 VmMetadata 内部类,收集并序列化 VM、卷、网卡和快照元数据,然后将其记录到日志中。同时添加了相关的卷快照导入。 变更内容
🐰 庆祝诗
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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.40.5)compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.javaComment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java:
- Around line 4863-4905: The handler for APIRecoverVmInstanceMsg has been fully
commented out while handleApiMessage still routes messages to it, causing a
silent no-op; either restore the original implementation in
VmInstanceBase.handle(APIRecoverVmInstanceMsg) (reintroduce the thdf.chainSubmit
ChainTask that calls validateOperationByState, refreshVO, recoverVm with the
Completion that publishes APIRecoverVmInstanceEvent via bus and uses
getSelfInventory on success), or explicitly remove the routing in
handleApiMessage and return/publish a clear error event immediately so callers
don’t get a silent success; ensure references to APIRecoverVmInstanceMsg,
APIRecoverVmInstanceEvent, validateOperationByState, recoverVm,
getSelfInventory, and thdf.chainSubmit are updated accordingly.
- Around line 9373-9377: The handler method
VmInstanceBase.handle(APIRecoverVmInstanceMsg msg) is empty and must publish an
APIRecoverVmInstanceEvent so callers get a response; restore the original
recovery flow: create an APIRecoverVmInstanceEvent for msg.getId(), attempt the
VM recovery logic (reuse the existing recovery code path or invoke the recovery
helper used elsewhere), on success set event.setInventory(...) and publish the
event via bus.publish(event), and on failure catch the exception, log it and
publish an event with error code/event.setError(errCode) or throw a
CloudRuntimeException as your pattern requires; ensure you reference
APIRecoverVmInstanceMsg, APIRecoverVmInstanceEvent and the
VmInstanceBase.handle(...) method when implementing the fix.
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java
🧰 Additional context used
📓 Path-based instructions (1)
**/*.java
⚙️ CodeRabbit configuration file
**/*.java: ## 1. API 设计要求
- API 命名:
- API 名称必须唯一,不能重复。
- API 消息类需要继承
APIMessage;其返回类必须继承APIReply或APIEvent,并在注释中用@RestResponse进行标注。- API 消息上必须添加注解
@RestRequest,并满足如下规范:
path:
- 针对资源使用复数形式。
- 当 path 中引用消息类变量时,使用
{variableName}格式。- HTTP 方法对应:
- 查询操作 →
HttpMethod.GET- 更新操作 →
HttpMethod.PUT- 创建操作 →
HttpMethod.POST- 删除操作 →
HttpMethod.DELETE- API 类需要实现
__example__方法以便生成 API 文档,并确保生成对应的 Groovy API Template 与 API Markdown 文件。
2. 命名与格式规范
类名:
- 使用 UpperCamelCase 风格。
- 特殊情况:
- VO/AO/EO 类型类除外。
- 抽象类采用
Abstract或Base前缀/后缀。- 异常类应以
Exception结尾。- 测试类需要以
Test或Case结尾。方法名、参数名、成员变量和局部变量:
- 使用 lowerCamelCase 风格。
常量命名:
- 全部大写,使用下划线分隔单词。
- 要求表达清楚,避免使用含糊或不准确的名称。
包名:
- 统一使用小写,使用点分隔符,每个部分应是一个具有自然语义的英文单词(参考 Spring 框架的结构)。
命名细节:
- 避免在父子类或同一代码块中出现相同名字的成员或局部变量,防止混淆。
- 命名缩写:
- 不允许使用不必要的缩写,如:
AbsSchedulerJob、condi、Fu等。应使用完整单词提升可读性。
3. 编写自解释代码
意图表达:
- 避免使用布尔型参数造成含义不明确。例如:
- 对于
stopAgent(boolean ignoreError),建议拆分为不同函数(如stopAgentIgnoreError()),或使用枚举表达操作类型。- 命名应尽量用完整的单词组合表达意图,并在名称中体现数据类型或用途(例如在常量与变量名称中,将类型词放在末尾)。
注释:
- 代码应尽量做到自解释,对少于两行的说明可以直接写在代码中。
- 对于较长的注释,需要仔细校对并随代码更新,确保内容正确。
- 接口方法不应有多余的修饰符(例如
public),且必须配有有效的 Javadoc 注释。
4. 流程控制和结构优化
if...else 的使用:
- 应尽量减少 if...else 结构的使用,建议:
- 限制嵌套层级最多为两层,且内层不应再出现
else分支。- 尽早返回(Early Return),将条件判断中的处理逻辑提前结束或抽成独立方法。
- 使用 Java Stream 或 Lambda 表达式代替冗长的循环与条件判断。
条件判断:
- if 条件表达不宜过长或过于复杂,必要时可以将条件抽成 boolean 变量描述。
代码块长度:
- 单个 if 代码块不宜超过一屏显示,以提高可读性和后续维护性。
5. 异常处理与日志
- 捕获异常的原则:
- 对于可以通过预检查避免的 RuntimeException(如
NullPointerException、IndexOutOfBoundsException等),不建议使用 try-catch 来进行处理。- 捕获异常应仅用于处理真正的意外情况,不应将异常逻辑当作正常流程控制。
- 在必要时,应继续抛出异常,使上层业务处理者可以转换为用户友好的错误提示。
- 使用 try-with-resources 语法管理资源,确保在 finally 块中正确关闭资源,并避免在 finally 中返回值。
...
Files:
compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java
🧠 Learnings (3)
📓 Common learnings
Learnt from: zstack-robot-1
Repo: MatheMatrix/zstack PR: 2360
File: network/src/main/java/org/zstack/network/l3/L3BasicNetwork.java:449-490
Timestamp: 2025-08-04T04:48:19.103Z
Learning: ZStack项目在cherry-pick操作中,即使发现了性能优化机会(如IP地址批量保存的内存优化),也严格遵循不做额外修改的政策,优先保证cherry-pick的完整性和一致性。
Learnt from: ZStack-Robot
Repo: MatheMatrix/zstack PR: 2489
File: storage/src/main/java/org/zstack/storage/snapshot/VolumeTree.java:471-545
Timestamp: 2025-08-22T05:36:40.467Z
Learning: In ZStack项目中,对于核心逻辑相关的代码,团队倾向于暂时不进行重构,即使代码复杂度较高,优先保证核心功能的稳定性。
Learnt from: ZStack-Robot
Repo: MatheMatrix/zstack PR: 2325
File: compute/src/main/java/org/zstack/compute/vm/VmMigrateCallExtensionFlow.java:29-29
Timestamp: 2025-07-24T05:53:10.246Z
Learning: 在ZStack项目的重构过程中,团队采用务实的优先级策略:优先完成影响运行时功能的代码重构,对于注释中的旧引用等非功能性问题可以延后处理,因为这些不会影响系统的实际运行。
Learnt from: zstack-robot-1
Repo: MatheMatrix/zstack PR: 2360
File: compute/src/main/java/org/zstack/compute/vm/StaticIpOperator.java:364-501
Timestamp: 2025-08-04T03:19:07.454Z
Learning: In ZStack project, developers may prefer to keep related validation logic together in a single method (like validateStaticIpTagsInApiMessage with 130+ lines) when the architecture is clear and there's no code reuse, rather than splitting into smaller methods based purely on single responsibility principle.
Learnt from: ZStack-Robot
Repo: MatheMatrix/zstack PR: 2419
File: plugin/sdnController/src/main/java/org/zstack/sdnController/SdnControllerBase.java:986-1067
Timestamp: 2025-08-13T02:31:40.023Z
Learning: 在ZStack项目中,团队倾向于保持统一的业务流程方法不进行拆分,即使方法较长也会维持在单个方法中以保持业务逻辑的完整性。
Learnt from: zstack-robot-2
Repo: MatheMatrix/zstack PR: 2496
File: plugin/sharedMountPointPrimaryStorage/src/main/java/org/zstack/storage/primary/smp/KvmBackend.java:2545-2566
Timestamp: 2025-08-24T07:35:42.793Z
Learning: 在 ZStack 代码库中,当响应类包含数值字段(如 size、actualSize)时,优先使用原始类型(long)而不是包装类型(Long),以避免 NPE 风险和不必要的装箱/拆箱操作。如果 Agent 端可能不设置该字段,应在 Agent 端确保设置默认值,而不是在使用端做 null 检查。
📚 Learning: 2025-08-14T06:56:19.585Z
Learnt from: zstack-robot-2
Repo: MatheMatrix/zstack PR: 2435
File: storage/src/main/java/org/zstack/storage/snapshot/group/VolumeSnapshotGroupBase.java:47-47
Timestamp: 2025-08-14T06:56:19.585Z
Learning: 在VolumeSnapshotGroupBase.java中,VmInstanceResourceMetadataManager的注入和SKIP_RESOURCE_ROLLBACK标记虽然在当前版本中未被使用,但这些导入在大型重构PR中是有意为之的,用于保持代码一致性或为后续功能做准备。
Applied to files:
compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java
📚 Learning: 2025-08-12T05:52:18.323Z
Learnt from: MatheMatrix
Repo: MatheMatrix/zstack PR: 2418
File: compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java:3873-3885
Timestamp: 2025-08-12T05:52:18.323Z
Learning: 在 compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java 的 setNoIpAllocationStaticIp() 流程中,静态 IP 标签删除已统一在 change-ip-in-database 步骤对 voRemoveSet 循环处理:对收集到的旧 IPv4/IPv6 UsedIpVO 均调用 ipOperator.deleteStaticIpByVmUuidAndL3Uuid(vmUuid, l3Uuid, IPv6NetworkUtils.ipv6AddessToTagValue(ip)) 清理对应的 static-ip 标签。因此无需在分支里分别删除 IPv4/IPv6 的标签。
Applied to files:
compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java
| // private void handle(final APIRecoverVmInstanceMsg msg) { | ||
| // thdf.chainSubmit(new ChainTask(msg) { | ||
| // @Override | ||
| // public String getSyncSignature() { | ||
| // return syncThreadName; | ||
| // } | ||
| // | ||
| // @Override | ||
| // public void run(final SyncTaskChain chain) { | ||
| // final APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId()); | ||
| // refreshVO(); | ||
| // | ||
| // ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); | ||
| // if (error != null) { | ||
| // evt.setError(error); | ||
| // bus.publish(evt); | ||
| // chain.next(); | ||
| // return; | ||
| // } | ||
| // | ||
| // recoverVm(new Completion(msg, chain) { | ||
| // @Override | ||
| // public void success() { | ||
| // evt.setInventory(getSelfInventory()); | ||
| // bus.publish(evt); | ||
| // chain.next(); | ||
| // } | ||
| // | ||
| // @Override | ||
| // public void fail(ErrorCode errorCode) { | ||
| // evt.setError(errorCode); | ||
| // bus.publish(evt); | ||
| // chain.next(); | ||
| // } | ||
| // }); | ||
| // } | ||
| // | ||
| // @Override | ||
| // public String getName() { | ||
| // return "recover-vm"; | ||
| // } | ||
| // }); | ||
| // } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
恢复 APIRecoverVmInstanceMsg 的实际执行路径,避免当前“注释实现”造成的功能回归与误导
这里把原实现整段注释掉,但 handleApiMessage() 仍然会把 APIRecoverVmInstanceMsg 路由到该 handler;结合下方新增的空实现(Line 9373-9377),当前 API recover 语义等同于被禁用,且从代码阅读角度非常容易误判“只是临时注释”。
建议:要么恢复实现(见下方建议 diff),要么明确删除路由/直接返回错误事件(避免 silent no-op)。
🤖 Prompt for AI Agents
In @compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java around lines
4863 - 4905, The handler for APIRecoverVmInstanceMsg has been fully commented
out while handleApiMessage still routes messages to it, causing a silent no-op;
either restore the original implementation in
VmInstanceBase.handle(APIRecoverVmInstanceMsg) (reintroduce the thdf.chainSubmit
ChainTask that calls validateOperationByState, refreshVO, recoverVm with the
Completion that publishes APIRecoverVmInstanceEvent via bus and uses
getSelfInventory on success), or explicitly remove the routing in
handleApiMessage and return/publish a clear error event immediately so callers
don’t get a silent success; ensure references to APIRecoverVmInstanceMsg,
APIRecoverVmInstanceEvent, validateOperationByState, recoverVm,
getSelfInventory, and thdf.chainSubmit are updated accordingly.
| private void handle(final APIRecoverVmInstanceMsg msg) { | ||
| // | ||
|
|
||
|
|
||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
阻断级问题:APIRecoverVmInstanceMsg handler 为空,可能导致 API 调用无事件返回/超时
当前方法体为空,且没有发布 APIRecoverVmInstanceEvent,调用侧很可能等不到事件。建议直接恢复原逻辑(或至少 publish error/success event)。
建议修复(恢复为可工作的 handler)
private void handle(final APIRecoverVmInstanceMsg msg) {
- //
+ thdf.chainSubmit(new ChainTask(msg) {
+ @Override
+ public String getSyncSignature() {
+ return syncThreadName;
+ }
+
+ @Override
+ public void run(final SyncTaskChain chain) {
+ final APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId());
+ refreshVO();
+
+ ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR);
+ if (error != null) {
+ evt.setError(error);
+ bus.publish(evt);
+ chain.next();
+ return;
+ }
+
+ recoverVm(new Completion(msg, chain) {
+ @Override
+ public void success() {
+ evt.setInventory(getSelfInventory());
+ bus.publish(evt);
+ chain.next();
+ }
+
+ @Override
+ public void fail(ErrorCode errorCode) {
+ evt.setError(errorCode);
+ bus.publish(evt);
+ chain.next();
+ }
+ });
+ }
+
+ @Override
+ public String getName() {
+ return "recover-vm";
+ }
+ });
}🤖 Prompt for AI Agents
In @compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java around lines
9373 - 9377, The handler method VmInstanceBase.handle(APIRecoverVmInstanceMsg
msg) is empty and must publish an APIRecoverVmInstanceEvent so callers get a
response; restore the original recovery flow: create an
APIRecoverVmInstanceEvent for msg.getId(), attempt the VM recovery logic (reuse
the existing recovery code path or invoke the recovery helper used elsewhere),
on success set event.setInventory(...) and publish the event via
bus.publish(event), and on failure catch the exception, log it and publish an
event with error code/event.setError(errCode) or throw a CloudRuntimeException
as your pattern requires; ensure you reference APIRecoverVmInstanceMsg,
APIRecoverVmInstanceEvent and the VmInstanceBase.handle(...) method when
implementing the fix.
3ebc3ec to
4a00f1d
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java`:
- Around line 9462-9464: The current logger.info call in VmInstanceBase that
logs JSONObjectUtil.toJsonString(vmMetadata) along with vms.get(0).getUuid()
exposes potentially sensitive metadata and should be changed: replace the
logger.info(...) usage with a lower level (logger.debug) and/or route through a
sanitizer/truncator before serializing (e.g., build a scrubbed map from
vmMetadata removing or masking fields like paths, uuids, account identifiers and
truncating long strings) and respect a configurable flag to enable full metadata
logging; update references in VmInstanceBase around the recover log (the
JSONObjectUtil.toJsonString(vmMetadata) and logger.info call) to use the
debug-level call and sanitized JSON or gated logging via a config switch.
- Around line 9435-9457: Replace the full-table scans and get(0) usage in
VmInstanceBase where vms, volumes, nics, snapshot, group and groupRef are loaded
into VmMetadata: query each VO by the VM UUID (use msg.getUuid() or the relevant
msg field) and by the proper foreign-key (e.g., VolumeVO.byVmUuid,
VmNicVO.byVmUuid, VolumeSnapshotVO.byVolumeUuid,
VolumeSnapshotGroupRefVO.byGroupUuid) instead of Q.New(...).list() for the
entire table; then check each resulting list for emptiness and return a proper
error event (or throw a controlled error) when required rather than calling
get(0), and build vmMetadata only from the filtered results. Ensure you update
references to vmMetadata.vmInstanceVO, vmMetadata.volumeVO, vmMetadata.vmNicVO
and the volumeSnapshots map population to use the filtered query results and
null/empty guards.
♻️ Duplicate comments (1)
compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java (1)
9397-9464: 阻断:APIRecover 变成空转且未发布事件,调用会超时/语义回归。
当前实现只记录元数据并日志输出,没有发布APIRecoverVmInstanceEvent,也不再走recoverVm,与 API 语义不一致。此问题已在此前 review 中指出,仍未修复。
| List<VmInstanceVO> vms = Q.New(VmInstanceVO.class).list(); | ||
| List<VolumeVO> volumes = Q.New(VolumeVO.class).list(); | ||
| List<VmNicVO> nics = Q.New(VmNicVO.class).list(); | ||
|
|
||
| List<VolumeSnapshotVO> snapshot = Q.New(VolumeSnapshotVO.class).list(); | ||
| List<VolumeSnapshotGroupVO> group = Q.New(VolumeSnapshotGroupVO.class).list(); | ||
| List<VolumeSnapshotGroupRefVO> groupRef = Q.New(VolumeSnapshotGroupRefVO.class).list(); | ||
|
|
||
| VmMetadata vmMetadata = new VmMetadata(); | ||
| vmMetadata.vmInstanceVO = vms.get(0).toString(); | ||
| vmMetadata.volumeVO = volumes.get(0).toString(); | ||
| vmMetadata.vmNicVO = nics.get(0).toString(); | ||
|
|
||
| Map<String, List<String>> volumeSnapshots = new HashMap<>(); | ||
| snapshot.forEach(s -> { | ||
| if (volumeSnapshots.containsKey(s.getVolumeUuid())) { | ||
| volumeSnapshots.get(s.getVolumeUuid()).add(s.toString()); | ||
| } else { | ||
| volumeSnapshots.put(s.getVolumeUuid(), new ArrayList<>()); | ||
| volumeSnapshots.get(s.getVolumeUuid()).add(s.toString()); | ||
| } | ||
| }); | ||
| vmMetadata.volumeSnapshots = volumeSnapshots; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
不要全表扫描并使用 get(0);应按 msg.getUuid() 关联查询并做空结果保护。
这里对 VM/卷/NIC/快照/快照组全表查询,然后取 get(0),容易拿到错误对象,且在空表时直接抛 IndexOutOfBoundsException;同时会造成严重性能/内存开销。建议按 VM UUID 和关联资源过滤,并在找不到时返回错误事件。
💡参考修正(示例)
- List<VmInstanceVO> vms = Q.New(VmInstanceVO.class).list();
- List<VolumeVO> volumes = Q.New(VolumeVO.class).list();
- List<VmNicVO> nics = Q.New(VmNicVO.class).list();
+ VmInstanceVO vm = Q.New(VmInstanceVO.class)
+ .eq(VmInstanceVO_.uuid, msg.getUuid())
+ .find();
+ if (vm == null) {
+ APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId());
+ evt.setError(operr("vm[uuid:%s] not found", msg.getUuid()));
+ bus.publish(evt);
+ return;
+ }
+ List<VolumeVO> volumes = Q.New(VolumeVO.class)
+ .eq(VolumeVO_.vmInstanceUuid, vm.getUuid())
+ .list();
+ List<VmNicVO> nics = Q.New(VmNicVO.class)
+ .eq(VmNicVO_.vmInstanceUuid, vm.getUuid())
+ .list();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| List<VmInstanceVO> vms = Q.New(VmInstanceVO.class).list(); | |
| List<VolumeVO> volumes = Q.New(VolumeVO.class).list(); | |
| List<VmNicVO> nics = Q.New(VmNicVO.class).list(); | |
| List<VolumeSnapshotVO> snapshot = Q.New(VolumeSnapshotVO.class).list(); | |
| List<VolumeSnapshotGroupVO> group = Q.New(VolumeSnapshotGroupVO.class).list(); | |
| List<VolumeSnapshotGroupRefVO> groupRef = Q.New(VolumeSnapshotGroupRefVO.class).list(); | |
| VmMetadata vmMetadata = new VmMetadata(); | |
| vmMetadata.vmInstanceVO = vms.get(0).toString(); | |
| vmMetadata.volumeVO = volumes.get(0).toString(); | |
| vmMetadata.vmNicVO = nics.get(0).toString(); | |
| Map<String, List<String>> volumeSnapshots = new HashMap<>(); | |
| snapshot.forEach(s -> { | |
| if (volumeSnapshots.containsKey(s.getVolumeUuid())) { | |
| volumeSnapshots.get(s.getVolumeUuid()).add(s.toString()); | |
| } else { | |
| volumeSnapshots.put(s.getVolumeUuid(), new ArrayList<>()); | |
| volumeSnapshots.get(s.getVolumeUuid()).add(s.toString()); | |
| } | |
| }); | |
| vmMetadata.volumeSnapshots = volumeSnapshots; | |
| VmInstanceVO vm = Q.New(VmInstanceVO.class) | |
| .eq(VmInstanceVO_.uuid, msg.getUuid()) | |
| .find(); | |
| if (vm == null) { | |
| APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId()); | |
| evt.setError(operr("vm[uuid:%s] not found", msg.getUuid())); | |
| bus.publish(evt); | |
| return; | |
| } | |
| List<VolumeVO> volumes = Q.New(VolumeVO.class) | |
| .eq(VolumeVO_.vmInstanceUuid, vm.getUuid()) | |
| .list(); | |
| List<VmNicVO> nics = Q.New(VmNicVO.class) | |
| .eq(VmNicVO_.vmInstanceUuid, vm.getUuid()) | |
| .list(); | |
| List<VolumeSnapshotVO> snapshot = Q.New(VolumeSnapshotVO.class).list(); | |
| List<VolumeSnapshotGroupVO> group = Q.New(VolumeSnapshotGroupVO.class).list(); | |
| List<VolumeSnapshotGroupRefVO> groupRef = Q.New(VolumeSnapshotGroupRefVO.class).list(); | |
| VmMetadata vmMetadata = new VmMetadata(); | |
| vmMetadata.vmInstanceVO = vm.toString(); | |
| vmMetadata.volumeVO = volumes.get(0).toString(); | |
| vmMetadata.vmNicVO = nics.get(0).toString(); | |
| Map<String, List<String>> volumeSnapshots = new HashMap<>(); | |
| snapshot.forEach(s -> { | |
| if (volumeSnapshots.containsKey(s.getVolumeUuid())) { | |
| volumeSnapshots.get(s.getVolumeUuid()).add(s.toString()); | |
| } else { | |
| volumeSnapshots.put(s.getVolumeUuid(), new ArrayList<>()); | |
| volumeSnapshots.get(s.getVolumeUuid()).add(s.toString()); | |
| } | |
| }); | |
| vmMetadata.volumeSnapshots = volumeSnapshots; |
🤖 Prompt for AI Agents
In `@compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java` around lines
9435 - 9457, Replace the full-table scans and get(0) usage in VmInstanceBase
where vms, volumes, nics, snapshot, group and groupRef are loaded into
VmMetadata: query each VO by the VM UUID (use msg.getUuid() or the relevant msg
field) and by the proper foreign-key (e.g., VolumeVO.byVmUuid, VmNicVO.byVmUuid,
VolumeSnapshotVO.byVolumeUuid, VolumeSnapshotGroupRefVO.byGroupUuid) instead of
Q.New(...).list() for the entire table; then check each resulting list for
emptiness and return a proper error event (or throw a controlled error) when
required rather than calling get(0), and build vmMetadata only from the filtered
results. Ensure you update references to vmMetadata.vmInstanceVO,
vmMetadata.volumeVO, vmMetadata.vmNicVO and the volumeSnapshots map population
to use the filtered query results and null/empty guards.
| String json = JSONObjectUtil.toJsonString(vmMetadata); | ||
| logger.info(String.format("recover vm instance [uuid:%s] with metadata: %s", vms.get(0).getUuid(), json)); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
元数据 JSON 以 info 级别输出存在敏感信息与日志放大风险。
快照/卷等 toString 往往包含路径、uuid、账号等信息,info 级别会污染审计/运维日志并引入合规风险。建议降级为 debug,做字段脱敏/截断或改为可控开关。
🤖 Prompt for AI Agents
In `@compute/src/main/java/org/zstack/compute/vm/VmInstanceBase.java` around lines
9462 - 9464, The current logger.info call in VmInstanceBase that logs
JSONObjectUtil.toJsonString(vmMetadata) along with vms.get(0).getUuid() exposes
potentially sensitive metadata and should be changed: replace the
logger.info(...) usage with a lower level (logger.debug) and/or route through a
sanitizer/truncator before serializing (e.g., build a scrubbed map from
vmMetadata removing or masking fields like paths, uuids, account identifiers and
truncating long strings) and respect a configurable flag to enable full metadata
logging; update references in VmInstanceBase around the recover log (the
JSONObjectUtil.toJsonString(vmMetadata) and logger.info call) to use the
debug-level call and sanitized JSON or gated logging via a config switch.
2821d99 to
ab9be52
Compare
Resolves: ZSV-1 Change-Id: I746a6d7266686d637a6d76756861636a74766b74
ab9be52 to
72ceb84
Compare
Resolves: ZSV-1
Change-Id: I746a6d7266686d637a6d76756861636a74766b74
sync from gitlab !9002