整体架构与 Cargo Workspace
概述
Cube Hypervisor 是一个大型 Rust 项目,采用 Cargo workspace 组织代码。本文深入分析其架构设计和代码组织。
Workspace 结构
根 Cargo.toml
toml
[package]
name = "cube-hypervisor"
version = "28.0.0"
edition = "2021"
default-run = "cube-hypervisor"
[dependencies]
# 核心依赖
vmm = { path = "vmm" }
hypervisor = { path = "hypervisor" }
# 工具依赖
api_client = { path = "api_client" }
event_monitor = { path = "event_monitor" }
event_notifier = { path = "event_notifier" }
logging = { path = "logging" }
tracer = { path = "tracer" }
tpm = { path = "tpm" }
log_json = { path = "log_json" }
option_parser = { path = "option_parser" }
# 第三方依赖
anyhow = "1.0.86"
clap = { version = "4.4.7", features = ["wrap_help", "cargo", "string"] }
serde = { version = "1.0", features = ["rc", "derive"] }
serde_json = "1.0.87"模块依赖关系
核心模块分析
1. cube-hypervisor (主入口)
职责: CLI 解析、VMM 实例封装
rust
// src/main.rs
fn main() {
// 1. 解析命令行参数
let app = create_app();
let matches = app.get_matches();
// 2. 配置日志
setup_logger(&matches);
// 3. 创建 VmmInstance
let vmm_config = parse_config(&matches);
let mut vmm = VmmInstance::new(vmm_config);
// 4. 启动 VMM
vmm.start();
// 5. 处理信号
handle_signals();
}关键文件:
| 文件 | 行数 | 职责 |
|---|---|---|
main.rs | 1832 | CLI 入口、参数解析 |
lib.rs | 359 | VmmInstance 封装 |
vmm_config.rs | 90 | 配置结构 |
common.rs | 258 | 通用工具 |
2. vmm (VMM 核心)
职责: 虚拟机管理、设备管理、内存管理、CPU 管理
rust
// vmm/src/lib.rs
pub struct Vmm {
vm: Option<Vm>,
vm_config: Option<VmConfig>,
api_evt: EventFd,
api_receiver: Receiver<ApiRequest>,
// ...
}
impl Vmm {
pub fn control_loop(&mut self) {
loop {
// 1. 等待 API 请求
let request = self.api_receiver.recv();
// 2. 处理请求
match request {
ApiRequest::VmCreate(config, sender) => {
let result = self.vm_create(config);
sender.send(result);
}
ApiRequest::VmBoot(sender) => {
let result = self.vm_boot();
sender.send(result);
}
// ...
}
}
}
}关键文件:
| 文件 | 行数 | 职责 |
|---|---|---|
vm.rs | 3467 | 虚拟机管理 |
cpu.rs | 2773 | vCPU 管理 |
memory_manager.rs | 2731 | 内存管理 |
device_manager.rs | 5036 | 设备管理 |
config.rs | 3850 | 配置解析 |
vm_config.rs | 655 | 配置结构 |
acpi.rs | 869 | ACPI 表生成 |
migration.rs | 120 | 迁移与快照 |
api/mod.rs | 717 | API 定义 |
api/http.rs | 500+ | HTTP API |
api/service.rs | 300+ | API 服务 |
3. hypervisor (抽象层)
职责: 封装不同 hypervisor 的差异
rust
// hypervisor/src/lib.rs
pub trait Hypervisor: Send + Sync {
fn create_vm(&self) -> Result<Arc<dyn Vm>, HypervisorError>;
fn get_api_version(&self) -> Result<i32, HypervisorError>;
fn get_cpuid(&self) -> Result<Vec<CpuIdEntry>, HypervisorError>;
}
pub trait Vm: Send + Sync {
fn create_vcpu(&self, id: u8) -> Result<Arc<dyn Vcpu>, HypervisorVmError>;
fn set_user_memory_region(&self, ...) -> Result<(), HypervisorVmError>;
}
pub trait Vcpu: Send + Sync {
fn run(&self) -> Result<VmExit, HypervisorCpuError>;
fn set_cpuid2(&self, cpuid: &[CpuIdEntry]) -> Result<(), HypervisorCpuError>;
}实现:
| 实现 | 说明 |
|---|---|
kvm/ | KVM 实现 (Linux) |
mshv/ | MS-HV 实现 (Windows) |
4. virtio-devices (Virtio 设备)
职责: 实现各种 Virtio 设备
rust
// virtio-devices/src/lib.rs
pub trait VirtioDevice: Send {
fn device_type(&self) -> VirtioDeviceType;
fn activate(&mut self, mem: GuestMemoryAtomic, ...) -> ActivateResult;
fn reset(&mut self) -> Result<()>;
fn snapshot(&self) -> Result<Snapshot>;
fn restore(&mut self, snapshot: Snapshot) -> Result<()>;
}设备列表:
| 设备 | 文件 | 说明 |
|---|---|---|
| Block | block.rs | 块设备 |
| Net | net.rs | 网络设备 |
| Fs | fs.rs | 文件系统 |
| Vsock | vsock.rs | Socket 通信 |
| Balloon | balloon.rs | 内存气球 |
| Rng | rng.rs | 随机数 |
| Console | console.rs | 控制台 |
| Iommu | iommu.rs | IOMMU |
| Mem | mem.rs | 内存设备 |
| Pmem | pmem.rs | 持久内存 |
| Vdpa | vdpa.rs | vDPA |
| Watchdog | watchdog.rs | 看门狗 |
5. arch (架构支持)
职责: 架构特定的代码
arch/src/
├── lib.rs # 通用接口
├── x86_64/ # x86_64 特定
│ ├── mod.rs
│ ├── layout.rs # 内存布局
│ ├── regs.rs # 寄存器
│ ├── interrupts.rs # 中断
│ ├── mptable.rs # MP 表
│ ├── smbios.rs # SMBIOS
│ └── cpuid_filter.rs # CPUID 过滤
└── aarch64/ # ARM64 特定
├── mod.rs
├── layout.rs # 内存布局
├── regs.rs # 寄存器
├── fdt.rs # FDT
└── uefi.rs # UEFI代码统计
| 模块 | 文件数 | 代码行数 | 说明 |
|---|---|---|---|
| vmm | 15 | ~20,000 | VMM 核心 |
| virtio-devices | 20 | ~10,000 | Virtio 设备 |
| hypervisor | 8 | ~2,000 | Hypervisor 抽象 |
| arch | 10 | ~3,000 | 架构支持 |
| devices | 8 | ~2,000 | 传统设备 |
| pci | 8 | ~3,000 | PCI 子系统 |
| 其他 | 30+ | ~10,000 | 工具和基础设施 |
| 总计 | 100+ | ~50,000 |
设计模式
1. Trait 抽象
rust
// 使用 trait 抽象底层差异
pub trait Hypervisor { ... }
pub trait Vm { ... }
pub trait Vcpu { ... }
pub trait VirtioDevice { ... }
pub trait BusDevice { ... }
pub trait InterruptManager { ... }2. Builder 模式
rust
// 配置构建
VmConfig::builder()
.cpus(CpusConfig::builder().boot_vcpus(2).build())
.memory(MemoryConfig::builder().size(512 * 1024 * 1024).build())
.build()3. 状态机
rust
// VM 状态机
pub enum VmState {
Created,
Running,
Shutdown,
Paused,
Snapshot,
}4. 事件驱动
rust
// epoll 事件循环
loop {
let events = epoll_wait(epoll_fd, &mut events, timeout)?;
for event in events {
match event.data {
QUEUE_EVENT => { ... }
KILL_EVENT => { ... }
PAUSE_EVENT => { ... }
}
}
}编译与构建
编译命令
bash
# Debug 构建
cargo build
# Release 构建
cargo build --release
# 指定特性
cargo build --features "kvm,mshv"
# 运行测试
cargo test --all特性标志
toml
[features]
default = ["kvm"]
kvm = ["hypervisor/kvm", "vmm/kvm"]
mshv = ["hypervisor/mshv", "vmm/mshv"]
guest_debug = ["vmm/guest_debug"]
tdx = ["vmm/tdx"]