diff --git a/src/cpu-template-helper/src/main.rs b/src/cpu-template-helper/src/main.rs index 35b7ea22d82..19ae70ec423 100644 --- a/src/cpu-template-helper/src/main.rs +++ b/src/cpu-template-helper/src/main.rs @@ -161,7 +161,7 @@ fn run(cli: Cli) -> Result<(), HelperError> { let (vmm, vm_resources) = utils::build_microvm_from_config(config, template)?; let cpu_template = vm_resources - .machine_config + .machine_spec .cpu_template .get_cpu_template()? .into_owned(); diff --git a/src/cpu-template-helper/src/utils/mod.rs b/src/cpu-template-helper/src/utils/mod.rs index f23871df1a9..6323b180a26 100644 --- a/src/cpu-template-helper/src/utils/mod.rs +++ b/src/cpu-template-helper/src/utils/mod.rs @@ -165,7 +165,7 @@ pub fn add_suffix(path: &Path, suffix: &str) -> PathBuf { pub mod tests { use std::fmt::Display; - use vmm::resources::VmmConfig; + use vmm::resources::VmmSpec; use super::*; @@ -217,8 +217,8 @@ pub mod tests { assert!(kernel.as_file().metadata().unwrap().len() > 0); // Ensure the rootfs exists and it is empty. assert_eq!(rootfs.as_file().metadata().unwrap().len(), 0); - // Ensure the generated config is valid as `VmmConfig`. - serde_json::from_str::(&config).unwrap(); + // Ensure the generated config is valid as `VmmSpec`. + serde_json::from_str::(&config).unwrap(); } // Ensure the temporary mock resources are deleted. assert!(!kernel_path.exists()); diff --git a/src/firecracker/src/api_server/parsed_request.rs b/src/firecracker/src/api_server/parsed_request.rs index f98170ccbea..10a249f893b 100644 --- a/src/firecracker/src/api_server/parsed_request.rs +++ b/src/firecracker/src/api_server/parsed_request.rs @@ -84,7 +84,7 @@ impl TryFrom<&Request> for ParsedRequest { (Method::Get, "balloon", None) => parse_get_balloon(path_tokens), (Method::Get, "version", None) => parse_get_version(), (Method::Get, "vm", None) if path_tokens.next() == Some("config") => { - Ok(ParsedRequest::new_sync(VmmAction::GetFullVmConfig)) + Ok(ParsedRequest::new_sync(VmmAction::GetFullVmSpec)) } (Method::Get, "machine-config", None) => parse_get_machine_config(), (Method::Get, "mmds", None) => parse_get_mmds(), @@ -179,12 +179,12 @@ impl ParsedRequest { info!("The request was executed successfully. Status code: 204 No Content."); Response::new(Version::Http11, StatusCode::NoContent) } - VmmData::MachineConfiguration(machine_config) => { - Self::success_response_with_data(machine_config) + VmmData::MachineSpec(machine_spec) => { + Self::success_response_with_data(machine_spec) } VmmData::MmdsValue(value) => Self::success_response_with_mmds_value(value), - VmmData::BalloonConfig(balloon_config) => { - Self::success_response_with_data(balloon_config) + VmmData::BalloonSpec(balloon_spec) => { + Self::success_response_with_data(balloon_spec) } VmmData::BalloonStats(stats) => Self::success_response_with_data(stats), VmmData::VirtioMemStatus(data) => Self::success_response_with_data(data), @@ -195,7 +195,7 @@ impl ParsedRequest { VmmData::VmmVersion(version) => Self::success_response_with_data( &serde_json::json!({ "firecracker_version": version.as_str() }), ), - VmmData::FullVmConfig(config) => Self::success_response_with_data(config), + VmmData::FullVmSpec(vmm_spec) => Self::success_response_with_data(vmm_spec), }, Err(vmm_action_error) => { let mut response = match vmm_action_error { @@ -223,8 +223,19 @@ impl ParsedRequest { } /// Helper function to avoid boiler-plate code. - pub(crate) fn new_sync(vmm_action: VmmAction) -> ParsedRequest { - ParsedRequest::new(RequestAction::Sync(Box::new(vmm_action))) + pub(crate) fn new_sync(vmm_action: T) -> ParsedRequest + where + T: Into, + { + ParsedRequest::new(RequestAction::Sync(Box::new(vmm_action.into()))) + } + + pub(crate) fn new_stateless(entrypoint: F, args: A) -> ParsedRequest + where + F: FnOnce(A) -> VmmAction, + A: vmm::vmm_config::StatelessArgs, + { + ParsedRequest::new_sync(vmm::vmm_config::VmmActionPayload::new(entrypoint, args)) } } @@ -342,11 +353,11 @@ pub mod tests { use vmm::builder::StartMicrovmError; use vmm::cpu_config::templates::test_utils::build_test_template; use vmm::devices::virtio::balloon::device::HintingStatus; - use vmm::resources::VmmConfig; + use vmm::resources::VmmSpec; use vmm::rpc_interface::VmmActionError; - use vmm::vmm_config::balloon::{BalloonDeviceConfig, BalloonStats}; + use vmm::vmm_config::balloon::{BalloonDeviceSpec, BalloonStats}; use vmm::vmm_config::instance_info::InstanceInfo; - use vmm::vmm_config::machine_config::MachineConfig; + use vmm::vmm_config::machine_config::MachineSpec; use super::*; @@ -581,8 +592,8 @@ pub mod tests { let data = Ok(vmm_data); let mut buf = Cursor::new(vec![0]); let expected_response = match data.as_ref().unwrap() { - VmmData::BalloonConfig(cfg) => { - http_response(&serde_json::to_string(cfg).unwrap(), 200) + VmmData::BalloonSpec(spec) => { + http_response(&serde_json::to_string(spec).unwrap(), 200) } VmmData::BalloonStats(stats) => { http_response(&serde_json::to_string(stats).unwrap(), 200) @@ -594,11 +605,11 @@ pub mod tests { http_response(&serde_json::to_string(status).unwrap(), 200) } VmmData::Empty => http_response("", 204), - VmmData::FullVmConfig(cfg) => { - http_response(&serde_json::to_string(cfg).unwrap(), 200) + VmmData::FullVmSpec(spec) => { + http_response(&serde_json::to_string(spec).unwrap(), 200) } - VmmData::MachineConfiguration(cfg) => { - http_response(&serde_json::to_string(cfg).unwrap(), 200) + VmmData::MachineSpec(spec) => { + http_response(&serde_json::to_string(spec).unwrap(), 200) } VmmData::MmdsValue(value) => { http_response(&serde_json::to_string(value).unwrap(), 200) @@ -616,7 +627,7 @@ pub mod tests { assert_eq!(buf.into_inner(), expected_response.as_bytes()); }; - verify_ok_response_with(VmmData::BalloonConfig(BalloonDeviceConfig::default())); + verify_ok_response_with(VmmData::BalloonSpec(BalloonDeviceSpec::default())); verify_ok_response_with(VmmData::BalloonStats(BalloonStats { swap_in: Some(1), swap_out: Some(1), @@ -626,8 +637,8 @@ pub mod tests { ..Default::default() })); verify_ok_response_with(VmmData::Empty); - verify_ok_response_with(VmmData::FullVmConfig(VmmConfig::default())); - verify_ok_response_with(VmmData::MachineConfiguration(MachineConfig::default())); + verify_ok_response_with(VmmData::FullVmSpec(VmmSpec::default())); + verify_ok_response_with(VmmData::MachineSpec(MachineSpec::default())); verify_ok_response_with(VmmData::MmdsValue(serde_json::from_str("{}").unwrap())); verify_ok_response_with(VmmData::InstanceInformation(InstanceInfo::default())); verify_ok_response_with(VmmData::VmmVersion(String::default())); diff --git a/src/firecracker/src/api_server/request/balloon.rs b/src/firecracker/src/api_server/request/balloon.rs index 4093a0e7547..62168552fac 100644 --- a/src/firecracker/src/api_server/request/balloon.rs +++ b/src/firecracker/src/api_server/request/balloon.rs @@ -3,9 +3,7 @@ use micro_http::{Method, StatusCode}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::balloon::{ - BalloonDeviceConfig, BalloonUpdateConfig, BalloonUpdateStatsConfig, -}; +use vmm::vmm_config::balloon::{BalloonDeviceSpec, BalloonUpdateSpec, BalloonUpdateStatsSpec}; use super::super::parsed_request::{ParsedRequest, RequestError}; use super::Body; @@ -39,14 +37,15 @@ where StatusCode::BadRequest, format!("Unrecognized GET request path `{}`.", stats_path), )), - None => Ok(ParsedRequest::new_sync(VmmAction::GetBalloonConfig)), + None => Ok(ParsedRequest::new_sync(VmmAction::GetBalloonSpec)), } } pub(crate) fn parse_put_balloon(body: &Body) -> Result { - Ok(ParsedRequest::new_sync(VmmAction::SetBalloonDevice( - serde_json::from_slice::(body.raw())?, - ))) + Ok(ParsedRequest::new_stateless( + VmmAction::SetBalloonDevice, + serde_json::from_slice::(body.raw())?, + )) } fn parse_patch_hinting<'a, T>( @@ -64,9 +63,10 @@ where Some(b) => serde_json::from_slice(b.raw())?, }; - Ok(ParsedRequest::new_sync(VmmAction::StartFreePageHinting( + Ok(ParsedRequest::new_stateless( + VmmAction::StartFreePageHinting, cmd, - ))) + )) } Some("stop") => Ok(ParsedRequest::new_sync(VmmAction::StopFreePageHinting)), Some(stats_path) => Err(RequestError::Generic( @@ -88,15 +88,15 @@ where T: Iterator, { match (path_tokens.next(), body) { - (Some("statistics"), Some(body)) => { - Ok(ParsedRequest::new_sync(VmmAction::UpdateBalloonStatistics( - serde_json::from_slice::(body.raw())?, - ))) - } + (Some("statistics"), Some(body)) => Ok(ParsedRequest::new_stateless( + VmmAction::UpdateBalloonStatistics, + serde_json::from_slice::(body.raw())?, + )), (Some("hinting"), body) => parse_patch_hinting(body, path_tokens), - (_, Some(body)) => Ok(ParsedRequest::new_sync(VmmAction::UpdateBalloon( - serde_json::from_slice::(body.raw())?, - ))), + (_, Some(body)) => Ok(ParsedRequest::new_stateless( + VmmAction::UpdateBalloon, + serde_json::from_slice::(body.raw())?, + )), (_, None) => method_to_error(Method::Patch), } } @@ -183,25 +183,25 @@ mod tests { let body = r#"{ "amount_mib": 1 }"#; - let expected_config = BalloonUpdateConfig { amount_mib: 1 }; + let expected_spec = BalloonUpdateSpec { amount_mib: 1 }; assert_eq!( vmm_action_from_request( parse_patch_balloon(Some(&Body::new(body)), [].into_iter()).unwrap() ), - VmmAction::UpdateBalloon(expected_config) + VmmAction::UpdateBalloon(expected_spec) ); let body = r#"{ "stats_polling_interval_s": 1 }"#; - let expected_config = BalloonUpdateStatsConfig { + let expected_spec = BalloonUpdateStatsSpec { stats_polling_interval_s: 1, }; assert_eq!( vmm_action_from_request( parse_patch_balloon(Some(&Body::new(body)), ["statistics"].into_iter()).unwrap() ), - VmmAction::UpdateBalloonStatistics(expected_config) + VmmAction::UpdateBalloonStatistics(expected_spec) ); // PATCH start hinting run valid data diff --git a/src/firecracker/src/api_server/request/boot_source.rs b/src/firecracker/src/api_server/request/boot_source.rs index 10e16148461..122c1997f19 100644 --- a/src/firecracker/src/api_server/request/boot_source.rs +++ b/src/firecracker/src/api_server/request/boot_source.rs @@ -3,18 +3,19 @@ use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::boot_source::BootSourceConfig; +use vmm::vmm_config::boot_source::BootSourceSpec; use super::super::parsed_request::{ParsedRequest, RequestError}; use super::Body; pub(crate) fn parse_put_boot_source(body: &Body) -> Result { METRICS.put_api_requests.boot_source_count.inc(); - Ok(ParsedRequest::new_sync(VmmAction::ConfigureBootSource( - serde_json::from_slice::(body.raw()).inspect_err(|_| { + Ok(ParsedRequest::new_stateless( + VmmAction::ConfigureBootSource, + serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.boot_source_fails.inc(); })?, - ))) + )) } #[cfg(test)] @@ -30,7 +31,7 @@ mod tests { "initrd_path": "/bar/foo", "boot_args": "foobar" }"#; - let same_body = BootSourceConfig { + let same_body = BootSourceSpec { kernel_image_path: String::from("/foo/bar"), initrd_path: Some(String::from("/bar/foo")), boot_args: Some(String::from("foobar")), diff --git a/src/firecracker/src/api_server/request/cpu_configuration.rs b/src/firecracker/src/api_server/request/cpu_configuration.rs index 454df80be4b..26c3e9f5868 100644 --- a/src/firecracker/src/api_server/request/cpu_configuration.rs +++ b/src/firecracker/src/api_server/request/cpu_configuration.rs @@ -12,12 +12,13 @@ pub(crate) fn parse_put_cpu_config(body: &Body) -> Result(body.raw()).inspect_err(|_| { + let device_spec = serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.drive_fails.inc(); })?; - if id != device_cfg.drive_id { + if id != device_spec.drive_id { METRICS.put_api_requests.drive_fails.inc(); Err(RequestError::Generic( StatusCode::BadRequest, "The id from the path does not match the id from the body!".to_string(), )) } else { - Ok(ParsedRequest::new_sync(VmmAction::InsertBlockDevice( - device_cfg, - ))) + Ok(ParsedRequest::new_stateless( + VmmAction::InsertBlockDevice, + device_spec, + )) } } @@ -49,12 +50,12 @@ pub(crate) fn parse_patch_drive( return Err(RequestError::EmptyID); }; - let block_device_update_cfg: BlockDeviceUpdateConfig = - serde_json::from_slice::(body.raw()).inspect_err(|_| { + let block_device_update_spec: BlockDeviceUpdateSpec = + serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.patch_api_requests.drive_fails.inc(); })?; - if id != block_device_update_cfg.drive_id { + if id != block_device_update_spec.drive_id { METRICS.patch_api_requests.drive_fails.inc(); return Err(RequestError::Generic( StatusCode::BadRequest, @@ -62,9 +63,10 @@ pub(crate) fn parse_patch_drive( )); } - Ok(ParsedRequest::new_sync(VmmAction::UpdateBlockDevice( - block_device_update_cfg, - ))) + Ok(ParsedRequest::new_stateless( + VmmAction::UpdateBlockDevice, + block_device_update_spec, + )) } #[cfg(test)] @@ -133,14 +135,14 @@ mod tests { "drive_id": "foo", "path_on_host": "dummy" }"#; - let expected_config = BlockDeviceUpdateConfig { + let expected_spec = BlockDeviceUpdateSpec { drive_id: "foo".to_string(), path_on_host: Some("dummy".to_string()), rate_limiter: None, }; assert_eq!( vmm_action_from_request(parse_patch_drive(&Body::new(body), Some("foo")).unwrap()), - VmmAction::UpdateBlockDevice(expected_config) + VmmAction::UpdateBlockDevice(expected_spec) ); let body = r#"{ diff --git a/src/firecracker/src/api_server/request/entropy.rs b/src/firecracker/src/api_server/request/entropy.rs index 4c360265506..1c51c95438b 100644 --- a/src/firecracker/src/api_server/request/entropy.rs +++ b/src/firecracker/src/api_server/request/entropy.rs @@ -2,14 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::entropy::EntropyDeviceConfig; +use vmm::vmm_config::entropy::EntropyDeviceSpec; use super::super::parsed_request::{ParsedRequest, RequestError}; use super::Body; pub(crate) fn parse_put_entropy(body: &Body) -> Result { - let cfg = serde_json::from_slice::(body.raw())?; - Ok(ParsedRequest::new_sync(VmmAction::SetEntropyDevice(cfg))) + let spec = serde_json::from_slice::(body.raw())?; + Ok(ParsedRequest::new_stateless( + VmmAction::SetEntropyDevice, + spec, + )) } #[cfg(test)] diff --git a/src/firecracker/src/api_server/request/hotplug/memory.rs b/src/firecracker/src/api_server/request/hotplug/memory.rs index 5ec514ca964..77172a0f659 100644 --- a/src/firecracker/src/api_server/request/hotplug/memory.rs +++ b/src/firecracker/src/api_server/request/hotplug/memory.rs @@ -4,18 +4,19 @@ use micro_http::Body; use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::memory_hotplug::{MemoryHotplugConfig, MemoryHotplugSizeUpdate}; +use vmm::vmm_config::memory_hotplug::{MemoryHotplugSizeUpdate, MemoryHotplugSpec}; use crate::api_server::parsed_request::{ParsedRequest, RequestError}; pub(crate) fn parse_put_memory_hotplug(body: &Body) -> Result { METRICS.put_api_requests.hotplug_memory_count.inc(); - let config = serde_json::from_slice::(body.raw()).inspect_err(|_| { + let spec = serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.hotplug_memory_fails.inc(); })?; - Ok(ParsedRequest::new_sync(VmmAction::SetMemoryHotplugDevice( - config, - ))) + Ok(ParsedRequest::new_stateless( + VmmAction::SetMemoryHotplugDevice, + spec, + )) } pub(crate) fn parse_get_memory_hotplug() -> Result { @@ -29,9 +30,10 @@ pub(crate) fn parse_patch_memory_hotplug(body: &Body) -> Result(body.raw()).inspect_err(|_| { METRICS.patch_api_requests.hotplug_memory_fails.inc(); })?; - Ok(ParsedRequest::new_sync(VmmAction::UpdateMemoryHotplugSize( + Ok(ParsedRequest::new_stateless( + VmmAction::UpdateMemoryHotplugSize, config, - ))) + )) } #[cfg(test)] @@ -58,14 +60,14 @@ mod tests { let body = r#"{ "total_size_mib": 2048 }"#; - let expected_config = MemoryHotplugConfig { + let expected_spec = MemoryHotplugSpec { total_size_mib: 2048, block_size_mib: VIRTIO_MEM_DEFAULT_BLOCK_SIZE_MIB, slot_size_mib: VIRTIO_MEM_DEFAULT_SLOT_SIZE_MIB, }; assert_eq!( vmm_action_from_request(parse_put_memory_hotplug(&Body::new(body)).unwrap()), - VmmAction::SetMemoryHotplugDevice(expected_config) + VmmAction::SetMemoryHotplugDevice(expected_spec) ); // PUT with valid input fields. @@ -74,14 +76,14 @@ mod tests { "block_size_mib": 64, "slot_size_mib": 64 }"#; - let expected_config = MemoryHotplugConfig { + let expected_spec = MemoryHotplugSpec { total_size_mib: 2048, block_size_mib: 64, slot_size_mib: 64, }; assert_eq!( vmm_action_from_request(parse_put_memory_hotplug(&Body::new(body)).unwrap()), - VmmAction::SetMemoryHotplugDevice(expected_config) + VmmAction::SetMemoryHotplugDevice(expected_spec) ); } diff --git a/src/firecracker/src/api_server/request/logger.rs b/src/firecracker/src/api_server/request/logger.rs index cda125ac71c..5df9cf7ee1e 100644 --- a/src/firecracker/src/api_server/request/logger.rs +++ b/src/firecracker/src/api_server/request/logger.rs @@ -13,7 +13,10 @@ pub(crate) fn parse_put_logger(body: &Body) -> Result Result { METRICS.get_api_requests.machine_cfg_count.inc(); - Ok(ParsedRequest::new_sync(VmmAction::GetVmMachineConfig)) + Ok(ParsedRequest::new_sync(VmmAction::GetVmMachineSpec)) } pub(crate) fn parse_put_machine_config(body: &Body) -> Result { METRICS.put_api_requests.machine_cfg_count.inc(); - let config = serde_json::from_slice::(body.raw()).inspect_err(|_| { + let spec = serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.machine_cfg_fails.inc(); })?; // Check for the presence of deprecated `cpu_template` field. let mut deprecation_message = None; - if config.cpu_template.is_some() { + if spec.cpu_template.is_some() { // `cpu_template` field in request is deprecated. METRICS.deprecated_api.deprecated_http_api_calls.inc(); deprecation_message = Some("PUT /machine-config: cpu_template field is deprecated."); } - // Convert `MachineConfig` to `MachineConfigUpdate`. - let config_update = MachineConfigUpdate::from(config); + // Convert `MachineSpec` to `MachineSpecUpdate`. + let spec_update = MachineSpecUpdate::from(spec); // Construct the `ParsedRequest` object. - let mut parsed_req = - ParsedRequest::new_sync(VmmAction::UpdateMachineConfiguration(config_update)); + let mut parsed_req = ParsedRequest::new_stateless(VmmAction::UpdateMachineSpec, spec_update); // If `cpu_template` was present, set the deprecation message in `parsing_info`. if let Some(msg) = deprecation_message { parsed_req.parsing_info().append_deprecation_message(msg); @@ -43,26 +42,25 @@ pub(crate) fn parse_put_machine_config(body: &Body) -> Result Result { METRICS.patch_api_requests.machine_cfg_count.inc(); - let config_update = - serde_json::from_slice::(body.raw()).inspect_err(|_| { + let spec_update = + serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.patch_api_requests.machine_cfg_fails.inc(); })?; - if config_update.is_empty() { + if spec_update.is_empty() { return method_to_error(Method::Patch); } // Check for the presence of deprecated `cpu_template` field. let mut deprecation_message = None; - if config_update.cpu_template.is_some() { + if spec_update.cpu_template.is_some() { // `cpu_template` field in request is deprecated. METRICS.deprecated_api.deprecated_http_api_calls.inc(); deprecation_message = Some("PATCH /machine-config: cpu_template field is deprecated."); } // Construct the `ParsedRequest` object. - let mut parsed_req = - ParsedRequest::new_sync(VmmAction::UpdateMachineConfiguration(config_update)); + let mut parsed_req = ParsedRequest::new_stateless(VmmAction::UpdateMachineSpec, spec_update); // If `cpu_template` was present, set the deprecation message in `parsing_info`. if let Some(msg) = deprecation_message { parsed_req.parsing_info().append_deprecation_message(msg); @@ -116,7 +114,7 @@ mod tests { "huge_pages": "{huge_page}" }}"# ); - let expected_config = MachineConfigUpdate { + let expected_spec_update = MachineSpecUpdate { vcpu_count: Some(8), mem_size_mib: Some(1024), smt: Some(false), @@ -128,7 +126,7 @@ mod tests { }; assert_eq!( vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()), - VmmAction::UpdateMachineConfiguration(expected_config) + VmmAction::UpdateMachineSpec(expected_spec_update) ); } @@ -137,7 +135,7 @@ mod tests { "mem_size_mib": 1024, "cpu_template": "None" }"#; - let expected_config = MachineConfigUpdate { + let expected_spec_update = MachineSpecUpdate { vcpu_count: Some(8), mem_size_mib: Some(1024), smt: Some(false), @@ -149,7 +147,7 @@ mod tests { }; assert_eq!( vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()), - VmmAction::UpdateMachineConfiguration(expected_config) + VmmAction::UpdateMachineSpec(expected_spec_update) ); let body = r#"{ @@ -158,7 +156,7 @@ mod tests { "smt": false, "track_dirty_pages": true }"#; - let expected_config = MachineConfigUpdate { + let expected_spec_update = MachineSpecUpdate { vcpu_count: Some(8), mem_size_mib: Some(1024), smt: Some(false), @@ -170,7 +168,7 @@ mod tests { }; assert_eq!( vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()), - VmmAction::UpdateMachineConfiguration(expected_config) + VmmAction::UpdateMachineSpec(expected_spec_update) ); // 4. Test that applying a CPU template is successful on x86_64 while on aarch64, it is not. @@ -183,7 +181,7 @@ mod tests { }"#; #[cfg(target_arch = "x86_64")] { - let expected_config = MachineConfigUpdate { + let expected_spec_update = MachineSpecUpdate { vcpu_count: Some(8), mem_size_mib: Some(1024), smt: Some(false), @@ -195,7 +193,7 @@ mod tests { }; assert_eq!( vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()), - VmmAction::UpdateMachineConfiguration(expected_config) + VmmAction::UpdateMachineSpec(expected_spec_update) ); } #[cfg(target_arch = "aarch64")] @@ -210,7 +208,7 @@ mod tests { "smt": true, "track_dirty_pages": true }"#; - let expected_config = MachineConfigUpdate { + let expected_spec_update = MachineSpecUpdate { vcpu_count: Some(8), mem_size_mib: Some(1024), smt: Some(true), @@ -222,7 +220,7 @@ mod tests { }; assert_eq!( vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()), - VmmAction::UpdateMachineConfiguration(expected_config) + VmmAction::UpdateMachineSpec(expected_spec_update) ); // 6. Test nonsense values for huge page size diff --git a/src/firecracker/src/api_server/request/metrics.rs b/src/firecracker/src/api_server/request/metrics.rs index 054ece19422..769f217aa29 100644 --- a/src/firecracker/src/api_server/request/metrics.rs +++ b/src/firecracker/src/api_server/request/metrics.rs @@ -3,18 +3,19 @@ use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::metrics::MetricsConfig; +use vmm::vmm_config::metrics::MetricsSpec; use super::super::parsed_request::{ParsedRequest, RequestError}; use super::Body; pub(crate) fn parse_put_metrics(body: &Body) -> Result { METRICS.put_api_requests.metrics_count.inc(); - Ok(ParsedRequest::new_sync(VmmAction::ConfigureMetrics( - serde_json::from_slice::(body.raw()).inspect_err(|_| { + Ok(ParsedRequest::new_stateless( + VmmAction::ConfigureMetrics, + serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.metrics_fails.inc(); })?, - ))) + )) } #[cfg(test)] @@ -29,12 +30,12 @@ mod tests { let body = r#"{ "metrics_path": "metrics" }"#; - let expected_config = MetricsConfig { + let expected_spec = MetricsSpec { metrics_path: PathBuf::from("metrics"), }; assert_eq!( vmm_action_from_request(parse_put_metrics(&Body::new(body)).unwrap()), - VmmAction::ConfigureMetrics(expected_config) + VmmAction::ConfigureMetrics(expected_spec) ); let invalid_body = r#"{ diff --git a/src/firecracker/src/api_server/request/mmds.rs b/src/firecracker/src/api_server/request/mmds.rs index 2bc96512d3c..f038a2844c7 100644 --- a/src/firecracker/src/api_server/request/mmds.rs +++ b/src/firecracker/src/api_server/request/mmds.rs @@ -5,7 +5,7 @@ use micro_http::StatusCode; use vmm::logger::{IncMetric, METRICS}; use vmm::mmds::data_store::MmdsVersion; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::mmds::MmdsConfig; +use vmm::vmm_config::mmds::MmdsSpec; use super::super::parsed_request::{ParsedRequest, RequestError}; use super::Body; @@ -16,12 +16,12 @@ pub(crate) fn parse_get_mmds() -> Result { } fn parse_put_mmds_config(body: &Body) -> Result { - let config: MmdsConfig = serde_json::from_slice(body.raw()).inspect_err(|_| { + let spec: MmdsSpec = serde_json::from_slice(body.raw()).inspect_err(|_| { METRICS.put_api_requests.mmds_fails.inc(); })?; // Construct the `ParsedRequest` object. - let version = config.version; - let mut parsed_request = ParsedRequest::new_sync(VmmAction::SetMmdsConfiguration(config)); + let version = spec.version; + let mut parsed_request = ParsedRequest::new_stateless(VmmAction::SetMmdsSpec, spec); // MmdsV1 is deprecated. if version == MmdsVersion::V1 { @@ -40,11 +40,12 @@ pub(crate) fn parse_put_mmds( ) -> Result { METRICS.put_api_requests.mmds_count.inc(); match path_second_token { - None => Ok(ParsedRequest::new_sync(VmmAction::PutMMDS( + None => Ok(ParsedRequest::new_stateless( + VmmAction::PutMMDS, serde_json::from_slice(body.raw()).inspect_err(|_| { METRICS.put_api_requests.mmds_fails.inc(); })?, - ))), + )), Some("config") => parse_put_mmds_config(body), Some(unrecognized) => { METRICS.put_api_requests.mmds_fails.inc(); @@ -58,11 +59,12 @@ pub(crate) fn parse_put_mmds( pub(crate) fn parse_patch_mmds(body: &Body) -> Result { METRICS.patch_api_requests.mmds_count.inc(); - Ok(ParsedRequest::new_sync(VmmAction::PatchMMDS( + Ok(ParsedRequest::new_stateless( + VmmAction::PatchMMDS, serde_json::from_slice(body.raw()).inspect_err(|_| { METRICS.patch_api_requests.mmds_fails.inc(); })?, - ))) + )) } #[cfg(test)] diff --git a/src/firecracker/src/api_server/request/net.rs b/src/firecracker/src/api_server/request/net.rs index a0125add274..7779cb23d5a 100644 --- a/src/firecracker/src/api_server/request/net.rs +++ b/src/firecracker/src/api_server/request/net.rs @@ -3,7 +3,7 @@ use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::net::{NetworkInterfaceConfig, NetworkInterfaceUpdateConfig}; +use vmm::vmm_config::net::{NetworkInterfaceSpec, NetworkInterfaceUpdateSpec}; use super::super::parsed_request::{ParsedRequest, RequestError, checked_id}; use super::{Body, StatusCode}; @@ -20,7 +20,7 @@ pub(crate) fn parse_put_net( return Err(RequestError::EmptyID); }; - let netif = serde_json::from_slice::(body.raw()).inspect_err(|_| { + let netif = serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.network_fails.inc(); })?; if id != netif.iface_id.as_str() { @@ -34,9 +34,10 @@ pub(crate) fn parse_put_net( ), )); } - Ok(ParsedRequest::new_sync(VmmAction::InsertNetworkDevice( + Ok(ParsedRequest::new_stateless( + VmmAction::InsertNetworkDevice, netif, - ))) + )) } pub(crate) fn parse_patch_net( @@ -52,7 +53,7 @@ pub(crate) fn parse_patch_net( }; let netif = - serde_json::from_slice::(body.raw()).inspect_err(|_| { + serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.patch_api_requests.network_fails.inc(); })?; if id != netif.iface_id { @@ -66,9 +67,10 @@ pub(crate) fn parse_patch_net( ), )); } - Ok(ParsedRequest::new_sync(VmmAction::UpdateNetworkInterface( + Ok(ParsedRequest::new_stateless( + VmmAction::UpdateNetworkInterface, netif, - ))) + )) } #[cfg(test)] @@ -89,10 +91,10 @@ mod tests { parse_put_net(&Body::new(body), None).unwrap_err(); // 3. Success case. - let expected_config = serde_json::from_str::(body).unwrap(); + let expected_spec = serde_json::from_str::(body).unwrap(); assert_eq!( vmm_action_from_request(parse_put_net(&Body::new(body), Some("foo")).unwrap()), - VmmAction::InsertNetworkDevice(expected_config) + VmmAction::InsertNetworkDevice(expected_spec) ); // 4. Serde error for invalid field (bytes instead of bandwidth). @@ -127,10 +129,10 @@ mod tests { parse_patch_net(&Body::new(body), None).unwrap_err(); // 3. Success case. - let expected_config = serde_json::from_str::(body).unwrap(); + let expected_spec = serde_json::from_str::(body).unwrap(); assert_eq!( vmm_action_from_request(parse_patch_net(&Body::new(body), Some("foo")).unwrap()), - VmmAction::UpdateNetworkInterface(expected_config) + VmmAction::UpdateNetworkInterface(expected_spec) ); // 4. Serde error for invalid field (bytes instead of bandwidth). diff --git a/src/firecracker/src/api_server/request/pmem.rs b/src/firecracker/src/api_server/request/pmem.rs index dc538a0d5fc..25bfb65acca 100644 --- a/src/firecracker/src/api_server/request/pmem.rs +++ b/src/firecracker/src/api_server/request/pmem.rs @@ -3,7 +3,7 @@ use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::pmem::PmemConfig; +use vmm::vmm_config::pmem::PmemSpec; use super::super::parsed_request::{ParsedRequest, RequestError, checked_id}; use super::{Body, StatusCode}; @@ -20,20 +20,21 @@ pub(crate) fn parse_put_pmem( return Err(RequestError::EmptyID); }; - let device_cfg = serde_json::from_slice::(body.raw()).inspect_err(|_| { + let device_spec = serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.pmem_fails.inc(); })?; - if id != device_cfg.id { + if id != device_spec.id { METRICS.put_api_requests.pmem_fails.inc(); Err(RequestError::Generic( StatusCode::BadRequest, "The id from the path does not match the id from the body!".to_string(), )) } else { - Ok(ParsedRequest::new_sync(VmmAction::InsertPmemDevice( - device_cfg, - ))) + Ok(ParsedRequest::new_stateless( + VmmAction::InsertPmemDevice, + device_spec, + )) } } @@ -64,12 +65,12 @@ mod tests { }"#; let r = vmm_action_from_request(parse_put_pmem(&Body::new(body), Some("1000")).unwrap()); - let expected_config = PmemConfig { + let expected_spec = PmemSpec { id: "1000".to_string(), path_on_host: "dummy".to_string(), root_device: true, read_only: true, }; - assert_eq!(r, VmmAction::InsertPmemDevice(expected_config)); + assert_eq!(r, VmmAction::InsertPmemDevice(expected_spec)); } } diff --git a/src/firecracker/src/api_server/request/serial.rs b/src/firecracker/src/api_server/request/serial.rs index a75895cece2..929f7f05786 100644 --- a/src/firecracker/src/api_server/request/serial.rs +++ b/src/firecracker/src/api_server/request/serial.rs @@ -4,17 +4,20 @@ use micro_http::Body; use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::serial::SerialConfig; +use vmm::vmm_config::serial::SerialSpec; use crate::api_server::parsed_request::{ParsedRequest, RequestError}; pub(crate) fn parse_put_serial(body: &Body) -> Result { METRICS.put_api_requests.serial_count.inc(); - let res = serde_json::from_slice::(body.raw()); - let config = res.inspect_err(|_| { + let res = serde_json::from_slice::(body.raw()); + let spec = res.inspect_err(|_| { METRICS.put_api_requests.serial_fails.inc(); })?; - Ok(ParsedRequest::new_sync(VmmAction::ConfigureSerial(config))) + Ok(ParsedRequest::new_stateless( + VmmAction::ConfigureSerial, + spec, + )) } #[cfg(test)] @@ -28,12 +31,12 @@ mod tests { fn test_parse_put_serial_request() { let body = r#"{"serial_out_path": "serial"}"#; - let expected_config = SerialConfig { + let expected_spec = SerialSpec { serial_out_path: Some(PathBuf::from("serial")), }; assert_eq!( vmm_action_from_request(parse_put_serial(&Body::new(body)).unwrap()), - VmmAction::ConfigureSerial(expected_config) + VmmAction::ConfigureSerial(expected_spec) ); } } diff --git a/src/firecracker/src/api_server/request/snapshot.rs b/src/firecracker/src/api_server/request/snapshot.rs index 8284aa66287..52cb9a6cca0 100644 --- a/src/firecracker/src/api_server/request/snapshot.rs +++ b/src/firecracker/src/api_server/request/snapshot.rs @@ -5,8 +5,8 @@ use serde::de::Error as DeserializeError; use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; use vmm::vmm_config::snapshot::{ - CreateSnapshotParams, LoadSnapshotConfig, LoadSnapshotParams, MemBackendConfig, MemBackendType, - Vm, VmState, + CreateSnapshotParams, LoadSnapshotParams, LoadSnapshotSpec, MemBackendSpec, MemBackendType, Vm, + VmState, }; use super::super::parsed_request::{ParsedRequest, RequestError}; @@ -53,16 +53,17 @@ pub(crate) fn parse_patch_vm_state(body: &Body) -> Result Result { - let snapshot_config = serde_json::from_slice::(body.raw())?; - Ok(ParsedRequest::new_sync(VmmAction::CreateSnapshot( - snapshot_config, - ))) + let snapshot_params = serde_json::from_slice::(body.raw())?; + Ok(ParsedRequest::new_stateless( + VmmAction::CreateSnapshot, + snapshot_params, + )) } fn parse_put_snapshot_load(body: &Body) -> Result { - let snapshot_config = serde_json::from_slice::(body.raw())?; + let snapshot_spec = serde_json::from_slice::(body.raw())?; - match (&snapshot_config.mem_backend, &snapshot_config.mem_file_path) { + match (&snapshot_spec.mem_backend, &snapshot_spec.mem_file_path) { // Ensure `mem_file_path` and `mem_backend` fields are not present at the same time. (Some(_), Some(_)) => { return Err(RequestError::SerdeJson(serde_json::Error::custom( @@ -82,38 +83,37 @@ fn parse_put_snapshot_load(body: &Body) -> Result { // deprecation message if found. let mut deprecation_message = None; #[allow(deprecated)] - if snapshot_config.mem_file_path.is_some() || snapshot_config.enable_diff_snapshots { + if snapshot_spec.mem_file_path.is_some() || snapshot_spec.enable_diff_snapshots { // `mem_file_path` field in request is deprecated. METRICS.deprecated_api.deprecated_http_api_calls.inc(); deprecation_message = Some(LOAD_DEPRECATION_MESSAGE); } // If `mem_file_path` is specified instead of `mem_backend`, we construct the - // `MemBackendConfig` object from the path specified, with `File` as backend type. - let mem_backend = match snapshot_config.mem_backend { - Some(backend_cfg) => backend_cfg, + // `MemBackendSpec` object from the path specified, with `File` as backend type. + let mem_backend = match snapshot_spec.mem_backend { + Some(backend_spec) => backend_spec, None => { - MemBackendConfig { + MemBackendSpec { // This is safe to unwrap() because we ensure above that one of the two: // either `mem_file_path` or `mem_backend` field is always specified. - backend_path: snapshot_config.mem_file_path.unwrap(), + backend_path: snapshot_spec.mem_file_path.unwrap(), backend_type: MemBackendType::File, } } }; let snapshot_params = LoadSnapshotParams { - snapshot_path: snapshot_config.snapshot_path, + snapshot_path: snapshot_spec.snapshot_path, mem_backend, #[allow(deprecated)] - track_dirty_pages: snapshot_config.enable_diff_snapshots - || snapshot_config.track_dirty_pages, - resume_vm: snapshot_config.resume_vm, - network_overrides: snapshot_config.network_overrides, + track_dirty_pages: snapshot_spec.enable_diff_snapshots || snapshot_spec.track_dirty_pages, + resume_vm: snapshot_spec.resume_vm, + network_overrides: snapshot_spec.network_overrides, }; // Construct the `ParsedRequest` object. - let mut parsed_req = ParsedRequest::new_sync(VmmAction::LoadSnapshot(snapshot_params)); + let mut parsed_req = ParsedRequest::new_stateless(VmmAction::LoadSnapshot, snapshot_params); // If `mem_file_path` was present, set the deprecation message in `parsing_info`. if let Some(msg) = deprecation_message { @@ -125,7 +125,7 @@ fn parse_put_snapshot_load(body: &Body) -> Result { #[cfg(test)] mod tests { - use vmm::vmm_config::snapshot::{MemBackendConfig, MemBackendType, NetworkOverride}; + use vmm::vmm_config::snapshot::{MemBackendSpec, MemBackendType, NetworkOverride}; use super::*; use crate::api_server::parsed_request::tests::{depr_action_from_req, vmm_action_from_request}; @@ -180,7 +180,7 @@ mod tests { }"#; let expected_config = LoadSnapshotParams { snapshot_path: PathBuf::from("foo"), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: PathBuf::from("bar"), backend_type: MemBackendType::File, }, @@ -210,7 +210,7 @@ mod tests { }"#; let expected_config = LoadSnapshotParams { snapshot_path: PathBuf::from("foo"), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: PathBuf::from("bar"), backend_type: MemBackendType::File, }, @@ -240,7 +240,7 @@ mod tests { }"#; let expected_config = LoadSnapshotParams { snapshot_path: PathBuf::from("foo"), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: PathBuf::from("bar"), backend_type: MemBackendType::Uffd, }, @@ -276,7 +276,7 @@ mod tests { }"#; let expected_config = LoadSnapshotParams { snapshot_path: PathBuf::from("foo"), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: PathBuf::from("bar"), backend_type: MemBackendType::Uffd, }, @@ -306,7 +306,7 @@ mod tests { }"#; let expected_config = LoadSnapshotParams { snapshot_path: PathBuf::from("foo"), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: PathBuf::from("bar"), backend_type: MemBackendType::File, }, diff --git a/src/firecracker/src/api_server/request/vsock.rs b/src/firecracker/src/api_server/request/vsock.rs index acf129d456c..4f9a7a599bc 100644 --- a/src/firecracker/src/api_server/request/vsock.rs +++ b/src/firecracker/src/api_server/request/vsock.rs @@ -3,27 +3,27 @@ use vmm::logger::{IncMetric, METRICS}; use vmm::rpc_interface::VmmAction; -use vmm::vmm_config::vsock::VsockDeviceConfig; +use vmm::vmm_config::vsock::VsockDeviceSpec; use super::super::parsed_request::{ParsedRequest, RequestError}; use super::Body; pub(crate) fn parse_put_vsock(body: &Body) -> Result { METRICS.put_api_requests.vsock_count.inc(); - let vsock_cfg = serde_json::from_slice::(body.raw()).inspect_err(|_| { + let vsock_spec = serde_json::from_slice::(body.raw()).inspect_err(|_| { METRICS.put_api_requests.vsock_fails.inc(); })?; // Check for the presence of deprecated `vsock_id` field. let mut deprecation_message = None; - if vsock_cfg.vsock_id.is_some() { + if vsock_spec.vsock_id.is_some() { // vsock_id field in request is deprecated. METRICS.deprecated_api.deprecated_http_api_calls.inc(); deprecation_message = Some("PUT /vsock: vsock_id field is deprecated."); } // Construct the `ParsedRequest` object. - let mut parsed_req = ParsedRequest::new_sync(VmmAction::SetVsockDevice(vsock_cfg)); + let mut parsed_req = ParsedRequest::new_stateless(VmmAction::SetVsockDevice, vsock_spec); // If `vsock_id` was present, set the deprecation message in `parsing_info`. if let Some(msg) = deprecation_message { parsed_req.parsing_info().append_deprecation_message(msg); diff --git a/src/firecracker/src/main.rs b/src/firecracker/src/main.rs index 739214999a4..44440b6e8c9 100644 --- a/src/firecracker/src/main.rs +++ b/src/firecracker/src/main.rs @@ -30,7 +30,7 @@ use vmm::seccomp::BpfThreadMap; use vmm::signal_handler::register_signal_handlers; use vmm::snapshot::{SnapshotError, get_format_version}; use vmm::vmm_config::instance_info::{InstanceInfo, VmState}; -use vmm::vmm_config::metrics::{MetricsConfig, MetricsConfigError, init_metrics}; +use vmm::vmm_config::metrics::{MetricsSpec, MetricsSpecError, init_metrics}; use vmm::{EventManager, FcExitCode, HTTP_MAX_PAYLOAD_SIZE}; use vmm_sys_util::terminal::Terminal; @@ -58,7 +58,7 @@ enum MainError { /// Could not initialize logger: {0} LoggerInitialization(vmm::logger::LoggerUpdateError), /// Could not initialize metrics: {0} - MetricsInitialization(MetricsConfigError), + MetricsInitialization(MetricsSpecError), /// Seccomp error: {0} SeccompFilter(FilterError), /// Failed to resize fd table: {0} @@ -350,10 +350,10 @@ fn main_exec() -> Result<(), MainError> { }; if let Some(metrics_path) = arguments.single_value("metrics-path") { - let metrics_config = MetricsConfig { + let metrics_spec = MetricsSpec { metrics_path: PathBuf::from(metrics_path), }; - init_metrics(metrics_config).map_err(MainError::MetricsInitialization)?; + init_metrics(metrics_spec).map_err(MainError::MetricsInitialization)?; } let mut seccomp_filters: BpfThreadMap = SeccompConfig::from_args( diff --git a/src/vmm/benches/memory_access.rs b/src/vmm/benches/memory_access.rs index a272aceceaa..df86fbe35e7 100644 --- a/src/vmm/benches/memory_access.rs +++ b/src/vmm/benches/memory_access.rs @@ -5,7 +5,7 @@ use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; use vmm::resources::VmResources; -use vmm::vmm_config::machine_config::{HugePageConfig, MachineConfig}; +use vmm::vmm_config::machine_config::{HugePageConfig, MachineSpec}; fn bench_single_page_fault(c: &mut Criterion, configuration: VmResources) { c.bench_function("page_fault", |b| { @@ -34,7 +34,7 @@ pub fn bench_4k_page_fault(c: &mut Criterion) { bench_single_page_fault( c, VmResources { - machine_config: MachineConfig { + machine_spec: MachineSpec { vcpu_count: 1, mem_size_mib: 2, ..Default::default() @@ -48,7 +48,7 @@ pub fn bench_2m_page_fault(c: &mut Criterion) { bench_single_page_fault( c, VmResources { - machine_config: MachineConfig { + machine_spec: MachineSpec { vcpu_count: 1, mem_size_mib: 2, huge_pages: HugePageConfig::Hugetlbfs2M, diff --git a/src/vmm/src/arch/aarch64/mod.rs b/src/vmm/src/arch/aarch64/mod.rs index 4e82a7d3d56..d4c64f7d8ea 100644 --- a/src/vmm/src/arch/aarch64/mod.rs +++ b/src/vmm/src/arch/aarch64/mod.rs @@ -29,7 +29,7 @@ use crate::cpu_config::aarch64::{CpuConfiguration, CpuConfigurationError}; use crate::cpu_config::templates::CustomCpuTemplate; use crate::initrd::InitrdConfig; use crate::utils::{align_up, u64_to_usize, usize_to_u64}; -use crate::vmm_config::machine_config::MachineConfig; +use crate::vmm_config::machine_config::MachineSpec; use crate::vstate::memory::{ Address, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap, GuestRegionType, }; @@ -90,7 +90,7 @@ pub fn configure_system_for_boot( vm: &Vm, device_manager: &mut DeviceManager, vcpus: &mut [Vcpu], - machine_config: &MachineConfig, + machine_spec: &MachineSpec, cpu_template: &CustomCpuTemplate, entry_point: EntryPoint, initrd: &Option, @@ -103,8 +103,8 @@ pub fn configure_system_for_boot( let cpu_config = CpuConfiguration::apply_template(cpu_config, cpu_template); let vcpu_config = VcpuConfig { - vcpu_count: machine_config.vcpu_count, - smt: machine_config.smt, + vcpu_count: machine_spec.vcpu_count, + smt: machine_spec.smt, cpu_config, }; diff --git a/src/vmm/src/arch/x86_64/mod.rs b/src/vmm/src/arch/x86_64/mod.rs index 4d6b906768e..cb925b0b864 100644 --- a/src/vmm/src/arch/x86_64/mod.rs +++ b/src/vmm/src/arch/x86_64/mod.rs @@ -58,7 +58,7 @@ use crate::cpu_config::x86_64::CpuConfiguration; use crate::device_manager::DeviceManager; use crate::initrd::InitrdConfig; use crate::utils::{align_down, u64_to_usize, usize_to_u64}; -use crate::vmm_config::machine_config::MachineConfig; +use crate::vmm_config::machine_config::MachineSpec; use crate::vstate::memory::{ Address, GuestAddress, GuestMemory, GuestMemoryMmap, GuestMemoryRegion, GuestRegionType, }; @@ -178,7 +178,7 @@ pub fn configure_system_for_boot( vm: &Vm, device_manager: &mut DeviceManager, vcpus: &mut [Vcpu], - machine_config: &MachineConfig, + machine_spec: &MachineSpec, cpu_template: &CustomCpuTemplate, entry_point: EntryPoint, initrd: &Option, @@ -190,8 +190,8 @@ pub fn configure_system_for_boot( let cpu_config = CpuConfiguration::apply_template(cpu_config, cpu_template)?; let vcpu_config = VcpuConfig { - vcpu_count: machine_config.vcpu_count, - smt: machine_config.smt, + vcpu_count: machine_spec.vcpu_count, + smt: machine_spec.smt, cpu_config, }; diff --git a/src/vmm/src/builder.rs b/src/vmm/src/builder.rs index 332b1ac3cc3..e957fe62823 100644 --- a/src/vmm/src/builder.rs +++ b/src/vmm/src/builder.rs @@ -46,8 +46,8 @@ use crate::seccomp::BpfThreadMap; use crate::snapshot::Persist; use crate::utils::mib_to_bytes; use crate::vmm_config::instance_info::InstanceInfo; -use crate::vmm_config::machine_config::MachineConfigError; -use crate::vmm_config::memory_hotplug::MemoryHotplugConfig; +use crate::vmm_config::machine_config::MachineSpecError; +use crate::vmm_config::memory_hotplug::MemoryHotplugSpec; use crate::vstate::kvm::{Kvm, KvmError}; use crate::vstate::memory::GuestRegionMmap; #[cfg(target_arch = "aarch64")] @@ -110,7 +110,7 @@ pub enum StartMicrovmError { /// Cannot restore microvm state: {0} RestoreMicrovmState(MicrovmStateError), /// Cannot set vm resources: {0} - SetVmResources(MachineConfigError), + SetVmResources(MachineSpecError), /// Cannot create the entropy device: {0} CreateEntropyDevice(crate::devices::virtio::rng::EntropyError), /// Failed to allocate guest resource: {0} @@ -161,16 +161,13 @@ pub fn build_microvm_for_boot( #[allow(unused_mut)] let mut boot_cmdline = boot_config.cmdline.clone(); - let cpu_template = vm_resources - .machine_config - .cpu_template - .get_cpu_template()?; + let cpu_template = vm_resources.machine_spec.cpu_template.get_cpu_template()?; let kvm = Kvm::new(cpu_template.kvm_capabilities.clone())?; // Set up Kvm Vm and register memory regions. // Build custom CPU config if a custom template is provided. let mut vm = Vm::new(&kvm)?; - let (mut vcpus, vcpus_exit_evt) = vm.create_vcpus(vm_resources.machine_config.vcpu_count)?; + let (mut vcpus, vcpus_exit_evt) = vm.create_vcpus(vm_resources.machine_spec.vcpu_count)?; vm.register_dram_memory_regions(guest_memory)?; // Allocate memory as soon as possible to make hotpluggable memory available to all consumers, @@ -302,7 +299,7 @@ pub fn build_microvm_for_boot( &vm, &mut device_manager, vcpus.as_mut(), - &vm_resources.machine_config, + &vm_resources.machine_spec, &cpu_template, entry_point, &initrd, @@ -406,7 +403,7 @@ pub enum BuildMicrovmFromSnapshotError { /// Failed to restore microVM state: {0} RestoreState(#[from] crate::vstate::vm::ArchVmError), /// Failed to update microVM configuration: {0} - VmUpdateConfig(#[from] MachineConfigError), + VmUpdateConfig(#[from] MachineSpecError), /// Failed to restore MMIO device: {0} RestoreMmioDevice(#[from] MicrovmStateError), /// Failed to emulate MMIO serial: {0} @@ -449,7 +446,7 @@ pub fn build_microvm_from_snapshot( let mut vm = Vm::new(&kvm).map_err(StartMicrovmError::Vm)?; let (mut vcpus, vcpus_exit_evt) = vm - .create_vcpus(vm_resources.machine_config.vcpu_count) + .create_vcpus(vm_resources.machine_spec.vcpu_count) .map_err(StartMicrovmError::Vm)?; vm.restore_memory_regions(guest_memory, µvm_state.vm_state.memory) @@ -489,7 +486,7 @@ pub fn build_microvm_from_snapshot( vm.restore_state(µvm_state.vm_state)?; // Restore the boot source config paths. - vm_resources.boot_source.config = microvm_state.vm_info.boot_source; + vm_resources.boot_source.spec = microvm_state.vm_info.boot_source; let vm = Arc::new(vm); @@ -624,7 +621,7 @@ fn attach_virtio_mem_device( device_manager: &mut DeviceManager, vm: &Arc, cmdline: &mut LoaderKernelCmdline, - config: &MemoryHotplugConfig, + spec: &MemoryHotplugSpec, event_manager: &mut EventManager, addr: GuestAddress, ) -> Result<(), StartMicrovmError> { @@ -632,9 +629,9 @@ fn attach_virtio_mem_device( VirtioMem::new( Arc::clone(vm), addr, - config.total_size_mib, - config.block_size_mib, - config.slot_size_mib, + spec.total_size_mib, + spec.block_size_mib, + spec.slot_size_mib, ) .map_err(|e| StartMicrovmError::Internal(VmmError::VirtioMem(e)))?, )); @@ -700,16 +697,16 @@ fn attach_pmem_devices<'a, I: Iterator>> + Debug>( for (i, device) in pmem_devices.enumerate() { let id = { let mut locked_dev = device.lock().expect("Poisoned lock"); - if locked_dev.config.root_device { + if locked_dev.spec.root_device { cmdline.insert_str(format!("root=/dev/pmem{i}"))?; - match locked_dev.config.read_only { + match locked_dev.spec.read_only { true => cmdline.insert_str("ro")?, false => cmdline.insert_str("rw")?, } } locked_dev.alloc_region(vm.as_ref()); locked_dev.set_mem_region(vm.as_ref())?; - locked_dev.config.id.to_string() + locked_dev.spec.id.to_string() }; event_manager.add_subscriber(device.clone()); @@ -759,14 +756,14 @@ pub(crate) mod tests { use crate::mmds::data_store::{Mmds, MmdsVersion}; use crate::mmds::ns::MmdsNetworkStack; use crate::utils::mib_to_bytes; - use crate::vmm_config::balloon::{BALLOON_DEV_ID, BalloonBuilder, BalloonDeviceConfig}; + use crate::vmm_config::balloon::{BALLOON_DEV_ID, BalloonBuilder, BalloonDeviceSpec}; use crate::vmm_config::boot_source::DEFAULT_KERNEL_CMDLINE; - use crate::vmm_config::drive::{BlockBuilder, BlockDeviceConfig}; - use crate::vmm_config::entropy::{EntropyDeviceBuilder, EntropyDeviceConfig}; - use crate::vmm_config::net::{NetBuilder, NetworkInterfaceConfig}; - use crate::vmm_config::pmem::{PmemBuilder, PmemConfig}; - use crate::vmm_config::vsock::tests::default_config; - use crate::vmm_config::vsock::{VsockBuilder, VsockDeviceConfig}; + use crate::vmm_config::drive::{BlockBuilder, BlockDeviceSpec}; + use crate::vmm_config::entropy::{EntropyDeviceBuilder, EntropyDeviceSpec}; + use crate::vmm_config::net::{NetBuilder, NetworkInterfaceSpec}; + use crate::vmm_config::pmem::{PmemBuilder, PmemSpec}; + use crate::vmm_config::vsock::tests::default_spec; + use crate::vmm_config::vsock::{VsockBuilder, VsockDeviceSpec}; use crate::vstate::vm::tests::setup_vm_with_memory; #[derive(Debug)] @@ -850,7 +847,7 @@ pub(crate) mod tests { for custom_block_cfg in custom_block_cfgs { block_files.push(TempFile::new().unwrap()); - let block_device_config = BlockDeviceConfig { + let block_device_spec = BlockDeviceSpec { drive_id: String::from(&custom_block_cfg.drive_id), partuuid: custom_block_cfg.partuuid, is_root_device: custom_block_cfg.is_root_device, @@ -872,9 +869,7 @@ pub(crate) mod tests { socket: None, }; - block_dev_configs - .insert(block_device_config, false) - .unwrap(); + block_dev_configs.insert(block_device_spec, false).unwrap(); } attach_block_devices( @@ -892,10 +887,10 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - net_config: NetworkInterfaceConfig, + net_spec: NetworkInterfaceSpec, ) { let mut net_builder = NetBuilder::new(); - net_builder.build(net_config).unwrap(); + net_builder.build(net_spec).unwrap(); let res = attach_net_devices( &mut vmm.device_manager, @@ -911,11 +906,11 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - net_config: NetworkInterfaceConfig, + net_spec: NetworkInterfaceSpec, mmds_version: MmdsVersion, ) { let mut net_builder = NetBuilder::new(); - net_builder.build(net_config).unwrap(); + net_builder.build(net_spec).unwrap(); let net = net_builder.iter().next().unwrap(); let mut mmds = Mmds::default(); mmds.set_version(mmds_version); @@ -938,10 +933,10 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - vsock_config: VsockDeviceConfig, + vsock_spec: VsockDeviceSpec, ) { let vsock_dev_id = VSOCK_DEV_ID.to_owned(); - let vsock = VsockBuilder::create_unixsock_vsock(vsock_config).unwrap(); + let vsock = VsockBuilder::create_unixsock_vsock(vsock_spec).unwrap(); let vsock = Arc::new(Mutex::new(vsock)); attach_unixsock_vsock_device( @@ -964,10 +959,10 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - entropy_config: EntropyDeviceConfig, + entropy_spec: EntropyDeviceSpec, ) { let mut builder = EntropyDeviceBuilder::new(); - let entropy = builder.build(entropy_config).unwrap(); + let entropy = builder.build(entropy_spec).unwrap(); attach_entropy_device( &mut vmm.device_manager, @@ -989,17 +984,17 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - configs: Vec, + specs: Vec, ) -> Vec { let mut builder = PmemBuilder::default(); let mut files = Vec::new(); - for mut config in configs { + for mut spec in specs { let tmp_file = TempFile::new().unwrap(); tmp_file.as_file().set_len(0x20_0000).unwrap(); let tmp_file_path = tmp_file.as_path().to_str().unwrap().to_string(); files.push(tmp_file); - config.path_on_host = tmp_file_path; - builder.build(config, false).unwrap(); + spec.path_on_host = tmp_file_path; + builder.build(spec, false).unwrap(); } attach_pmem_devices( @@ -1027,10 +1022,10 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - balloon_config: BalloonDeviceConfig, + balloon_spec: BalloonDeviceSpec, ) { let mut builder = BalloonBuilder::new(); - builder.set(balloon_config).unwrap(); + builder.set(balloon_spec).unwrap(); let balloon = builder.get().unwrap(); attach_balloon_device( @@ -1054,7 +1049,7 @@ pub(crate) mod tests { let mut event_manager = EventManager::new().expect("Unable to create EventManager"); let mut vmm = default_vmm(); - let network_interface = NetworkInterfaceConfig { + let network_interface = NetworkInterfaceSpec { iface_id: String::from("netif"), host_dev_name: String::from("hostname"), guest_mac: None, @@ -1267,7 +1262,7 @@ pub(crate) mod tests { let mut event_manager = EventManager::new().expect("Unable to create EventManager"); let id = String::from("root"); - let configs = vec![PmemConfig { + let pmem_specs = vec![PmemSpec { id: id.clone(), path_on_host: "".into(), root_device: true, @@ -1275,7 +1270,7 @@ pub(crate) mod tests { }]; let mut vmm = default_vmm(); let mut cmdline = default_kernel_cmdline(); - _ = insert_pmem_devices(&mut vmm, &mut cmdline, &mut event_manager, configs); + _ = insert_pmem_devices(&mut vmm, &mut cmdline, &mut event_manager, pmem_specs); assert!(cmdline_contains(&cmdline, "root=/dev/pmem0 ro")); assert!( vmm.device_manager @@ -1301,7 +1296,7 @@ pub(crate) mod tests { let mut event_manager = EventManager::new().expect("Unable to create EventManager"); let mut vmm = default_vmm(); - let balloon_config = BalloonDeviceConfig { + let balloon_spec = BalloonDeviceSpec { amount_mib: 0, deflate_on_oom: false, stats_polling_interval_s: 0, @@ -1310,7 +1305,7 @@ pub(crate) mod tests { }; let mut cmdline = default_kernel_cmdline(); - insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_config); + insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_spec); // Check if the vsock device is described in kernel_cmdline. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] assert!(cmdline_contains( @@ -1324,10 +1319,10 @@ pub(crate) mod tests { let mut event_manager = EventManager::new().expect("Unable to create EventManager"); let mut vmm = default_vmm(); - let entropy_config = EntropyDeviceConfig::default(); + let entropy_spec = EntropyDeviceSpec::default(); let mut cmdline = default_kernel_cmdline(); - insert_entropy_device(&mut vmm, &mut cmdline, &mut event_manager, entropy_config); + insert_entropy_device(&mut vmm, &mut cmdline, &mut event_manager, entropy_spec); // Check if the vsock device is described in kernel_cmdline. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] assert!(cmdline_contains( @@ -1343,10 +1338,10 @@ pub(crate) mod tests { let mut tmp_sock_file = TempFile::new().unwrap(); tmp_sock_file.remove().unwrap(); - let vsock_config = default_config(&tmp_sock_file); + let vsock_spec = default_spec(&tmp_sock_file); let mut cmdline = default_kernel_cmdline(); - insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_config); + insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_spec); // Check if the vsock device is described in kernel_cmdline. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] assert!(cmdline_contains( @@ -1359,13 +1354,13 @@ pub(crate) mod tests { vmm: &mut Vmm, cmdline: &mut Cmdline, event_manager: &mut EventManager, - config: MemoryHotplugConfig, + spec: MemoryHotplugSpec, ) { attach_virtio_mem_device( &mut vmm.device_manager, &vmm.vm, cmdline, - &config, + &spec, event_manager, GuestAddress(512 << 30), ) @@ -1377,14 +1372,14 @@ pub(crate) mod tests { let mut event_manager = EventManager::new().expect("Unable to create EventManager"); let mut vmm = default_vmm(); - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 128, }; let mut cmdline = default_kernel_cmdline(); - insert_virtio_mem_device(&mut vmm, &mut cmdline, &mut event_manager, config); + insert_virtio_mem_device(&mut vmm, &mut cmdline, &mut event_manager, spec); // Check if the vsock device is described in kernel_cmdline. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] diff --git a/src/vmm/src/cpu_config/templates.rs b/src/vmm/src/cpu_config/templates.rs index bc558a457e4..93e6e6fb66e 100644 --- a/src/vmm/src/cpu_config/templates.rs +++ b/src/vmm/src/cpu_config/templates.rs @@ -72,7 +72,7 @@ impl From<&Option> for StaticCpuTemplate { } } -// This conversion is used when converting `&VmConfig` to `MachineConfig` to +// This conversion is used when converting `&VmConfig` to `MachineSpec` to // respond `GET /machine-config` and `GET /vm`. impl From<&CpuTemplateType> for StaticCpuTemplate { fn from(value: &CpuTemplateType) -> Self { diff --git a/src/vmm/src/device_manager/pci_mngr.rs b/src/vmm/src/device_manager/pci_mngr.rs index 219a558c2a2..b6b612c7d0b 100644 --- a/src/vmm/src/device_manager/pci_mngr.rs +++ b/src/vmm/src/device_manager/pci_mngr.rs @@ -36,8 +36,8 @@ use crate::devices::virtio::vsock::{Vsock, VsockUnixBackend}; use crate::pci::bus::PciRootError; use crate::resources::VmResources; use crate::snapshot::Persist; -use crate::vmm_config::memory_hotplug::MemoryHotplugConfig; -use crate::vmm_config::mmds::MmdsConfigError; +use crate::vmm_config::memory_hotplug::MemoryHotplugSpec; +use crate::vmm_config::mmds::MmdsSpecError; use crate::vstate::bus::BusError; use crate::vstate::interrupts::InterruptError; use crate::vstate::memory::GuestMemoryMmap; @@ -66,7 +66,7 @@ pub enum PciManagerError { /// KVM error: {0} Kvm(#[from] vmm_sys_util::errno::Error), /// MMDS error: {0} - Mmds(#[from] MmdsConfigError), + Mmds(#[from] MmdsSpecError), } impl PciDevices { @@ -402,7 +402,7 @@ impl<'a> Persist<'a> for PciDevices { .unwrap(); let device_state = pmem_dev.save(); state.pmem_devices.push(VirtioDeviceState { - device_id: pmem_dev.config.id.clone(), + device_id: pmem_dev.spec.id.clone(), pci_device_bdf, device_state, transport_state, @@ -629,7 +629,7 @@ impl<'a> Persist<'a> for PciDevices { let ctor_args = VirtioMemConstructorArgs::new(Arc::clone(constructor_args.vm)); let device = VirtioMem::restore(ctor_args, &memory_device.device_state).unwrap(); - constructor_args.vm_resources.memory_hotplug = Some(MemoryHotplugConfig { + constructor_args.vm_resources.memory_hotplug = Some(MemoryHotplugSpec { total_size_mib: device.total_size_mib(), block_size_mib: device.block_size_mib(), slot_size_mib: device.slot_size_mib(), @@ -660,14 +660,14 @@ mod tests { use crate::device_manager; use crate::devices::virtio::block::CacheType; use crate::mmds::data_store::MmdsVersion; - use crate::resources::VmmConfig; + use crate::resources::VmmSpec; use crate::snapshot::Snapshot; - use crate::vmm_config::balloon::BalloonDeviceConfig; - use crate::vmm_config::entropy::EntropyDeviceConfig; - use crate::vmm_config::memory_hotplug::MemoryHotplugConfig; - use crate::vmm_config::net::NetworkInterfaceConfig; - use crate::vmm_config::pmem::PmemConfig; - use crate::vmm_config::vsock::VsockDeviceConfig; + use crate::vmm_config::balloon::BalloonDeviceSpec; + use crate::vmm_config::entropy::EntropyDeviceSpec; + use crate::vmm_config::memory_hotplug::MemoryHotplugSpec; + use crate::vmm_config::net::NetworkInterfaceSpec; + use crate::vmm_config::pmem::PmemSpec; + use crate::vmm_config::vsock::VsockDeviceSpec; #[test] fn test_device_manager_persistence() { @@ -685,14 +685,14 @@ mod tests { let mut cmdline = default_kernel_cmdline(); // Add a balloon device. - let balloon_cfg = BalloonDeviceConfig { + let balloon_spec = BalloonDeviceSpec { amount_mib: 123, deflate_on_oom: false, stats_polling_interval_s: 1, free_page_hinting: false, free_page_reporting: false, }; - insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_cfg); + insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_spec); // Add a block device. let drive_id = String::from("root"); let block_configs = vec![CustomBlockConfig::new( @@ -705,7 +705,7 @@ mod tests { _block_files = insert_block_devices(&mut vmm, &mut cmdline, &mut event_manager, block_configs); // Add a net device. - let network_interface = NetworkInterfaceConfig { + let network_interface_spec = NetworkInterfaceSpec { iface_id: String::from("netif"), host_dev_name: String::from("hostname"), guest_mac: None, @@ -716,32 +716,32 @@ mod tests { &mut vmm, &mut cmdline, &mut event_manager, - network_interface, + network_interface_spec, MmdsVersion::V2, ); // Add a vsock device. let vsock_dev_id = "vsock"; - let vsock_config = VsockDeviceConfig { + let vsock_spec = VsockDeviceSpec { vsock_id: Some(vsock_dev_id.to_string()), guest_cid: 3, uds_path: tmp_sock_file.as_path().to_str().unwrap().to_string(), }; - insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_config); + insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_spec); // Add an entropy device. - let entropy_config = EntropyDeviceConfig::default(); - insert_entropy_device(&mut vmm, &mut cmdline, &mut event_manager, entropy_config); + let entropy_spec = EntropyDeviceSpec::default(); + insert_entropy_device(&mut vmm, &mut cmdline, &mut event_manager, entropy_spec); // Add a pmem device. let pmem_id = String::from("pmem"); - let pmem_configs = vec![PmemConfig { + let pmem_specs = vec![PmemSpec { id: pmem_id, path_on_host: "".into(), root_device: true, read_only: true, }]; _pmem_files = - insert_pmem_devices(&mut vmm, &mut cmdline, &mut event_manager, pmem_configs); + insert_pmem_devices(&mut vmm, &mut cmdline, &mut event_manager, pmem_specs); - let memory_hotplug_config = MemoryHotplugConfig { + let memory_hotplug_spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 128, @@ -750,7 +750,7 @@ mod tests { &mut vmm, &mut cmdline, &mut event_manager, - memory_hotplug_config, + memory_hotplug_spec, ); Snapshot::new(vmm.device_manager.save()) @@ -877,7 +877,7 @@ mod tests { ); assert_eq!( expected_vm_resources, - serde_json::to_string_pretty(&VmmConfig::from(&*vm_resources)).unwrap() + serde_json::to_string_pretty(&VmmSpec::from(&*vm_resources)).unwrap() ); } } diff --git a/src/vmm/src/device_manager/persist.rs b/src/vmm/src/device_manager/persist.rs index 16e65a67845..8797fa5cd45 100644 --- a/src/vmm/src/device_manager/persist.rs +++ b/src/vmm/src/device_manager/persist.rs @@ -53,8 +53,8 @@ use crate::devices::virtio::vsock::{Vsock, VsockError, VsockUnixBackend, VsockUn use crate::mmds::data_store::MmdsVersion; use crate::resources::VmResources; use crate::snapshot::Persist; -use crate::vmm_config::memory_hotplug::MemoryHotplugConfig; -use crate::vmm_config::mmds::MmdsConfigError; +use crate::vmm_config::memory_hotplug::MemoryHotplugSpec; +use crate::vmm_config::mmds::MmdsSpecError; use crate::vstate::bus::BusError; use crate::vstate::memory::GuestMemoryMmap; use crate::{EventManager, Vm}; @@ -81,8 +81,8 @@ pub enum DevicePersistError { Vsock(#[from] VsockError), /// VsockUnixBackend: {0} VsockUnixBackend(#[from] VsockUnixBackendError), - /// MmdsConfig: {0} - MmdsConfig(#[from] MmdsConfigError), + /// MmdsSpec: {0} + MmdsSpec(#[from] MmdsSpecError), /// Entropy: {0} Entropy(#[from] EntropyError), /// Pmem: {0} @@ -599,7 +599,7 @@ impl<'a> Persist<'a> for MMIODeviceManager { let ctor_args = VirtioMemConstructorArgs::new(Arc::clone(vm)); let device = VirtioMem::restore(ctor_args, &memory_state.device_state)?; - constructor_args.vm_resources.memory_hotplug = Some(MemoryHotplugConfig { + constructor_args.vm_resources.memory_hotplug = Some(MemoryHotplugSpec { total_size_mib: device.total_size_mib(), block_size_mib: device.block_size_mib(), slot_size_mib: device.slot_size_mib(), @@ -631,14 +631,14 @@ mod tests { use crate::builder::tests::*; use crate::device_manager; use crate::devices::virtio::block::CacheType; - use crate::resources::VmmConfig; + use crate::resources::VmmSpec; use crate::snapshot::Snapshot; - use crate::vmm_config::balloon::BalloonDeviceConfig; - use crate::vmm_config::entropy::EntropyDeviceConfig; - use crate::vmm_config::memory_hotplug::MemoryHotplugConfig; - use crate::vmm_config::net::NetworkInterfaceConfig; - use crate::vmm_config::pmem::PmemConfig; - use crate::vmm_config::vsock::VsockDeviceConfig; + use crate::vmm_config::balloon::BalloonDeviceSpec; + use crate::vmm_config::entropy::EntropyDeviceSpec; + use crate::vmm_config::memory_hotplug::MemoryHotplugSpec; + use crate::vmm_config::net::NetworkInterfaceSpec; + use crate::vmm_config::pmem::PmemSpec; + use crate::vmm_config::vsock::VsockDeviceSpec; impl PartialEq for VirtioDeviceState { fn eq(&self, other: &VirtioDeviceState) -> bool { @@ -696,14 +696,14 @@ mod tests { let mut cmdline = default_kernel_cmdline(); // Add a balloon device. - let balloon_cfg = BalloonDeviceConfig { + let balloon_spec = BalloonDeviceSpec { amount_mib: 123, deflate_on_oom: false, stats_polling_interval_s: 1, free_page_hinting: false, free_page_reporting: false, }; - insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_cfg); + insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_spec); // Add a block device. let drive_id = String::from("root"); let block_configs = vec![CustomBlockConfig::new( @@ -716,7 +716,7 @@ mod tests { _block_files = insert_block_devices(&mut vmm, &mut cmdline, &mut event_manager, block_configs); // Add a net device. - let network_interface = NetworkInterfaceConfig { + let network_interface_spec = NetworkInterfaceSpec { iface_id: String::from("netif"), host_dev_name: String::from("hostname"), guest_mac: None, @@ -727,32 +727,32 @@ mod tests { &mut vmm, &mut cmdline, &mut event_manager, - network_interface, + network_interface_spec, MmdsVersion::V2, ); // Add a vsock device. let vsock_dev_id = "vsock"; - let vsock_config = VsockDeviceConfig { + let vsock_spec = VsockDeviceSpec { vsock_id: Some(vsock_dev_id.to_string()), guest_cid: 3, uds_path: tmp_sock_file.as_path().to_str().unwrap().to_string(), }; - insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_config); + insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_spec); // Add an entropy device. - let entropy_config = EntropyDeviceConfig::default(); - insert_entropy_device(&mut vmm, &mut cmdline, &mut event_manager, entropy_config); + let entropy_spec = EntropyDeviceSpec::default(); + insert_entropy_device(&mut vmm, &mut cmdline, &mut event_manager, entropy_spec); // Add a pmem device. let pmem_id = String::from("pmem"); - let pmem_configs = vec![PmemConfig { + let pmem_specs = vec![PmemSpec { id: pmem_id, path_on_host: "".into(), root_device: true, read_only: true, }]; _pmem_files = - insert_pmem_devices(&mut vmm, &mut cmdline, &mut event_manager, pmem_configs); + insert_pmem_devices(&mut vmm, &mut cmdline, &mut event_manager, pmem_specs); - let memory_hotplug_config = MemoryHotplugConfig { + let memory_hotplug_spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 128, @@ -761,7 +761,7 @@ mod tests { &mut vmm, &mut cmdline, &mut event_manager, - memory_hotplug_config, + memory_hotplug_spec, ); Snapshot::new(vmm.device_manager.save()) @@ -884,7 +884,7 @@ mod tests { ); assert_eq!( expected_vm_resources, - serde_json::to_string_pretty(&VmmConfig::from(&*vm_resources)).unwrap() + serde_json::to_string_pretty(&VmmSpec::from(&*vm_resources)).unwrap() ); } } diff --git a/src/vmm/src/devices/virtio/block/device.rs b/src/vmm/src/devices/virtio/block/device.rs index d3f3b10f3b3..b137fe3f0b4 100644 --- a/src/vmm/src/devices/virtio/block/device.rs +++ b/src/vmm/src/devices/virtio/block/device.rs @@ -19,7 +19,7 @@ use crate::devices::virtio::transport::VirtioInterrupt; use crate::impl_device_type; use crate::rate_limiter::BucketUpdate; use crate::snapshot::Persist; -use crate::vmm_config::drive::BlockDeviceConfig; +use crate::vmm_config::drive::BlockDeviceSpec; use crate::vstate::memory::GuestMemoryMmap; // Clippy thinks that values of the enum are too different in size. @@ -31,12 +31,12 @@ pub enum Block { } impl Block { - pub fn new(config: BlockDeviceConfig) -> Result { - if let Ok(config) = VirtioBlockConfig::try_from(&config) { + pub fn new(spec: BlockDeviceSpec) -> Result { + if let Ok(config) = VirtioBlockConfig::try_from(&spec) { Ok(Self::Virtio( VirtioBlock::new(config).map_err(BlockError::VirtioBackend)?, )) - } else if let Ok(config) = VhostUserBlockConfig::try_from(&config) { + } else if let Ok(config) = VhostUserBlockConfig::try_from(&spec) { Ok(Self::VhostUser( VhostUserBlock::new(config).map_err(BlockError::VhostUserBackend)?, )) @@ -45,7 +45,7 @@ impl Block { } } - pub fn config(&self) -> BlockDeviceConfig { + pub fn config(&self) -> BlockDeviceSpec { match self { Self::Virtio(b) => b.config().into(), Self::VhostUser(b) => b.config().into(), diff --git a/src/vmm/src/devices/virtio/block/vhost_user/device.rs b/src/vmm/src/devices/virtio/block/vhost_user/device.rs index dd08b8de7c8..9bf80aeb1ff 100644 --- a/src/vmm/src/devices/virtio/block/vhost_user/device.rs +++ b/src/vmm/src/devices/virtio/block/vhost_user/device.rs @@ -30,7 +30,7 @@ use crate::devices::virtio::vhost_user_metrics::{ use crate::impl_device_type; use crate::logger::{IncMetric, StoreMetric, log_dev_preview_warning}; use crate::utils::u64_to_usize; -use crate::vmm_config::drive::BlockDeviceConfig; +use crate::vmm_config::drive::BlockDeviceSpec; use crate::vstate::memory::GuestMemoryMmap; /// Block device config space size in bytes. @@ -65,10 +65,10 @@ pub struct VhostUserBlockConfig { pub socket: String, } -impl TryFrom<&BlockDeviceConfig> for VhostUserBlockConfig { +impl TryFrom<&BlockDeviceSpec> for VhostUserBlockConfig { type Error = VhostUserBlockError; - fn try_from(value: &BlockDeviceConfig) -> Result { + fn try_from(value: &BlockDeviceSpec) -> Result { if value.socket.is_some() && value.is_read_only.is_none() && value.path_on_host.is_none() @@ -89,7 +89,7 @@ impl TryFrom<&BlockDeviceConfig> for VhostUserBlockConfig { } } -impl From for BlockDeviceConfig { +impl From for BlockDeviceSpec { fn from(value: VhostUserBlockConfig) -> Self { Self { drive_id: value.drive_id, @@ -395,7 +395,7 @@ mod tests { #[test] fn test_from_config() { - let block_config = BlockDeviceConfig { + let block_spec = BlockDeviceSpec { drive_id: "".to_string(), partuuid: None, is_root_device: false, @@ -408,9 +408,9 @@ mod tests { socket: Some("sock".to_string()), }; - VhostUserBlockConfig::try_from(&block_config).unwrap(); + VhostUserBlockConfig::try_from(&block_spec).unwrap(); - let block_config = BlockDeviceConfig { + let block_spec = BlockDeviceSpec { drive_id: "".to_string(), partuuid: None, is_root_device: false, @@ -423,9 +423,9 @@ mod tests { socket: None, }; - VhostUserBlockConfig::try_from(&block_config).unwrap_err(); + VhostUserBlockConfig::try_from(&block_spec).unwrap_err(); - let block_config = BlockDeviceConfig { + let block_spec = BlockDeviceSpec { drive_id: "".to_string(), partuuid: None, is_root_device: false, @@ -438,7 +438,7 @@ mod tests { socket: Some("sock".to_string()), }; - VhostUserBlockConfig::try_from(&block_config).unwrap_err(); + VhostUserBlockConfig::try_from(&block_spec).unwrap_err(); } #[test] diff --git a/src/vmm/src/devices/virtio/block/virtio/device.rs b/src/vmm/src/devices/virtio/block/virtio/device.rs index ecdd8ee4f6d..d7f6b3eb039 100644 --- a/src/vmm/src/devices/virtio/block/virtio/device.rs +++ b/src/vmm/src/devices/virtio/block/virtio/device.rs @@ -38,8 +38,8 @@ use crate::impl_device_type; use crate::logger::{IncMetric, error, warn}; use crate::rate_limiter::{BucketUpdate, RateLimiter}; use crate::utils::u64_to_usize; -use crate::vmm_config::RateLimiterConfig; -use crate::vmm_config::drive::BlockDeviceConfig; +use crate::vmm_config::RateLimiterSpec; +use crate::vmm_config::drive::BlockDeviceSpec; use crate::vstate::memory::GuestMemoryMmap; /// The engine file type, either Sync or Async (through io_uring). @@ -193,17 +193,17 @@ pub struct VirtioBlockConfig { /// Path of the backing file on the host pub path_on_host: String, /// Rate Limiter for I/O operations. - pub rate_limiter: Option, + pub rate_limiter: Option, /// The type of IO engine used by the device. #[serde(default)] #[serde(rename = "io_engine")] pub file_engine_type: FileEngineType, } -impl TryFrom<&BlockDeviceConfig> for VirtioBlockConfig { +impl TryFrom<&BlockDeviceSpec> for VirtioBlockConfig { type Error = VirtioBlockError; - fn try_from(value: &BlockDeviceConfig) -> Result { + fn try_from(value: &BlockDeviceSpec) -> Result { if value.path_on_host.is_some() && value.socket.is_none() { Ok(Self { drive_id: value.drive_id.clone(), @@ -222,7 +222,7 @@ impl TryFrom<&BlockDeviceConfig> for VirtioBlockConfig { } } -impl From for BlockDeviceConfig { +impl From for BlockDeviceSpec { fn from(value: VirtioBlockConfig) -> Self { Self { drive_id: value.drive_id, @@ -293,7 +293,7 @@ impl VirtioBlock { let rate_limiter = config .rate_limiter - .map(RateLimiterConfig::try_into) + .map(RateLimiterSpec::try_into) .transpose() .map_err(VirtioBlockError::RateLimiter)? .unwrap_or_default(); @@ -341,7 +341,7 @@ impl VirtioBlock { /// Returns a copy of a device config pub fn config(&self) -> VirtioBlockConfig { - let rl: RateLimiterConfig = (&self.rate_limiter).into(); + let rl: RateLimiterSpec = (&self.rate_limiter).into(); VirtioBlockConfig { drive_id: self.id.clone(), path_on_host: self.disk.file_path.clone(), @@ -713,7 +713,7 @@ mod tests { #[test] fn test_from_config() { - let block_config = BlockDeviceConfig { + let block_spec = BlockDeviceSpec { drive_id: "".to_string(), partuuid: None, is_root_device: false, @@ -726,9 +726,9 @@ mod tests { socket: None, }; - VirtioBlockConfig::try_from(&block_config).unwrap(); + VirtioBlockConfig::try_from(&block_spec).unwrap(); - let block_config = BlockDeviceConfig { + let block_spec = BlockDeviceSpec { drive_id: "".to_string(), partuuid: None, is_root_device: false, @@ -741,9 +741,9 @@ mod tests { socket: Some("sock".to_string()), }; - VirtioBlockConfig::try_from(&block_config).unwrap_err(); + VirtioBlockConfig::try_from(&block_spec).unwrap_err(); - let block_config = BlockDeviceConfig { + let block_spec = BlockDeviceSpec { drive_id: "".to_string(), partuuid: None, is_root_device: false, @@ -756,7 +756,7 @@ mod tests { socket: Some("sock".to_string()), }; - VirtioBlockConfig::try_from(&block_config).unwrap_err(); + VirtioBlockConfig::try_from(&block_spec).unwrap_err(); } #[test] diff --git a/src/vmm/src/devices/virtio/block/virtio/test_utils.rs b/src/vmm/src/devices/virtio/block/virtio/test_utils.rs index e4f23c6a038..8eae3c0d008 100644 --- a/src/vmm/src/devices/virtio/block/virtio/test_utils.rs +++ b/src/vmm/src/devices/virtio/block/virtio/test_utils.rs @@ -23,7 +23,7 @@ use crate::devices::virtio::test_utils::{VirtQueue, VirtqDesc}; #[cfg(test)] use crate::devices::virtio::transport::VirtioInterruptType; use crate::rate_limiter::RateLimiter; -use crate::vmm_config::{RateLimiterConfig, TokenBucketConfig}; +use crate::vmm_config::{RateLimiterSpec, TokenBucketSpec}; use crate::vstate::memory::{Bytes, GuestAddress}; /// Create a default Block instance to be used in tests. @@ -45,13 +45,13 @@ pub fn default_block_with_path(path: String, file_engine_type: FileEngineType) - is_read_only: false, cache_type: CacheType::Unsafe, // Rate limiting is enabled but with a high operation rate (10 million ops/s). - rate_limiter: Some(RateLimiterConfig { - bandwidth: Some(TokenBucketConfig { + rate_limiter: Some(RateLimiterSpec { + bandwidth: Some(TokenBucketSpec { size: 0, one_time_burst: Some(0), refill_time: 0, }), - ops: Some(TokenBucketConfig { + ops: Some(TokenBucketSpec { size: 100_000, one_time_burst: Some(0), refill_time: 10, diff --git a/src/vmm/src/devices/virtio/pmem/device.rs b/src/vmm/src/devices/virtio/pmem/device.rs index ce426f2db47..217a858ecd0 100644 --- a/src/vmm/src/devices/virtio/pmem/device.rs +++ b/src/vmm/src/devices/virtio/pmem/device.rs @@ -24,7 +24,7 @@ use crate::devices::virtio::queue::{DescriptorChain, InvalidAvailIdx, Queue, Que use crate::devices::virtio::transport::{VirtioInterrupt, VirtioInterruptType}; use crate::logger::{IncMetric, error, info}; use crate::utils::{align_up, u64_to_usize}; -use crate::vmm_config::pmem::PmemConfig; +use crate::vmm_config::pmem::PmemSpec; use crate::vstate::memory::{ByteValued, Bytes, GuestMemoryMmap, GuestMmapRegion}; use crate::vstate::vm::VmError; use crate::{Vm, impl_device_type}; @@ -92,7 +92,7 @@ pub struct Pmem { pub mmap_ptr: u64, pub metrics: Arc, - pub config: PmemConfig, + pub spec: PmemSpec, } impl Drop for Pmem { @@ -112,15 +112,15 @@ impl Pmem { pub const ALIGNMENT: u64 = 2 * 1024 * 1024; /// Create a new Pmem device with a backing file at `disk_image_path` path. - pub fn new(config: PmemConfig) -> Result { - Self::new_with_queues(config, vec![Queue::new(PMEM_QUEUE_SIZE)]) + pub fn new(spec: PmemSpec) -> Result { + Self::new_with_queues(spec, vec![Queue::new(PMEM_QUEUE_SIZE)]) } /// Create a new Pmem device with a backing file at `disk_image_path` path using a pre-created /// set of queues. - pub fn new_with_queues(config: PmemConfig, queues: Vec) -> Result { + pub fn new_with_queues(spec: PmemSpec, queues: Vec) -> Result { let (file, file_len, mmap_ptr, mmap_len) = - Self::mmap_backing_file(&config.path_on_host, config.read_only)?; + Self::mmap_backing_file(&spec.path_on_host, spec.read_only)?; Ok(Self { avail_features: 1u64 << VIRTIO_F_VERSION_1, @@ -136,8 +136,8 @@ impl Pmem { file, file_len, mmap_ptr, - metrics: PmemMetricsPerDevice::alloc(config.id.clone()), - config, + metrics: PmemMetricsPerDevice::alloc(spec.id.clone()), + spec, }) } @@ -236,7 +236,7 @@ impl Pmem { guest_phys_addr: self.config_space.start, memory_size: self.config_space.size, userspace_addr: self.mmap_ptr, - flags: if self.config.read_only { + flags: if self.spec.read_only { KVM_MEM_READONLY } else { 0 @@ -401,7 +401,7 @@ impl VirtioDevice for Pmem { fn kick(&mut self) { if self.is_activated() { - info!("kick pmem {}.", self.config.id); + info!("kick pmem {}.", self.spec.id); self.handle_queue(); } } @@ -417,38 +417,38 @@ mod tests { #[test] fn test_from_config() { - let config = PmemConfig { + let spec = PmemSpec { id: "1".into(), path_on_host: "not_a_path".into(), root_device: true, read_only: false, }; assert!(matches!( - Pmem::new(config).unwrap_err(), + Pmem::new(spec).unwrap_err(), PmemError::BackingFile(_), )); let dummy_file = TempFile::new().unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let config = PmemConfig { + let spec = PmemSpec { id: "1".into(), path_on_host: dummy_path.clone(), root_device: true, read_only: false, }; assert!(matches!( - Pmem::new(config).unwrap_err(), + Pmem::new(spec).unwrap_err(), PmemError::BackingFileZeroSize, )); dummy_file.as_file().set_len(0x20_0000); - let config = PmemConfig { + let spec = PmemSpec { id: "1".into(), path_on_host: dummy_path, root_device: true, read_only: false, }; - Pmem::new(config).unwrap(); + Pmem::new(spec).unwrap(); } #[test] @@ -456,13 +456,13 @@ mod tests { let dummy_file = TempFile::new().unwrap(); dummy_file.as_file().set_len(0x20_0000); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let config = PmemConfig { + let spec = PmemSpec { id: "1".into(), path_on_host: dummy_path, root_device: true, read_only: false, }; - let mut pmem = Pmem::new(config).unwrap(); + let mut pmem = Pmem::new(spec).unwrap(); let mem = default_mem(); let interrupt = default_interrupt(); diff --git a/src/vmm/src/devices/virtio/pmem/persist.rs b/src/vmm/src/devices/virtio/pmem/persist.rs index a8089433b86..d0fdc55988f 100644 --- a/src/vmm/src/devices/virtio/pmem/persist.rs +++ b/src/vmm/src/devices/virtio/pmem/persist.rs @@ -11,7 +11,7 @@ use crate::devices::virtio::generated::virtio_ids::VIRTIO_ID_PMEM; use crate::devices::virtio::persist::{PersistError as VirtioStateError, VirtioDeviceState}; use crate::devices::virtio::pmem::{PMEM_NUM_QUEUES, PMEM_QUEUE_SIZE}; use crate::snapshot::Persist; -use crate::vmm_config::pmem::PmemConfig; +use crate::vmm_config::pmem::PmemSpec; use crate::vstate::memory::{GuestMemoryMmap, GuestRegionMmap}; use crate::vstate::vm::VmError; @@ -19,7 +19,7 @@ use crate::vstate::vm::VmError; pub struct PmemState { pub virtio_state: VirtioDeviceState, pub config_space: ConfigSpace, - pub config: PmemConfig, + pub spec: PmemSpec, } #[derive(Debug)] @@ -47,7 +47,7 @@ impl<'a> Persist<'a> for Pmem { PmemState { virtio_state: VirtioDeviceState::from_device(self), config_space: self.config_space, - config: self.config.clone(), + spec: self.spec.clone(), } } @@ -62,7 +62,7 @@ impl<'a> Persist<'a> for Pmem { PMEM_QUEUE_SIZE, )?; - let mut pmem = Pmem::new_with_queues(state.config.clone(), queues)?; + let mut pmem = Pmem::new_with_queues(state.spec.clone(), queues)?; pmem.config_space = state.config_space; pmem.avail_features = state.virtio_state.avail_features; pmem.acked_features = state.virtio_state.acked_features; @@ -89,13 +89,13 @@ mod tests { let dummy_file = TempFile::new().unwrap(); dummy_file.as_file().set_len(0x20_0000); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let config = PmemConfig { + let spec = PmemSpec { id: "1".into(), path_on_host: dummy_path, root_device: true, read_only: false, }; - let pmem = Pmem::new(config).unwrap(); + let pmem = Pmem::new(spec).unwrap(); let guest_mem = default_mem(); let kvm = Kvm::new(vec![]).unwrap(); let vm = Vm::new(&kvm).unwrap(); @@ -126,6 +126,6 @@ mod tests { assert_eq!(restored_pmem.queues(), pmem.queues()); assert!(!pmem.is_activated()); assert!(!restored_pmem.is_activated()); - assert_eq!(restored_pmem.config, pmem.config); + assert_eq!(restored_pmem.spec, pmem.spec); } } diff --git a/src/vmm/src/initrd.rs b/src/vmm/src/initrd.rs index 9dfcd8bc16e..f8cf2b13d4c 100644 --- a/src/vmm/src/initrd.rs +++ b/src/vmm/src/initrd.rs @@ -38,10 +38,10 @@ pub struct InitrdConfig { impl InitrdConfig { /// Load initrd into guest memory based on the boot config. pub fn from_config( - boot_cfg: &BootConfig, + boot_spec: &BootConfig, vm_memory: &GuestMemoryMmap, ) -> Result, InitrdError> { - Ok(match &boot_cfg.initrd_file { + Ok(match &boot_spec.initrd_file { Some(f) => { let f = f.try_clone().map_err(InitrdError::CloneFd)?; Some(Self::from_file(vm_memory, f)?) diff --git a/src/vmm/src/persist.rs b/src/vmm/src/persist.rs index ba2608070c6..c6abd96b079 100644 --- a/src/vmm/src/persist.rs +++ b/src/vmm/src/persist.rs @@ -31,9 +31,9 @@ use crate::resources::VmResources; use crate::seccomp::BpfThreadMap; use crate::snapshot::Snapshot; use crate::utils::u64_to_usize; -use crate::vmm_config::boot_source::BootSourceConfig; +use crate::vmm_config::boot_source::BootSourceSpec; use crate::vmm_config::instance_info::InstanceInfo; -use crate::vmm_config::machine_config::{HugePageConfig, MachineConfigError, MachineConfigUpdate}; +use crate::vmm_config::machine_config::{HugePageConfig, MachineSpecError, MachineSpecUpdate}; use crate::vmm_config::snapshot::{CreateSnapshotParams, LoadSnapshotParams, MemBackendType}; use crate::vstate::kvm::KvmState; use crate::vstate::memory::{ @@ -53,7 +53,7 @@ pub struct VmInfo { /// CPU template type pub cpu_template: StaticCpuTemplate, /// Boot source information. - pub boot_source: BootSourceConfig, + pub boot_source: BootSourceSpec, /// Huge page configuration pub huge_pages: HugePageConfig, } @@ -61,11 +61,11 @@ pub struct VmInfo { impl From<&VmResources> for VmInfo { fn from(value: &VmResources) -> Self { Self { - mem_size_mib: value.machine_config.mem_size_mib as u64, - smt: value.machine_config.smt, - cpu_template: StaticCpuTemplate::from(&value.machine_config.cpu_template), - boot_source: value.boot_source.config.clone(), - huge_pages: value.machine_config.huge_pages, + mem_size_mib: value.machine_spec.mem_size_mib as u64, + smt: value.machine_spec.smt, + cpu_template: StaticCpuTemplate::from(&value.machine_spec.cpu_template), + boot_source: value.boot_source.spec.clone(), + huge_pages: value.machine_spec.huge_pages, } } } @@ -375,11 +375,11 @@ pub fn restore_from_snapshot( .vcpu_states .len() .try_into() - .map_err(|_| MachineConfigError::InvalidVcpuCount) + .map_err(|_| MachineSpecError::InvalidVcpuCount) .map_err(BuildMicrovmFromSnapshotError::VmUpdateConfig)?; vm_resources - .update_machine_config(&MachineConfigUpdate { + .update_machine_spec(&MachineSpecUpdate { vcpu_count: Some(vcpu_count), mem_size_mib: Some(u64_to_usize(microvm_state.vm_info.mem_size_mib)), smt: Some(microvm_state.vm_info.smt), @@ -399,7 +399,7 @@ pub fn restore_from_snapshot( let (guest_memory, uffd) = match params.mem_backend.backend_type { MemBackendType::File => { - if vm_resources.machine_config.huge_pages.is_hugetlbfs() { + if vm_resources.machine_spec.huge_pages.is_hugetlbfs() { return Err(RestoreFromSnapshotGuestMemoryError::File( GuestMemoryFromFileError::HugetlbfsSnapshot, ) @@ -415,7 +415,7 @@ pub fn restore_from_snapshot( mem_backend_path, mem_state, track_dirty_pages, - vm_resources.machine_config.huge_pages, + vm_resources.machine_spec.huge_pages, ) .map_err(RestoreFromSnapshotGuestMemoryError::Uffd)?, }; @@ -617,9 +617,9 @@ mod tests { use crate::construct_kvm_mpidrs; use crate::devices::virtio::block::CacheType; use crate::snapshot::Persist; - use crate::vmm_config::balloon::BalloonDeviceConfig; - use crate::vmm_config::net::NetworkInterfaceConfig; - use crate::vmm_config::vsock::tests::default_config; + use crate::vmm_config::balloon::BalloonDeviceSpec; + use crate::vmm_config::net::NetworkInterfaceSpec; + use crate::vmm_config::vsock::tests::default_spec; use crate::vstate::memory::{GuestMemoryRegionState, GuestRegionType}; fn default_vmm_with_devices() -> Vmm { @@ -628,14 +628,14 @@ mod tests { let mut cmdline = default_kernel_cmdline(); // Add a balloon device. - let balloon_config = BalloonDeviceConfig { + let balloon_spec = BalloonDeviceSpec { amount_mib: 0, deflate_on_oom: false, stats_polling_interval_s: 0, free_page_hinting: false, free_page_reporting: false, }; - insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_config); + insert_balloon_device(&mut vmm, &mut cmdline, &mut event_manager, balloon_spec); // Add a block device. let drive_id = String::from("root"); @@ -649,7 +649,7 @@ mod tests { insert_block_devices(&mut vmm, &mut cmdline, &mut event_manager, block_configs); // Add net device. - let network_interface = NetworkInterfaceConfig { + let network_interface_spec = NetworkInterfaceSpec { iface_id: String::from("netif"), host_dev_name: String::from("hostname"), guest_mac: None, @@ -660,15 +660,15 @@ mod tests { &mut vmm, &mut cmdline, &mut event_manager, - network_interface, + network_interface_spec, ); // Add vsock device. let mut tmp_sock_file = TempFile::new().unwrap(); tmp_sock_file.remove().unwrap(); - let vsock_config = default_config(&tmp_sock_file); + let vsock_spec = default_spec(&tmp_sock_file); - insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_config); + insert_vsock_device(&mut vmm, &mut cmdline, &mut event_manager, vsock_spec); #[cfg(target_arch = "x86_64")] insert_vmgenid_device(&mut vmm); diff --git a/src/vmm/src/resources.rs b/src/vmm/src/resources.rs index e2faeffaf56..de4fbb5c3c6 100644 --- a/src/vmm/src/resources.rs +++ b/src/vmm/src/resources.rs @@ -16,19 +16,17 @@ use crate::mmds::ns::MmdsNetworkStack; use crate::utils::mib_to_bytes; use crate::utils::net::ipv4addr::is_link_local_valid; use crate::vmm_config::balloon::*; -use crate::vmm_config::boot_source::{ - BootConfig, BootSource, BootSourceConfig, BootSourceConfigError, -}; +use crate::vmm_config::boot_source::{BootConfig, BootSource, BootSourceSpec, BootSourceSpecError}; use crate::vmm_config::drive::*; use crate::vmm_config::entropy::*; use crate::vmm_config::instance_info::InstanceInfo; -use crate::vmm_config::machine_config::{MachineConfig, MachineConfigError, MachineConfigUpdate}; -use crate::vmm_config::memory_hotplug::{MemoryHotplugConfig, MemoryHotplugConfigError}; -use crate::vmm_config::metrics::{MetricsConfig, MetricsConfigError, init_metrics}; -use crate::vmm_config::mmds::{MmdsConfig, MmdsConfigError}; +use crate::vmm_config::machine_config::{MachineSpec, MachineSpecError, MachineSpecUpdate}; +use crate::vmm_config::memory_hotplug::{MemoryHotplugSpec, MemoryHotplugSpecError}; +use crate::vmm_config::metrics::{MetricsSpec, MetricsSpecError, init_metrics}; +use crate::vmm_config::mmds::{MmdsSpec, MmdsSpecError}; use crate::vmm_config::net::*; -use crate::vmm_config::pmem::{PmemBuilder, PmemConfig, PmemConfigError}; -use crate::vmm_config::serial::SerialConfig; +use crate::vmm_config::pmem::{PmemBuilder, PmemSpec, PmemSpecError}; +use crate::vmm_config::serial::SerialSpec; use crate::vmm_config::vsock::*; use crate::vstate::memory; use crate::vstate::memory::{GuestRegionMmap, MemoryError}; @@ -37,11 +35,11 @@ use crate::vstate::memory::{GuestRegionMmap, MemoryError}; #[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum ResourcesError { /// Balloon device error: {0} - BalloonDevice(#[from] BalloonConfigError), + BalloonDevice(#[from] BalloonSpecError), /// Block device error: {0} BlockDevice(#[from] DriveError), /// Boot source error: {0} - BootSource(#[from] BootSourceConfigError), + BootSource(#[from] BootSourceSpecError), /// File operation error: {0} File(#[from] std::io::Error), /// Invalid JSON: {0} @@ -49,23 +47,23 @@ pub enum ResourcesError { /// Logger error: {0} Logger(#[from] crate::logger::LoggerUpdateError), /// Metrics error: {0} - Metrics(#[from] MetricsConfigError), + Metrics(#[from] MetricsSpecError), /// MMDS error: {0} Mmds(#[from] mmds::data_store::MmdsDatastoreError), - /// MMDS config error: {0} - MmdsConfig(#[from] MmdsConfigError), + /// MMDS spec error: {0} + MmdsSpec(#[from] MmdsSpecError), /// Network device error: {0} NetDevice(#[from] NetworkInterfaceError), - /// VM config error: {0} - MachineConfig(#[from] MachineConfigError), + /// VM spec error: {0} + MachineSpec(#[from] MachineSpecError), /// Vsock device error: {0} - VsockDevice(#[from] VsockConfigError), + VsockDevice(#[from] VsockSpecError), /// Entropy device error: {0} EntropyDevice(#[from] EntropyDeviceError), /// Pmem device error: {0} - PmemDevice(#[from] PmemConfigError), - /// Memory hotplug config error: {0} - MemoryHotplugConfig(#[from] MemoryHotplugConfigError), + PmemDevice(#[from] PmemSpecError), + /// Memory hotplug spec error: {0} + MemoryHotplugSpec(#[from] MemoryHotplugSpecError), } #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] @@ -78,33 +76,33 @@ enum CustomCpuTemplateOrPath { /// Used for configuring a vmm from one single json passed to the Firecracker process. #[derive(Debug, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] -pub struct VmmConfig { - balloon: Option, - drives: Vec, - boot_source: BootSourceConfig, +pub struct VmmSpec { + balloon: Option, + drives: Vec, + boot_source: BootSourceSpec, cpu_config: Option, logger: Option, - machine_config: Option, - metrics: Option, - mmds_config: Option, + machine_spec: Option, + metrics: Option, + mmds_spec: Option, #[serde(default)] - network_interfaces: Vec, - vsock: Option, - entropy: Option, + network_interfaces: Vec, + vsock: Option, + entropy: Option, #[serde(default, rename = "pmem")] - pmem_devices: Vec, + pmem_devices: Vec, #[serde(skip)] - serial_config: Option, - memory_hotplug: Option, + serial_spec: Option, + memory_hotplug: Option, } /// A data structure that encapsulates the device configurations /// held in the Vmm. #[derive(Debug, Default)] pub struct VmResources { - /// The vCpu and memory configuration for this microVM. - pub machine_config: MachineConfig, - /// The boot source spec (contains both config and builder) for this microVM. + /// The vCpu and memory specification for this microVM. + pub machine_spec: MachineSpec, + /// The boot source (contains both spec and builder) for this microVM. pub boot_source: BootSource, /// The block devices. pub block: BlockBuilder, @@ -118,8 +116,8 @@ pub struct VmResources { pub entropy: EntropyDeviceBuilder, /// The pmem devices. pub pmem: PmemBuilder, - /// The memory hotplug configuration. - pub memory_hotplug: Option, + /// The memory hotplug specification. + pub memory_hotplug: Option, /// The optional Mmds data store. // This is initialised on demand (if ever used), so that we don't allocate it unless it's // actually used. @@ -142,13 +140,13 @@ impl VmResources { mmds_size_limit: usize, metadata_json: Option<&str>, ) -> Result { - let vmm_config = serde_json::from_str::(config_json)?; + let vmm_spec = serde_json::from_str::(config_json)?; - if let Some(logger_config) = vmm_config.logger { + if let Some(logger_config) = vmm_spec.logger { crate::logger::LOGGER.update(logger_config)?; } - if let Some(metrics) = vmm_config.metrics { + if let Some(metrics) = vmm_spec.metrics { init_metrics(metrics)?; } @@ -156,12 +154,12 @@ impl VmResources { mmds_size_limit, ..Default::default() }; - if let Some(machine_config) = vmm_config.machine_config { - let machine_config = MachineConfigUpdate::from(machine_config); - resources.update_machine_config(&machine_config)?; + if let Some(machine_spec) = vmm_spec.machine_spec { + let machine_spec_update = MachineSpecUpdate::from(machine_spec); + resources.update_machine_spec(&machine_spec_update)?; } - if let Some(either) = vmm_config.cpu_config { + if let Some(either) = vmm_spec.cpu_config { match either { CustomCpuTemplateOrPath::Path(path) => { let cpu_config_json = @@ -175,22 +173,22 @@ impl VmResources { } } - resources.build_boot_source(vmm_config.boot_source)?; + resources.build_boot_source(vmm_spec.boot_source)?; - for drive_config in vmm_config.drives.into_iter() { - resources.set_block_device(drive_config)?; + for drive_spec in vmm_spec.drives.into_iter() { + resources.set_block_device(drive_spec)?; } - for net_config in vmm_config.network_interfaces.into_iter() { - resources.build_net_device(net_config)?; + for net_spec in vmm_spec.network_interfaces.into_iter() { + resources.build_net_device(net_spec)?; } - if let Some(vsock_config) = vmm_config.vsock { - resources.set_vsock_device(vsock_config)?; + if let Some(vsock_spec) = vmm_spec.vsock { + resources.set_vsock_device(vsock_spec)?; } - if let Some(balloon_config) = vmm_config.balloon { - resources.set_balloon_device(balloon_config)?; + if let Some(balloon_spec) = vmm_spec.balloon { + resources.set_balloon_device(balloon_spec)?; } // Init the data store from file, if present. @@ -201,38 +199,38 @@ impl VmResources { info!("Successfully added metadata to mmds from file"); } - if let Some(mmds_config) = vmm_config.mmds_config { - resources.set_mmds_config(mmds_config, &instance_info.id)?; + if let Some(mmds_spec) = vmm_spec.mmds_spec { + resources.set_mmds_config(mmds_spec, &instance_info.id)?; } - if let Some(entropy_device_config) = vmm_config.entropy { - resources.build_entropy_device(entropy_device_config)?; + if let Some(entropy_device_spec) = vmm_spec.entropy { + resources.build_entropy_device(entropy_device_spec)?; } - for pmem_config in vmm_config.pmem_devices.into_iter() { - resources.build_pmem_device(pmem_config)?; + for pmem_spec in vmm_spec.pmem_devices.into_iter() { + resources.build_pmem_device(pmem_spec)?; } - if let Some(serial_cfg) = vmm_config.serial_config { - resources.serial_out_path = serial_cfg.serial_out_path; + if let Some(serial_spec) = vmm_spec.serial_spec { + resources.serial_out_path = serial_spec.serial_out_path; } - if let Some(memory_hotplug_config) = vmm_config.memory_hotplug { - resources.set_memory_hotplug_config(memory_hotplug_config)?; + if let Some(memory_hotplug_spec) = vmm_spec.memory_hotplug { + resources.set_memory_hotplug_config(memory_hotplug_spec)?; } Ok(resources) } /// If not initialised, create the mmds data store with the default config. - pub fn mmds_or_default(&mut self) -> Result<&Arc>, MmdsConfigError> { + pub fn mmds_or_default(&mut self) -> Result<&Arc>, MmdsSpecError> { Ok(self .mmds .get_or_insert(Arc::new(Mutex::new(Mmds::try_new(self.mmds_size_limit)?)))) } /// If not initialised, create the mmds data store with the default config. - pub fn locked_mmds_or_default(&mut self) -> Result, MmdsConfigError> { + pub fn locked_mmds_or_default(&mut self) -> Result, MmdsSpecError> { let mmds = self.mmds_or_default()?; Ok(mmds.lock().expect("Poisoned lock")) } @@ -240,15 +238,15 @@ impl VmResources { /// Add a custom CPU template to the VM resources /// to configure vCPUs. pub fn set_custom_cpu_template(&mut self, cpu_template: CustomCpuTemplate) { - self.machine_config.set_custom_cpu_template(cpu_template); + self.machine_spec.set_custom_cpu_template(cpu_template); } - /// Updates the configuration of the microVM. - pub fn update_machine_config( + /// Updates the specification of the microVM. + pub fn update_machine_spec( &mut self, - update: &MachineConfigUpdate, - ) -> Result<(), MachineConfigError> { - let updated = self.machine_config.update(update)?; + update: &MachineSpecUpdate, + ) -> Result<(), MachineSpecError> { + let updated = self.machine_spec.update(update)?; // The VM cannot have a memory size smaller than the target size // of the balloon device, if present. @@ -257,25 +255,25 @@ impl VmResources { < self .balloon .get_config() - .map_err(|_| MachineConfigError::InvalidVmState)? + .map_err(|_| MachineSpecError::InvalidVmState)? .amount_mib as usize { - return Err(MachineConfigError::IncompatibleBalloonSize); + return Err(MachineSpecError::IncompatibleBalloonSize); } - self.machine_config = updated; + self.machine_spec = updated; Ok(()) } - // Repopulate the MmdsConfig based on information from the data store + // Repopulate the MmdsSpec based on information from the data store // and the associated net devices. - fn mmds_config(&self) -> Option { + fn mmds_spec(&self) -> Option { // If the data store is not initialised, we can be sure that the user did not configure // mmds. let mmds = self.mmds.as_ref()?; - let mut mmds_config = None; + let mut mmds_spec = None; let net_devs_with_mmds: Vec<_> = self .net_builder .iter() @@ -284,7 +282,7 @@ impl VmResources { if !net_devs_with_mmds.is_empty() { let mmds_guard = mmds.lock().expect("Poisoned lock"); - let mut inner_mmds_config = MmdsConfig { + let mut inner_mmds_spec = MmdsSpec { version: mmds_guard.version(), network_interfaces: vec![], ipv4_address: None, @@ -293,43 +291,40 @@ impl VmResources { for net_dev in net_devs_with_mmds { let net = net_dev.lock().unwrap(); - inner_mmds_config.network_interfaces.push(net.id().clone()); + inner_mmds_spec.network_interfaces.push(net.id().clone()); // Only need to get one ip address, as they will all be equal. - if inner_mmds_config.ipv4_address.is_none() { + if inner_mmds_spec.ipv4_address.is_none() { // Safe to unwrap the mmds_ns as the filter() explicitly checks for // its existence. - inner_mmds_config.ipv4_address = Some(net.mmds_ns().unwrap().ipv4_addr()); + inner_mmds_spec.ipv4_address = Some(net.mmds_ns().unwrap().ipv4_addr()); } } - mmds_config = Some(inner_mmds_config); + mmds_spec = Some(inner_mmds_spec); } - mmds_config + mmds_spec } /// Sets a balloon device to be attached when the VM starts. - pub fn set_balloon_device( - &mut self, - config: BalloonDeviceConfig, - ) -> Result<(), BalloonConfigError> { + pub fn set_balloon_device(&mut self, spec: BalloonDeviceSpec) -> Result<(), BalloonSpecError> { // The balloon cannot have a target size greater than the size of // the guest memory. - if config.amount_mib as usize > self.machine_config.mem_size_mib { - return Err(BalloonConfigError::TooManyPagesRequested); + if spec.amount_mib as usize > self.machine_spec.mem_size_mib { + return Err(BalloonSpecError::TooManyPagesRequested); } - self.balloon.set(config) + self.balloon.set(spec) } /// Obtains the boot source hooks (kernel fd, command line creation and validation). pub fn build_boot_source( &mut self, - boot_source_cfg: BootSourceConfig, - ) -> Result<(), BootSourceConfigError> { + boot_source_spec: BootSourceSpec, + ) -> Result<(), BootSourceSpecError> { self.boot_source = BootSource { - builder: Some(BootConfig::new(&boot_source_cfg)?), - config: boot_source_cfg, + builder: Some(BootConfig::new(&boot_source_spec)?), + spec: boot_source_spec, }; Ok(()) @@ -340,58 +335,58 @@ impl VmResources { // If the drive_id does not exist, a new Block Device Config is added to the list. pub fn set_block_device( &mut self, - block_device_config: BlockDeviceConfig, + block_device_spec: BlockDeviceSpec, ) -> Result<(), DriveError> { let has_pmem_root = self.pmem.has_root_device(); - self.block.insert(block_device_config, has_pmem_root) + self.block.insert(block_device_spec, has_pmem_root) } /// Builds a network device to be attached when the VM starts. pub fn build_net_device( &mut self, - body: NetworkInterfaceConfig, + body: NetworkInterfaceSpec, ) -> Result<(), NetworkInterfaceError> { let _ = self.net_builder.build(body)?; Ok(()) } /// Sets a vsock device to be attached when the VM starts. - pub fn set_vsock_device(&mut self, config: VsockDeviceConfig) -> Result<(), VsockConfigError> { - self.vsock.insert(config) + pub fn set_vsock_device(&mut self, spec: VsockDeviceSpec) -> Result<(), VsockSpecError> { + self.vsock.insert(spec) } /// Builds an entropy device to be attached when the VM starts. pub fn build_entropy_device( &mut self, - body: EntropyDeviceConfig, + entropy_spec: EntropyDeviceSpec, ) -> Result<(), EntropyDeviceError> { - self.entropy.insert(body) + self.entropy.insert(entropy_spec) } /// Builds a pmem device to be attached when the VM starts. - pub fn build_pmem_device(&mut self, body: PmemConfig) -> Result<(), PmemConfigError> { + pub fn build_pmem_device(&mut self, pmem_spec: PmemSpec) -> Result<(), PmemSpecError> { let has_block_root = self.block.has_root_device(); - self.pmem.build(body, has_block_root) + self.pmem.build(pmem_spec, has_block_root) } /// Sets the memory hotplug configuration. pub fn set_memory_hotplug_config( &mut self, - config: MemoryHotplugConfig, - ) -> Result<(), MemoryHotplugConfigError> { - config.validate()?; - self.memory_hotplug = Some(config); + spec: MemoryHotplugSpec, + ) -> Result<(), MemoryHotplugSpecError> { + spec.validate()?; + self.memory_hotplug = Some(spec); Ok(()) } /// Setter for mmds config. pub fn set_mmds_config( &mut self, - config: MmdsConfig, + spec: MmdsSpec, instance_id: &str, - ) -> Result<(), MmdsConfigError> { - self.set_mmds_network_stack_config(&config)?; - self.set_mmds_basic_config(config.version, config.imds_compat, instance_id)?; + ) -> Result<(), MmdsSpecError> { + self.set_mmds_network_stack_config(&spec)?; + self.set_mmds_basic_config(spec.version, spec.imds_compat, instance_id)?; Ok(()) } @@ -402,7 +397,7 @@ impl VmResources { version: MmdsVersion, imds_compat: bool, instance_id: &str, - ) -> Result<(), MmdsConfigError> { + ) -> Result<(), MmdsSpecError> { let mut mmds_guard = self.locked_mmds_or_default()?; mmds_guard.set_version(version); mmds_guard.set_imds_compat(imds_compat); @@ -413,21 +408,18 @@ impl VmResources { // Updates MMDS Network Stack for network interfaces to allow forwarding // requests to MMDS (or not). - fn set_mmds_network_stack_config( - &mut self, - config: &MmdsConfig, - ) -> Result<(), MmdsConfigError> { + fn set_mmds_network_stack_config(&mut self, spec: &MmdsSpec) -> Result<(), MmdsSpecError> { // Check IPv4 address validity. - let ipv4_addr = match config.ipv4_addr() { + let ipv4_addr = match spec.ipv4_addr() { Some(ipv4_addr) if is_link_local_valid(ipv4_addr) => Ok(ipv4_addr), None => Ok(MmdsNetworkStack::default_ipv4_addr()), - _ => Err(MmdsConfigError::InvalidIpv4Addr), + _ => Err(MmdsSpecError::InvalidIpv4Addr), }?; - let network_interfaces = config.network_interfaces(); + let network_interfaces = spec.network_interfaces(); // Ensure that at least one network ID is specified. if network_interfaces.is_empty() { - return Err(MmdsConfigError::EmptyNetworkIfaceList); + return Err(MmdsSpecError::EmptyNetworkIfaceList); } // Ensure all interface IDs specified correspond to existing net devices. @@ -437,7 +429,7 @@ impl VmResources { .map(|device| device.lock().expect("Poisoned lock").id().clone()) .any(|x| &x == id) }) { - return Err(MmdsConfigError::InvalidNetworkInterfaceId); + return Err(MmdsSpecError::InvalidNetworkInterfaceId); } // Safe to unwrap because we've just made sure that it's initialised. @@ -484,14 +476,14 @@ impl VmResources { if vhost_user_device_used { memory::memfd_backed( regions, - self.machine_config.track_dirty_pages, - self.machine_config.huge_pages, + self.machine_spec.track_dirty_pages, + self.machine_spec.huge_pages, ) } else { memory::anonymous( regions.iter().copied(), - self.machine_config.track_dirty_pages, - self.machine_config.huge_pages, + self.machine_spec.track_dirty_pages, + self.machine_spec.huge_pages, ) } } @@ -499,7 +491,7 @@ impl VmResources { /// Allocates guest memory in a configuration most appropriate for these [`VmResources`]. pub fn allocate_guest_memory(&self) -> Result, MemoryError> { let regions = - crate::arch::arch_memory_regions(mib_to_bytes(self.machine_config.mem_size_mib)); + crate::arch::arch_memory_regions(mib_to_bytes(self.machine_spec.mem_size_mib)); self.allocate_memory_regions(®ions) } @@ -516,23 +508,23 @@ impl VmResources { } } -impl From<&VmResources> for VmmConfig { +impl From<&VmResources> for VmmSpec { fn from(resources: &VmResources) -> Self { - VmmConfig { + VmmSpec { balloon: resources.balloon.get_config().ok(), drives: resources.block.configs(), - boot_source: resources.boot_source.config.clone(), + boot_source: resources.boot_source.spec.clone(), cpu_config: None, logger: None, - machine_config: Some(resources.machine_config.clone()), + machine_spec: Some(resources.machine_spec.clone()), metrics: None, - mmds_config: resources.mmds_config(), + mmds_spec: resources.mmds_spec(), network_interfaces: resources.net_builder.configs(), - vsock: resources.vsock.config(), + vsock: resources.vsock.spec(), entropy: resources.entropy.config(), pmem_devices: resources.pmem.configs(), - // serial_config is marked serde(skip) so that it doesnt end up in snapshots. - serial_config: None, + // serial_spec is marked serde(skip) so that it doesnt end up in snapshots. + serial_spec: None, memory_hotplug: resources.memory_hotplug.clone(), } } @@ -557,17 +549,17 @@ mod tests { use crate::devices::virtio::vsock::VSOCK_DEV_ID; use crate::resources::VmResources; use crate::utils::net::mac::MacAddr; - use crate::vmm_config::RateLimiterConfig; + use crate::vmm_config::RateLimiterSpec; use crate::vmm_config::boot_source::{ - BootConfig, BootSource, BootSourceConfig, DEFAULT_KERNEL_CMDLINE, + BootConfig, BootSource, BootSourceSpec, DEFAULT_KERNEL_CMDLINE, }; - use crate::vmm_config::drive::{BlockBuilder, BlockDeviceConfig}; - use crate::vmm_config::machine_config::{HugePageConfig, MachineConfig, MachineConfigError}; - use crate::vmm_config::net::{NetBuilder, NetworkInterfaceConfig}; - use crate::vmm_config::vsock::tests::default_config; + use crate::vmm_config::drive::{BlockBuilder, BlockDeviceSpec}; + use crate::vmm_config::machine_config::{HugePageConfig, MachineSpec, MachineSpecError}; + use crate::vmm_config::net::{NetBuilder, NetworkInterfaceSpec}; + use crate::vmm_config::vsock::tests::default_spec; - fn default_net_cfg() -> NetworkInterfaceConfig { - NetworkInterfaceConfig { + fn default_net_spec() -> NetworkInterfaceSpec { + NetworkInterfaceSpec { iface_id: "net_if1".to_string(), // TempFile::new_with_prefix("") generates a random file name used as random net_if // name. @@ -578,22 +570,22 @@ mod tests { .unwrap() .to_string(), guest_mac: Some(MacAddr::from_str("01:23:45:67:89:0a").unwrap()), - rx_rate_limiter: Some(RateLimiterConfig::default()), - tx_rate_limiter: Some(RateLimiterConfig::default()), + rx_rate_limiter: Some(RateLimiterSpec::default()), + tx_rate_limiter: Some(RateLimiterSpec::default()), } } fn default_net_builder() -> NetBuilder { let mut net_builder = NetBuilder::new(); - net_builder.build(default_net_cfg()).unwrap(); + net_builder.build(default_net_spec()).unwrap(); net_builder } - fn default_block_cfg() -> (BlockDeviceConfig, TempFile) { + fn default_block_spec() -> (BlockDeviceSpec, TempFile) { let tmp_file = TempFile::new().unwrap(); ( - BlockDeviceConfig { + BlockDeviceSpec { drive_id: "block1".to_string(), partuuid: Some("0eaa91a0-01".to_string()), is_root_device: false, @@ -601,7 +593,7 @@ mod tests { is_read_only: Some(false), path_on_host: Some(tmp_file.as_path().to_str().unwrap().to_string()), - rate_limiter: Some(RateLimiterConfig::default()), + rate_limiter: Some(RateLimiterSpec::default()), file_engine_type: None, socket: None, @@ -612,8 +604,8 @@ mod tests { fn default_blocks() -> BlockBuilder { let mut blocks = BlockBuilder::new(); - let (cfg, _file) = default_block_cfg(); - blocks.insert(cfg, false).unwrap(); + let (spec, _file) = default_block_spec(); + blocks.insert(spec, false).unwrap(); blocks } @@ -622,7 +614,7 @@ mod tests { linux_loader::cmdline::Cmdline::try_from(DEFAULT_KERNEL_CMDLINE, 4096).unwrap(); let tmp_file = TempFile::new().unwrap(); BootSource { - config: BootSourceConfig::default(), + spec: BootSourceSpec::default(), builder: Some(BootConfig { cmdline: kernel_cmdline, kernel_file: File::open(tmp_file.as_path()).unwrap(), @@ -633,7 +625,7 @@ mod tests { fn default_vm_resources() -> VmResources { VmResources { - machine_config: MachineConfig::default(), + machine_spec: MachineSpec::default(), boot_source: default_boot_cfg(), block: default_blocks(), vsock: Default::default(), @@ -713,7 +705,7 @@ mod tests { assert!( matches!( error, - ResourcesError::BootSource(BootSourceConfigError::InvalidKernelPath(_)) + ResourcesError::BootSource(BootSourceSpecError::InvalidKernelPath(_)) ), "{:?}", error @@ -830,7 +822,7 @@ mod tests { assert!( matches!( error, - ResourcesError::MachineConfig(MachineConfigError::InvalidMemorySize) + ResourcesError::MachineSpec(MachineSpecError::InvalidMemorySize) ), "{:?}", error @@ -908,7 +900,7 @@ mod tests { assert!( matches!( error, - ResourcesError::Metrics(MetricsConfigError::InitializationFailure { .. }) + ResourcesError::Metrics(MetricsSpecError::InitializationFailure { .. }) ), "{:?}", error @@ -1190,7 +1182,7 @@ mod tests { ) .unwrap(); assert_eq!( - vm_resources.machine_config.cpu_template, + vm_resources.machine_spec.cpu_template, Some(CpuTemplateType::Custom(CustomCpuTemplate::default())) ); } @@ -1251,9 +1243,9 @@ mod tests { ) .unwrap(); - let initial_vmm_config = serde_json::from_str::(&json).unwrap(); - let vmm_config: VmmConfig = (&resources).into(); - assert_eq!(initial_vmm_config, vmm_config); + let initial_vmm_spec = serde_json::from_str::(&json).unwrap(); + let vmm_spec: VmmSpec = (&resources).into(); + assert_eq!(initial_vmm_spec, vmm_spec); } { @@ -1266,9 +1258,9 @@ mod tests { ) .unwrap(); - let initial_vmm_config = serde_json::from_str::(&json).unwrap(); - let vmm_config: VmmConfig = (&resources).into(); - assert_eq!(initial_vmm_config, vmm_config); + let initial_vmm_spec = serde_json::from_str::(&json).unwrap(); + let vmm_spec: VmmSpec = (&resources).into(); + assert_eq!(initial_vmm_spec, vmm_spec); } } @@ -1327,9 +1319,9 @@ mod tests { ) .unwrap(); - let initial_vmm_config = serde_json::from_str::(&json).unwrap(); - let vmm_config: VmmConfig = (&resources).into(); - assert_eq!(initial_vmm_config, vmm_config); + let initial_vmm_spec = serde_json::from_str::(&json).unwrap(); + let vmm_spec: VmmSpec = (&resources).into(); + assert_eq!(initial_vmm_spec, vmm_spec); } // Multiple interfaces configured for MMDS. @@ -1387,16 +1379,16 @@ mod tests { ) .unwrap(); - let initial_vmm_config = serde_json::from_str::(&json).unwrap(); - let vmm_config: VmmConfig = (&resources).into(); - assert_eq!(initial_vmm_config, vmm_config); + let initial_vmm_spec = serde_json::from_str::(&json).unwrap(); + let vmm_spec: VmmSpec = (&resources).into(); + assert_eq!(initial_vmm_spec, vmm_spec); } } #[test] fn test_update_machine_config() { let mut vm_resources = default_vm_resources(); - let mut aux_vm_config = MachineConfigUpdate { + let mut aux_vm_spec_update = MachineSpecUpdate { vcpu_count: Some(32), mem_size_mib: Some(512), smt: Some(false), @@ -1411,57 +1403,61 @@ mod tests { }; assert_ne!( - MachineConfigUpdate::from(vm_resources.machine_config.clone()), - aux_vm_config + MachineSpecUpdate::from(vm_resources.machine_spec.clone()), + aux_vm_spec_update ); - vm_resources.update_machine_config(&aux_vm_config).unwrap(); + vm_resources + .update_machine_spec(&aux_vm_spec_update) + .unwrap(); assert_eq!( - MachineConfigUpdate::from(vm_resources.machine_config.clone()), - aux_vm_config + MachineSpecUpdate::from(vm_resources.machine_spec.clone()), + aux_vm_spec_update ); // Invalid vcpu count. - aux_vm_config.vcpu_count = Some(0); + aux_vm_spec_update.vcpu_count = Some(0); assert_eq!( - vm_resources.update_machine_config(&aux_vm_config), - Err(MachineConfigError::InvalidVcpuCount) + vm_resources.update_machine_spec(&aux_vm_spec_update), + Err(MachineSpecError::InvalidVcpuCount) ); - aux_vm_config.vcpu_count = Some(33); + aux_vm_spec_update.vcpu_count = Some(33); assert_eq!( - vm_resources.update_machine_config(&aux_vm_config), - Err(MachineConfigError::InvalidVcpuCount) + vm_resources.update_machine_spec(&aux_vm_spec_update), + Err(MachineSpecError::InvalidVcpuCount) ); // Check that SMT is not supported on aarch64, and that on x86_64 enabling it requires vcpu // count to be even. - aux_vm_config.smt = Some(true); + aux_vm_spec_update.smt = Some(true); #[cfg(target_arch = "aarch64")] assert_eq!( - vm_resources.update_machine_config(&aux_vm_config), - Err(MachineConfigError::SmtNotSupported) + vm_resources.update_machine_spec(&aux_vm_spec_update), + Err(MachineSpecError::SmtNotSupported) ); - aux_vm_config.vcpu_count = Some(3); + aux_vm_spec_update.vcpu_count = Some(3); #[cfg(target_arch = "x86_64")] assert_eq!( - vm_resources.update_machine_config(&aux_vm_config), - Err(MachineConfigError::InvalidVcpuCount) + vm_resources.update_machine_spec(&aux_vm_spec_update), + Err(MachineSpecError::InvalidVcpuCount) ); - aux_vm_config.vcpu_count = Some(32); + aux_vm_spec_update.vcpu_count = Some(32); #[cfg(target_arch = "x86_64")] - vm_resources.update_machine_config(&aux_vm_config).unwrap(); - aux_vm_config.smt = Some(false); + vm_resources + .update_machine_spec(&aux_vm_spec_update) + .unwrap(); + aux_vm_spec_update.smt = Some(false); // Invalid mem_size_mib. - aux_vm_config.mem_size_mib = Some(0); + aux_vm_spec_update.mem_size_mib = Some(0); assert_eq!( - vm_resources.update_machine_config(&aux_vm_config), - Err(MachineConfigError::InvalidMemorySize) + vm_resources.update_machine_spec(&aux_vm_spec_update), + Err(MachineSpecError::InvalidMemorySize) ); // Incompatible mem_size_mib with balloon size. - vm_resources.machine_config.mem_size_mib = 128; + vm_resources.machine_spec.mem_size_mib = 128; vm_resources - .set_balloon_device(BalloonDeviceConfig { + .set_balloon_device(BalloonDeviceSpec { amount_mib: 100, deflate_on_oom: false, stats_polling_interval_s: 0, @@ -1469,39 +1465,43 @@ mod tests { free_page_reporting: false, }) .unwrap(); - aux_vm_config.mem_size_mib = Some(90); + aux_vm_spec_update.mem_size_mib = Some(90); assert_eq!( - vm_resources.update_machine_config(&aux_vm_config), - Err(MachineConfigError::IncompatibleBalloonSize) + vm_resources.update_machine_spec(&aux_vm_spec_update), + Err(MachineSpecError::IncompatibleBalloonSize) ); // mem_size_mib compatible with balloon size. - aux_vm_config.mem_size_mib = Some(256); - vm_resources.update_machine_config(&aux_vm_config).unwrap(); + aux_vm_spec_update.mem_size_mib = Some(256); + vm_resources + .update_machine_spec(&aux_vm_spec_update) + .unwrap(); // mem_size_mib incompatible with huge pages configuration - aux_vm_config.mem_size_mib = Some(129); - aux_vm_config.huge_pages = Some(HugePageConfig::Hugetlbfs2M); + aux_vm_spec_update.mem_size_mib = Some(129); + aux_vm_spec_update.huge_pages = Some(HugePageConfig::Hugetlbfs2M); assert_eq!( vm_resources - .update_machine_config(&aux_vm_config) + .update_machine_spec(&aux_vm_spec_update) .unwrap_err(), - MachineConfigError::InvalidMemorySize + MachineSpecError::InvalidMemorySize ); // mem_size_mib compatible with huge page configuration - aux_vm_config.mem_size_mib = Some(2048); + aux_vm_spec_update.mem_size_mib = Some(2048); // Remove the balloon device config that's added by `default_vm_resources` as it would // trigger the "ballooning incompatible with huge pages" check. vm_resources.balloon = BalloonBuilder::new(); - vm_resources.update_machine_config(&aux_vm_config).unwrap(); + vm_resources + .update_machine_spec(&aux_vm_spec_update) + .unwrap(); } #[test] fn test_set_balloon_device() { let mut vm_resources = default_vm_resources(); vm_resources.balloon = BalloonBuilder::new(); - let mut new_balloon_cfg = BalloonDeviceConfig { + let mut new_balloon_spec = BalloonDeviceSpec { amount_mib: 100, deflate_on_oom: false, stats_polling_interval_s: 0, @@ -1510,25 +1510,25 @@ mod tests { }; assert!(vm_resources.balloon.get().is_none()); vm_resources - .set_balloon_device(new_balloon_cfg.clone()) + .set_balloon_device(new_balloon_spec.clone()) .unwrap(); - let actual_balloon_cfg = vm_resources.balloon.get_config().unwrap(); - assert_eq!(actual_balloon_cfg.amount_mib, new_balloon_cfg.amount_mib); + let actual_balloon_spec = vm_resources.balloon.get_config().unwrap(); + assert_eq!(actual_balloon_spec.amount_mib, new_balloon_spec.amount_mib); assert_eq!( - actual_balloon_cfg.deflate_on_oom, - new_balloon_cfg.deflate_on_oom + actual_balloon_spec.deflate_on_oom, + new_balloon_spec.deflate_on_oom ); assert_eq!( - actual_balloon_cfg.stats_polling_interval_s, - new_balloon_cfg.stats_polling_interval_s + actual_balloon_spec.stats_polling_interval_s, + new_balloon_spec.stats_polling_interval_s ); let mut vm_resources = default_vm_resources(); vm_resources.balloon = BalloonBuilder::new(); - new_balloon_cfg.amount_mib = 256; + new_balloon_spec.amount_mib = 256; vm_resources - .set_balloon_device(new_balloon_cfg) + .set_balloon_device(new_balloon_spec) .unwrap_err(); } @@ -1536,22 +1536,22 @@ mod tests { fn test_set_entropy_device() { let mut vm_resources = default_vm_resources(); vm_resources.entropy = EntropyDeviceBuilder::new(); - let entropy_device_cfg = EntropyDeviceConfig::default(); + let entropy_device_spec = EntropyDeviceSpec::default(); assert!(vm_resources.entropy.get().is_none()); vm_resources - .build_entropy_device(entropy_device_cfg.clone()) + .build_entropy_device(entropy_device_spec.clone()) .unwrap(); - let actual_entropy_cfg = vm_resources.entropy.config().unwrap(); - assert_eq!(actual_entropy_cfg, entropy_device_cfg); + let actual_entropy_spec = vm_resources.entropy.config().unwrap(); + assert_eq!(actual_entropy_spec, entropy_device_spec); } #[test] fn test_set_boot_source() { let tmp_file = TempFile::new().unwrap(); let cmdline = "reboot=k panic=1 pci=off nomodule 8250.nr_uarts=0"; - let expected_boot_cfg = BootSourceConfig { + let expected_boot_spec = BootSourceSpec { kernel_image_path: String::from(tmp_file.as_path().to_str().unwrap()), initrd_path: Some(String::from(tmp_file.as_path().to_str().unwrap())), boot_args: Some(cmdline.to_string()), @@ -1584,7 +1584,7 @@ mod tests { tmp_ino ); - vm_resources.build_boot_source(expected_boot_cfg).unwrap(); + vm_resources.build_boot_source(expected_boot_spec).unwrap(); let boot_source_builder = vm_resources.boot_source.builder.unwrap(); assert_eq!( boot_source_builder @@ -1613,12 +1613,14 @@ mod tests { #[test] fn test_set_block_device() { let mut vm_resources = default_vm_resources(); - let (mut new_block_device_cfg, _file) = default_block_cfg(); + let (mut new_block_device_spec, _file) = default_block_spec(); let tmp_file = TempFile::new().unwrap(); - new_block_device_cfg.drive_id = "block2".to_string(); - new_block_device_cfg.path_on_host = Some(tmp_file.as_path().to_str().unwrap().to_string()); + new_block_device_spec.drive_id = "block2".to_string(); + new_block_device_spec.path_on_host = Some(tmp_file.as_path().to_str().unwrap().to_string()); assert_eq!(vm_resources.block.devices.len(), 1); - vm_resources.set_block_device(new_block_device_cfg).unwrap(); + vm_resources + .set_block_device(new_block_device_spec) + .unwrap(); assert_eq!(vm_resources.block.devices.len(), 2); } @@ -1627,11 +1629,11 @@ mod tests { let mut vm_resources = default_vm_resources(); let mut tmp_sock_file = TempFile::new().unwrap(); tmp_sock_file.remove().unwrap(); - let new_vsock_cfg = default_config(&tmp_sock_file); + let new_vsock_spec = default_spec(&tmp_sock_file); assert!(vm_resources.vsock.get().is_none()); - vm_resources.set_vsock_device(new_vsock_cfg).unwrap(); - let actual_vsock_cfg = vm_resources.vsock.get().unwrap(); - assert_eq!(actual_vsock_cfg.lock().unwrap().id(), VSOCK_DEV_ID); + vm_resources.set_vsock_device(new_vsock_spec).unwrap(); + let actual_vsock_spec = vm_resources.vsock.get().unwrap(); + assert_eq!(actual_vsock_spec.lock().unwrap().id(), VSOCK_DEV_ID); } #[test] @@ -1639,13 +1641,13 @@ mod tests { let mut vm_resources = default_vm_resources(); // Clone the existing net config in order to obtain a new one. - let mut new_net_device_cfg = default_net_cfg(); - new_net_device_cfg.iface_id = "new_net_if".to_string(); - new_net_device_cfg.guest_mac = Some(MacAddr::from_str("01:23:45:67:89:0c").unwrap()); - new_net_device_cfg.host_dev_name = "dummy_path2".to_string(); + let mut new_net_device_spec = default_net_spec(); + new_net_device_spec.iface_id = "new_net_if".to_string(); + new_net_device_spec.guest_mac = Some(MacAddr::from_str("01:23:45:67:89:0c").unwrap()); + new_net_device_spec.host_dev_name = "dummy_path2".to_string(); assert_eq!(vm_resources.net_builder.len(), 1); - vm_resources.build_net_device(new_net_device_cfg).unwrap(); + vm_resources.build_net_device(new_net_device_spec).unwrap(); assert_eq!(vm_resources.net_builder.len(), 2); } @@ -1655,13 +1657,13 @@ mod tests { let tmp_file = TempFile::new().unwrap(); tmp_file.as_file().set_len(0x1000).unwrap(); - let cfg = PmemConfig { + let spec = PmemSpec { id: "pmem".to_string(), path_on_host: tmp_file.as_path().to_str().unwrap().to_string(), ..Default::default() }; assert_eq!(vm_resources.pmem.devices.len(), 0); - vm_resources.build_pmem_device(cfg).unwrap(); + vm_resources.build_pmem_device(spec).unwrap(); assert_eq!(vm_resources.pmem.devices.len(), 1); } } diff --git a/src/vmm/src/rpc_interface.rs b/src/vmm/src/rpc_interface.rs index fdd0862a9d4..0c811c40c8c 100644 --- a/src/vmm/src/rpc_interface.rs +++ b/src/vmm/src/rpc_interface.rs @@ -19,29 +19,28 @@ use crate::devices::virtio::mem::VirtioMemStatus; use crate::logger::{LoggerConfig, info, warn, *}; use crate::mmds::data_store::{self, Mmds}; use crate::persist::{CreateSnapshotError, RestoreFromSnapshotError, VmInfo}; -use crate::resources::VmmConfig; +use crate::resources::VmmSpec; use crate::seccomp::BpfThreadMap; use crate::vmm_config::balloon::{ - BalloonConfigError, BalloonDeviceConfig, BalloonStats, BalloonUpdateConfig, - BalloonUpdateStatsConfig, + BalloonDeviceSpec, BalloonSpecError, BalloonStats, BalloonUpdateSpec, BalloonUpdateStatsSpec, }; -use crate::vmm_config::boot_source::{BootSourceConfig, BootSourceConfigError}; -use crate::vmm_config::drive::{BlockDeviceConfig, BlockDeviceUpdateConfig, DriveError}; -use crate::vmm_config::entropy::{EntropyDeviceConfig, EntropyDeviceError}; +use crate::vmm_config::boot_source::{BootSourceSpec, BootSourceSpecError}; +use crate::vmm_config::drive::{BlockDeviceSpec, BlockDeviceUpdateSpec, DriveError}; +use crate::vmm_config::entropy::{EntropyDeviceError, EntropyDeviceSpec}; use crate::vmm_config::instance_info::InstanceInfo; -use crate::vmm_config::machine_config::{MachineConfig, MachineConfigError, MachineConfigUpdate}; +use crate::vmm_config::machine_config::{MachineSpec, MachineSpecError, MachineSpecUpdate}; use crate::vmm_config::memory_hotplug::{ - MemoryHotplugConfig, MemoryHotplugConfigError, MemoryHotplugSizeUpdate, + MemoryHotplugSizeUpdate, MemoryHotplugSpec, MemoryHotplugSpecError, }; -use crate::vmm_config::metrics::{MetricsConfig, MetricsConfigError}; -use crate::vmm_config::mmds::{MmdsConfig, MmdsConfigError}; +use crate::vmm_config::metrics::{MetricsSpec, MetricsSpecError}; +use crate::vmm_config::mmds::{MmdsSpec, MmdsSpecError}; use crate::vmm_config::net::{ - NetworkInterfaceConfig, NetworkInterfaceError, NetworkInterfaceUpdateConfig, + NetworkInterfaceError, NetworkInterfaceSpec, NetworkInterfaceUpdateSpec, }; -use crate::vmm_config::pmem::{PmemConfig, PmemConfigError}; -use crate::vmm_config::serial::SerialConfig; +use crate::vmm_config::pmem::{PmemSpec, PmemSpecError}; +use crate::vmm_config::serial::SerialSpec; use crate::vmm_config::snapshot::{CreateSnapshotParams, LoadSnapshotParams, SnapshotType}; -use crate::vmm_config::vsock::{VsockConfigError, VsockDeviceConfig}; +use crate::vmm_config::vsock::{VsockDeviceSpec, VsockSpecError}; use crate::vmm_config::{self, RateLimiterUpdate}; /// This enum represents the public interface of the VMM. Each action contains various @@ -50,43 +49,43 @@ use crate::vmm_config::{self, RateLimiterUpdate}; pub enum VmmAction { /// Configure the boot source of the microVM using as input the `ConfigureBootSource`. This /// action can only be called before the microVM has booted. - ConfigureBootSource(BootSourceConfig), + ConfigureBootSource(BootSourceSpec), /// Configure the logger using as input the `LoggerConfig`. This action can only be called /// before the microVM has booted. ConfigureLogger(LoggerConfig), - /// Configure the metrics using as input the `MetricsConfig`. This action can only be called + /// Configure the metrics using as input the `MetricsSpec`. This action can only be called /// before the microVM has booted. - ConfigureMetrics(MetricsConfig), + ConfigureMetrics(MetricsSpec), /// Configure the serial device. This action can only be called before the microVM has booted. - ConfigureSerial(SerialConfig), + ConfigureSerial(SerialSpec), /// Create a snapshot using as input the `CreateSnapshotParams`. This action can only be called /// after the microVM has booted and only when the microVM is in `Paused` state. CreateSnapshot(CreateSnapshotParams), - /// Get the balloon device configuration. - GetBalloonConfig, + /// Get the balloon device specification. + GetBalloonSpec, /// Get the ballon device latest statistics. GetBalloonStats, - /// Get complete microVM configuration in JSON format. - GetFullVmConfig, + /// Get complete microVM specification in JSON format. + GetFullVmSpec, /// Get MMDS contents. GetMMDS, - /// Get the machine configuration of the microVM. - GetVmMachineConfig, + /// Get the machine specification of the microVM. + GetVmMachineSpec, /// Get microVM instance information. GetVmInstanceInfo, /// Get microVM version. GetVmmVersion, /// Flush the metrics. This action can only be called after the logger has been configured. FlushMetrics, - /// Add a new block device or update one that already exists using the `BlockDeviceConfig` as + /// Add a new block device or update one that already exists using the `BlockDeviceSpec` as /// input. This action can only be called before the microVM has booted. - InsertBlockDevice(BlockDeviceConfig), + InsertBlockDevice(BlockDeviceSpec), /// Add a virtio-pmem device. - InsertPmemDevice(PmemConfig), + InsertPmemDevice(PmemSpec), /// Add a new network interface config or update one that already exists using the - /// `NetworkInterfaceConfig` as input. This action can only be called before the microVM has + /// `NetworkInterfaceSpec` as input. This action can only be called before the microVM has /// booted. - InsertNetworkDevice(NetworkInterfaceConfig), + InsertNetworkDevice(NetworkInterfaceSpec), /// Load the microVM state using as input the `LoadSnapshotParams`. This action can only be /// called before the microVM has booted. If this action is successful, the loaded microVM will /// be in `Paused` state. Should change this state to `Resumed` for the microVM to run. @@ -102,23 +101,23 @@ pub enum VmmAction { /// Resume the guest, by resuming the microVM VCPUs. Resume, /// Set the balloon device or update the one that already exists using the - /// `BalloonDeviceConfig` as input. This action can only be called before the microVM + /// `BalloonDeviceSpec` as input. This action can only be called before the microVM /// has booted. - SetBalloonDevice(BalloonDeviceConfig), - /// Set the MMDS configuration. - SetMmdsConfiguration(MmdsConfig), + SetBalloonDevice(BalloonDeviceSpec), + /// Set the MMDS specification. + SetMmdsSpec(MmdsSpec), /// Set the vsock device or update the one that already exists using the - /// `VsockDeviceConfig` as input. This action can only be called before the microVM has + /// `VsockDeviceSpec` as input. This action can only be called before the microVM has /// booted. - SetVsockDevice(VsockDeviceConfig), - /// Set the entropy device using `EntropyDeviceConfig` as input. This action can only be called + SetVsockDevice(VsockDeviceSpec), + /// Set the entropy device using `EntropyDeviceSpec` as input. This action can only be called /// before the microVM has booted. - SetEntropyDevice(EntropyDeviceConfig), - /// Get the memory hotplug device configuration and status. + SetEntropyDevice(EntropyDeviceSpec), + /// Get the memory hotplug device specification and status. GetMemoryHotplugStatus, - /// Set the memory hotplug device using `MemoryHotplugConfig` as input. This action can only be + /// Set the memory hotplug device using `MemoryHotplugSpec` as input. This action can only be /// called before the microVM has booted. - SetMemoryHotplugDevice(MemoryHotplugConfig), + SetMemoryHotplugDevice(MemoryHotplugSpec), /// Updates the memory hotplug device using `MemoryHotplugConfigUpdate` as input. This action /// can only be called after the microVM has booted. UpdateMemoryHotplugSize(MemoryHotplugSizeUpdate), @@ -129,9 +128,9 @@ pub enum VmmAction { #[cfg(target_arch = "x86_64")] SendCtrlAltDel, /// Update the balloon size, after microVM start. - UpdateBalloon(BalloonUpdateConfig), + UpdateBalloon(BalloonUpdateSpec), /// Update the balloon statistics polling interval, after microVM start. - UpdateBalloonStatistics(BalloonUpdateStatsConfig), + UpdateBalloonStatistics(BalloonUpdateStatsSpec), /// Start a free page hinting run StartFreePageHinting(StartHintingCmd), /// Retrieve the status of the hinting run @@ -139,36 +138,46 @@ pub enum VmmAction { /// Stops a free page hinting run StopFreePageHinting, /// Update existing block device properties such as `path_on_host` or `rate_limiter`. - UpdateBlockDevice(BlockDeviceUpdateConfig), + UpdateBlockDevice(BlockDeviceUpdateSpec), /// Update a network interface, after microVM start. Currently, the only updatable properties /// are the RX and TX rate limiters. - UpdateNetworkInterface(NetworkInterfaceUpdateConfig), + UpdateNetworkInterface(NetworkInterfaceUpdateSpec), /// Update the microVM configuration (memory & vcpu) using `VmUpdateConfig` as input. This /// action can only be called before the microVM has booted. - UpdateMachineConfiguration(MachineConfigUpdate), + UpdateMachineSpec(MachineSpecUpdate), +} + +impl From> for VmmAction +where + F: FnOnce(A) -> VmmAction, + A: vmm_config::StatelessArgs, +{ + fn from(payload: vmm_config::VmmActionPayload) -> Self { + payload.dispatch() + } } /// Wrapper for all errors associated with VMM actions. #[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum VmmActionError { - /// Balloon config error: {0} - BalloonConfig(#[from] BalloonConfigError), + /// Balloon spec error: {0} + BalloonSpec(#[from] BalloonSpecError), /// Balloon update error: {0} BalloonUpdate(VmmError), /// Boot source error: {0} - BootSource(#[from] BootSourceConfigError), + BootSource(#[from] BootSourceSpecError), /// Create snapshot error: {0} CreateSnapshot(#[from] CreateSnapshotError), /// Configure CPU error: {0} ConfigureCpu(#[from] GuestConfigError), - /// Drive config error: {0} - DriveConfig(#[from] DriveError), + /// Drive spec error: {0} + DriveSpec(#[from] DriveError), /// Entropy device error: {0} EntropyDevice(#[from] EntropyDeviceError), /// Pmem device error: {0} - PmemDevice(#[from] PmemConfigError), - /// Memory hotplug config error: {0} - MemoryHotplugConfig(#[from] MemoryHotplugConfigError), + PmemDevice(#[from] PmemSpecError), + /// Memory hotplug spec error: {0} + MemoryHotplugSpec(#[from] MemoryHotplugSpecError), /// Memory hotplug update error: {0} MemoryHotplugUpdate(VmmError), /// Internal VMM error: {0} @@ -177,20 +186,20 @@ pub enum VmmActionError { LoadSnapshot(#[from] LoadSnapshotError), /// Logger error: {0} Logger(#[from] crate::logger::LoggerUpdateError), - /// Machine config error: {0} - MachineConfig(#[from] MachineConfigError), + /// Machine spec error: {0} + MachineSpec(#[from] MachineSpecError), /// Metrics error: {0} - Metrics(#[from] MetricsConfigError), + Metrics(#[from] MetricsSpecError), #[from(ignore)] /// MMDS error: {0} Mmds(#[from] data_store::MmdsDatastoreError), - /// MMMDS config error: {0} - MmdsConfig(#[from] MmdsConfigError), + /// MMDS spec error: {0} + MmdsSpec(#[from] MmdsSpecError), #[from(ignore)] /// MMDS limit exceeded error: {0} MmdsLimitExceeded(data_store::MmdsDatastoreError), - /// Network config error: {0} - NetworkConfig(#[from] NetworkInterfaceError), + /// Network spec error: {0} + NetworkSpec(#[from] NetworkInterfaceError), /// The requested operation is not supported: {0} NotSupported(String), /// The requested operation is not supported after starting the microVM. @@ -199,8 +208,8 @@ pub enum VmmActionError { OperationNotSupportedPreBoot, /// Start microvm error: {0} StartMicrovm(#[from] StartMicrovmError), - /// Vsock config error: {0} - VsockConfig(#[from] VsockConfigError), + /// Vsock spec error: {0} + VsockSpec(#[from] VsockSpecError), } /// The enum represents the response sent by the VMM in case of success. The response is either @@ -208,16 +217,16 @@ pub enum VmmActionError { #[allow(clippy::large_enum_variant)] #[derive(Debug, PartialEq, Eq)] pub enum VmmData { - /// The balloon device configuration. - BalloonConfig(BalloonDeviceConfig), + /// The balloon device specification. + BalloonSpec(BalloonDeviceSpec), /// The latest balloon device statistics. BalloonStats(BalloonStats), /// No data is sent on the channel. Empty, - /// The complete microVM configuration in JSON format. - FullVmConfig(VmmConfig), - /// The microVM configuration represented by `VmConfig`. - MachineConfiguration(MachineConfig), + /// The complete microVM specification in JSON format. + FullVmSpec(VmmSpec), + /// The microVM specification represented by `MachineSpec`. + MachineSpec(MachineSpec), /// Mmds contents. MmdsValue(serde_json::Value), /// The microVM instance information. @@ -304,7 +313,7 @@ impl MmdsRequestHandler for PrebootApiController<'_> { fn mmds(&mut self) -> Result, VmmActionError> { self.vm_resources .locked_mmds_or_default() - .map_err(VmmActionError::MmdsConfig) + .map_err(VmmActionError::MmdsSpec) } } @@ -328,7 +337,7 @@ pub type ApiResponse = Box>; #[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum BuildMicrovmFromRequestsError { /// Configuring MMDS failed: {0}. - ConfigureMmds(#[from] MmdsConfigError), + ConfigureMmds(#[from] MmdsSpecError), /// Populating MMDS from file failed: {0}. PopulateMmds(#[from] data_store::MmdsDatastoreError), /// Loading snapshot failed. @@ -437,50 +446,48 @@ impl<'a> PrebootApiController<'a> { match request { // Supported operations allowed pre-boot. - ConfigureBootSource(config) => self.set_boot_source(config), - ConfigureLogger(logger_cfg) => crate::logger::LOGGER - .update(logger_cfg) + ConfigureBootSource(spec) => self.set_boot_source(spec), + ConfigureLogger(spec) => crate::logger::LOGGER + .update(spec) .map(|()| VmmData::Empty) .map_err(VmmActionError::Logger), - ConfigureMetrics(metrics_cfg) => vmm_config::metrics::init_metrics(metrics_cfg) + ConfigureMetrics(spec) => vmm_config::metrics::init_metrics(spec) .map(|()| VmmData::Empty) .map_err(VmmActionError::Metrics), - ConfigureSerial(serial_cfg) => { - self.vm_resources.serial_out_path = serial_cfg.serial_out_path; + ConfigureSerial(spec) => { + self.vm_resources.serial_out_path = spec.serial_out_path; Ok(VmmData::Empty) } - GetBalloonConfig => self.balloon_config(), - GetFullVmConfig => { + GetBalloonSpec => self.balloon_config(), + GetFullVmSpec => { warn!( "If the VM was restored from snapshot, boot-source, machine-config.smt, and \ machine-config.cpu_template will all be empty." ); - Ok(VmmData::FullVmConfig((&*self.vm_resources).into())) + Ok(VmmData::FullVmSpec((&*self.vm_resources).into())) } GetMMDS => self.get_mmds(), - GetVmMachineConfig => Ok(VmmData::MachineConfiguration( - self.vm_resources.machine_config.clone(), - )), + GetVmMachineSpec => Ok(VmmData::MachineSpec(self.vm_resources.machine_spec.clone())), GetVmInstanceInfo => Ok(VmmData::InstanceInformation(self.instance_info.clone())), GetVmmVersion => Ok(VmmData::VmmVersion(self.instance_info.vmm_version.clone())), - InsertBlockDevice(config) => self.insert_block_device(config), - InsertPmemDevice(config) => self.insert_pmem_device(config), - InsertNetworkDevice(config) => self.insert_net_device(config), - LoadSnapshot(config) => self - .load_snapshot(&config) + InsertBlockDevice(spec) => self.insert_block_device(spec), + InsertPmemDevice(spec) => self.insert_pmem_device(spec), + InsertNetworkDevice(spec) => self.insert_net_device(spec), + LoadSnapshot(load_params) => self + .load_snapshot(&load_params) .map_err(VmmActionError::LoadSnapshot), PatchMMDS(value) => self.patch_mmds(value), PutCpuConfiguration(custom_cpu_template) => { self.set_custom_cpu_template(custom_cpu_template) } PutMMDS(value) => self.put_mmds(value), - SetBalloonDevice(config) => self.set_balloon_device(config), - SetVsockDevice(config) => self.set_vsock_device(config), - SetMmdsConfiguration(config) => self.set_mmds_config(config), + SetBalloonDevice(spec) => self.set_balloon_device(spec), + SetVsockDevice(spec) => self.set_vsock_device(spec), + SetMmdsSpec(spec) => self.set_mmds_config(spec), StartMicroVm => self.start_microvm(), - UpdateMachineConfiguration(config) => self.update_machine_config(config), - SetEntropyDevice(config) => self.set_entropy_device(config), - SetMemoryHotplugDevice(config) => self.set_memory_hotplug_device(config), + UpdateMachineSpec(spec_update) => self.update_machine_spec(spec_update), + SetEntropyDevice(spec) => self.set_entropy_device(spec), + SetMemoryHotplugDevice(spec) => self.set_memory_hotplug_device(spec), // Operations not allowed pre-boot. CreateSnapshot(_) | FlushMetrics @@ -505,70 +512,67 @@ impl<'a> PrebootApiController<'a> { self.vm_resources .balloon .get_config() - .map(VmmData::BalloonConfig) - .map_err(VmmActionError::BalloonConfig) + .map(VmmData::BalloonSpec) + .map_err(VmmActionError::BalloonSpec) } - fn insert_block_device(&mut self, cfg: BlockDeviceConfig) -> Result { + fn insert_block_device(&mut self, spec: BlockDeviceSpec) -> Result { self.boot_path = true; self.vm_resources - .set_block_device(cfg) + .set_block_device(spec) .map(|()| VmmData::Empty) - .map_err(VmmActionError::DriveConfig) + .map_err(VmmActionError::DriveSpec) } - fn insert_net_device( - &mut self, - cfg: NetworkInterfaceConfig, - ) -> Result { + fn insert_net_device(&mut self, spec: NetworkInterfaceSpec) -> Result { self.boot_path = true; self.vm_resources - .build_net_device(cfg) + .build_net_device(spec) .map(|()| VmmData::Empty) - .map_err(VmmActionError::NetworkConfig) + .map_err(VmmActionError::NetworkSpec) } - fn insert_pmem_device(&mut self, cfg: PmemConfig) -> Result { + fn insert_pmem_device(&mut self, spec: PmemSpec) -> Result { self.boot_path = true; self.vm_resources - .build_pmem_device(cfg) + .build_pmem_device(spec) .map(|()| VmmData::Empty) .map_err(VmmActionError::PmemDevice) } - fn set_balloon_device(&mut self, cfg: BalloonDeviceConfig) -> Result { + fn set_balloon_device(&mut self, spec: BalloonDeviceSpec) -> Result { self.boot_path = true; self.vm_resources - .set_balloon_device(cfg) + .set_balloon_device(spec) .map(|()| VmmData::Empty) - .map_err(VmmActionError::BalloonConfig) + .map_err(VmmActionError::BalloonSpec) } - fn set_boot_source(&mut self, cfg: BootSourceConfig) -> Result { + fn set_boot_source(&mut self, spec: BootSourceSpec) -> Result { self.boot_path = true; self.vm_resources - .build_boot_source(cfg) + .build_boot_source(spec) .map(|()| VmmData::Empty) .map_err(VmmActionError::BootSource) } - fn set_mmds_config(&mut self, cfg: MmdsConfig) -> Result { + fn set_mmds_config(&mut self, spec: MmdsSpec) -> Result { self.boot_path = true; self.vm_resources - .set_mmds_config(cfg, &self.instance_info.id) + .set_mmds_config(spec, &self.instance_info.id) .map(|()| VmmData::Empty) - .map_err(VmmActionError::MmdsConfig) + .map_err(VmmActionError::MmdsSpec) } - fn update_machine_config( + fn update_machine_spec( &mut self, - cfg: MachineConfigUpdate, + update: MachineSpecUpdate, ) -> Result { self.boot_path = true; self.vm_resources - .update_machine_config(&cfg) + .update_machine_spec(&update) .map(|()| VmmData::Empty) - .map_err(VmmActionError::MachineConfig) + .map_err(VmmActionError::MachineSpec) } fn set_custom_cpu_template( @@ -579,26 +583,26 @@ impl<'a> PrebootApiController<'a> { Ok(VmmData::Empty) } - fn set_vsock_device(&mut self, cfg: VsockDeviceConfig) -> Result { + fn set_vsock_device(&mut self, spec: VsockDeviceSpec) -> Result { self.boot_path = true; self.vm_resources - .set_vsock_device(cfg) + .set_vsock_device(spec) .map(|()| VmmData::Empty) - .map_err(VmmActionError::VsockConfig) + .map_err(VmmActionError::VsockSpec) } - fn set_entropy_device(&mut self, cfg: EntropyDeviceConfig) -> Result { + fn set_entropy_device(&mut self, spec: EntropyDeviceSpec) -> Result { self.boot_path = true; - self.vm_resources.build_entropy_device(cfg)?; + self.vm_resources.build_entropy_device(spec)?; Ok(VmmData::Empty) } fn set_memory_hotplug_device( &mut self, - cfg: MemoryHotplugConfig, + spec: MemoryHotplugSpec, ) -> Result { self.boot_path = true; - self.vm_resources.set_memory_hotplug_config(cfg)?; + self.vm_resources.set_memory_hotplug_config(spec)?; Ok(VmmData::Empty) } @@ -677,7 +681,7 @@ impl MmdsRequestHandler for RuntimeApiController { fn mmds(&mut self) -> Result, VmmActionError> { self.vm_resources .locked_mmds_or_default() - .map_err(VmmActionError::MmdsConfig) + .map_err(VmmActionError::MmdsSpec) } } @@ -689,12 +693,12 @@ impl RuntimeApiController { // Supported operations allowed post-boot. CreateSnapshot(snapshot_create_cfg) => self.create_snapshot(&snapshot_create_cfg), FlushMetrics => self.flush_metrics(), - GetBalloonConfig => self + GetBalloonSpec => self .vmm .lock() .expect("Poisoned lock") .balloon_config() - .map(|state| VmmData::BalloonConfig(BalloonDeviceConfig::from(state))) + .map(|state| VmmData::BalloonSpec(BalloonDeviceSpec::from(state))) .map_err(VmmActionError::InternalVmm), GetBalloonStats => self .vmm @@ -703,7 +707,7 @@ impl RuntimeApiController { .latest_balloon_stats() .map(VmmData::BalloonStats) .map_err(VmmActionError::InternalVmm), - GetFullVmConfig => Ok(VmmData::FullVmConfig((&self.vm_resources).into())), + GetFullVmSpec => Ok(VmmData::FullVmSpec((&self.vm_resources).into())), GetMemoryHotplugStatus => self .vmm .lock() @@ -712,9 +716,7 @@ impl RuntimeApiController { .map(VmmData::VirtioMemStatus) .map_err(VmmActionError::InternalVmm), GetMMDS => self.get_mmds(), - GetVmMachineConfig => Ok(VmmData::MachineConfiguration( - self.vm_resources.machine_config.clone(), - )), + GetVmMachineSpec => Ok(VmmData::MachineSpec(self.vm_resources.machine_spec.clone())), GetVmInstanceInfo => Ok(VmmData::InstanceInformation( self.vmm.lock().expect("Poisoned lock").instance_info(), )), @@ -762,7 +764,7 @@ impl RuntimeApiController { .stop_balloon_hinting() .map(|_| VmmData::Empty) .map_err(VmmActionError::BalloonUpdate), - UpdateBlockDevice(new_cfg) => self.update_block_device(new_cfg), + UpdateBlockDevice(new_spec) => self.update_block_device(new_spec), UpdateNetworkInterface(netif_update) => self.update_net_rate_limiters(netif_update), UpdateMemoryHotplugSize(cfg) => self .vmm @@ -783,11 +785,11 @@ impl RuntimeApiController { | PutCpuConfiguration(_) | SetBalloonDevice(_) | SetVsockDevice(_) - | SetMmdsConfiguration(_) + | SetMmdsSpec(_) | SetEntropyDevice(_) | SetMemoryHotplugDevice(_) | StartMicroVm - | UpdateMachineConfiguration(_) => Err(VmmActionError::OperationNotSupportedPostBoot), + | UpdateMachineSpec(_) => Err(VmmActionError::OperationNotSupportedPostBoot), } } @@ -892,50 +894,50 @@ impl RuntimeApiController { /// - rate limiter configuration. fn update_block_device( &mut self, - new_cfg: BlockDeviceUpdateConfig, + new_spec: BlockDeviceUpdateSpec, ) -> Result { let mut vmm = self.vmm.lock().expect("Poisoned lock"); // vhost-user-block updates - if new_cfg.path_on_host.is_none() && new_cfg.rate_limiter.is_none() { - vmm.update_vhost_user_block_config(&new_cfg.drive_id) + if new_spec.path_on_host.is_none() && new_spec.rate_limiter.is_none() { + vmm.update_vhost_user_block_config(&new_spec.drive_id) .map_err(DriveError::DeviceUpdate)?; } // virtio-block updates - if let Some(new_path) = new_cfg.path_on_host { - vmm.update_block_device_path(&new_cfg.drive_id, new_path) + if let Some(new_path) = new_spec.path_on_host { + vmm.update_block_device_path(&new_spec.drive_id, new_path) .map_err(DriveError::DeviceUpdate)?; } - if new_cfg.rate_limiter.is_some() { + if new_spec.rate_limiter.is_some() { vmm.update_block_rate_limiter( - &new_cfg.drive_id, - RateLimiterUpdate::from(new_cfg.rate_limiter).bandwidth, - RateLimiterUpdate::from(new_cfg.rate_limiter).ops, + &new_spec.drive_id, + RateLimiterUpdate::from(new_spec.rate_limiter).bandwidth, + RateLimiterUpdate::from(new_spec.rate_limiter).ops, ) .map_err(DriveError::DeviceUpdate)?; } Ok(VmmData::Empty) } - /// Updates configuration for an emulated net device as described in `new_cfg`. + /// Updates configuration for an emulated net device as described in `new_spec`. fn update_net_rate_limiters( &mut self, - new_cfg: NetworkInterfaceUpdateConfig, + new_spec: NetworkInterfaceUpdateSpec, ) -> Result { self.vmm .lock() .expect("Poisoned lock") .update_net_rate_limiters( - &new_cfg.iface_id, - RateLimiterUpdate::from(new_cfg.rx_rate_limiter).bandwidth, - RateLimiterUpdate::from(new_cfg.rx_rate_limiter).ops, - RateLimiterUpdate::from(new_cfg.tx_rate_limiter).bandwidth, - RateLimiterUpdate::from(new_cfg.tx_rate_limiter).ops, + &new_spec.iface_id, + RateLimiterUpdate::from(new_spec.rx_rate_limiter).bandwidth, + RateLimiterUpdate::from(new_spec.rx_rate_limiter).ops, + RateLimiterUpdate::from(new_spec.tx_rate_limiter).bandwidth, + RateLimiterUpdate::from(new_spec.tx_rate_limiter).ops, ) .map(|()| VmmData::Empty) .map_err(NetworkInterfaceError::DeviceUpdate) - .map_err(VmmActionError::NetworkConfig) + .map_err(VmmActionError::NetworkSpec) } } @@ -949,7 +951,7 @@ mod tests { use crate::devices::virtio::block::CacheType; use crate::mmds::data_store::MmdsVersion; use crate::seccomp::BpfThreadMap; - use crate::vmm_config::snapshot::{MemBackendConfig, MemBackendType}; + use crate::vmm_config::snapshot::{MemBackendSpec, MemBackendType}; fn default_preboot<'a>( vm_resources: &'a mut VmResources, @@ -986,8 +988,8 @@ mod tests { #[test] fn test_preboot_get_vm_config() { assert_eq!( - preboot_request(VmmAction::GetVmMachineConfig).unwrap(), - VmmData::MachineConfiguration(MachineConfig::default()) + preboot_request(VmmAction::GetVmMachineSpec).unwrap(), + VmmData::MachineSpec(MachineSpec::default()) ); } @@ -1217,7 +1219,7 @@ mod tests { check_unsupported(preboot_request(VmmAction::Resume)); check_unsupported(preboot_request(VmmAction::GetBalloonStats)); check_unsupported(preboot_request(VmmAction::UpdateBalloon( - BalloonUpdateConfig { amount_mib: 0 }, + BalloonUpdateSpec { amount_mib: 0 }, ))); check_unsupported(preboot_request(VmmAction::StartFreePageHinting( Default::default(), @@ -1225,15 +1227,15 @@ mod tests { check_unsupported(preboot_request(VmmAction::GetFreePageHintingStatus)); check_unsupported(preboot_request(VmmAction::StopFreePageHinting)); check_unsupported(preboot_request(VmmAction::UpdateBalloonStatistics( - BalloonUpdateStatsConfig { + BalloonUpdateStatsSpec { stats_polling_interval_s: 0, }, ))); check_unsupported(preboot_request(VmmAction::UpdateBlockDevice( - BlockDeviceUpdateConfig::default(), + BlockDeviceUpdateSpec::default(), ))); check_unsupported(preboot_request(VmmAction::UpdateNetworkInterface( - NetworkInterfaceUpdateConfig { + NetworkInterfaceUpdateSpec { iface_id: String::new(), rx_rate_limiter: None, tx_rate_limiter: None, @@ -1277,8 +1279,8 @@ mod tests { #[test] fn test_runtime_get_vm_config() { assert_eq!( - runtime_request(VmmAction::GetVmMachineConfig).unwrap(), - VmmData::MachineConfiguration(MachineConfig::default()) + runtime_request(VmmAction::GetVmMachineSpec).unwrap(), + VmmData::MachineSpec(MachineSpec::default()) ); } @@ -1293,7 +1295,7 @@ mod tests { } check_unsupported(runtime_request(VmmAction::ConfigureBootSource( - BootSourceConfig::default(), + BootSourceSpec::default(), ))); check_unsupported(runtime_request(VmmAction::ConfigureLogger(LoggerConfig { log_path: Some(PathBuf::new()), @@ -1302,13 +1304,11 @@ mod tests { show_log_origin: Some(false), module: None, }))); - check_unsupported(runtime_request(VmmAction::ConfigureMetrics( - MetricsConfig { - metrics_path: PathBuf::new(), - }, - ))); + check_unsupported(runtime_request(VmmAction::ConfigureMetrics(MetricsSpec { + metrics_path: PathBuf::new(), + }))); check_unsupported(runtime_request(VmmAction::InsertBlockDevice( - BlockDeviceConfig { + BlockDeviceSpec { drive_id: String::new(), partuuid: None, is_root_device: false, @@ -1323,7 +1323,7 @@ mod tests { }, ))); check_unsupported(runtime_request(VmmAction::InsertNetworkDevice( - NetworkInterfaceConfig { + NetworkInterfaceSpec { iface_id: String::new(), host_dev_name: String::new(), guest_mac: None, @@ -1332,37 +1332,35 @@ mod tests { }, ))); check_unsupported(runtime_request(VmmAction::SetVsockDevice( - VsockDeviceConfig { + VsockDeviceSpec { vsock_id: Some(String::new()), guest_cid: 0, uds_path: String::new(), }, ))); check_unsupported(runtime_request(VmmAction::SetBalloonDevice( - BalloonDeviceConfig::default(), + BalloonDeviceSpec::default(), ))); check_unsupported(runtime_request(VmmAction::SetVsockDevice( - VsockDeviceConfig { + VsockDeviceSpec { vsock_id: Some(String::new()), guest_cid: 0, uds_path: String::new(), }, ))); - check_unsupported(runtime_request(VmmAction::SetMmdsConfiguration( - MmdsConfig { - ipv4_address: None, - version: MmdsVersion::default(), - network_interfaces: Vec::new(), - imds_compat: false, - }, - ))); - check_unsupported(runtime_request(VmmAction::UpdateMachineConfiguration( - MachineConfigUpdate::from(MachineConfig::default()), + check_unsupported(runtime_request(VmmAction::SetMmdsSpec(MmdsSpec { + ipv4_address: None, + version: MmdsVersion::default(), + network_interfaces: Vec::new(), + imds_compat: false, + }))); + check_unsupported(runtime_request(VmmAction::UpdateMachineSpec( + MachineSpecUpdate::from(MachineSpec::default()), ))); check_unsupported(runtime_request(VmmAction::LoadSnapshot( LoadSnapshotParams { snapshot_path: PathBuf::new(), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_type: MemBackendType::File, backend_path: PathBuf::new(), }, @@ -1372,16 +1370,16 @@ mod tests { }, ))); check_unsupported(runtime_request(VmmAction::SetEntropyDevice( - EntropyDeviceConfig::default(), + EntropyDeviceSpec::default(), ))); - check_unsupported(runtime_request(VmmAction::InsertPmemDevice(PmemConfig { + check_unsupported(runtime_request(VmmAction::InsertPmemDevice(PmemSpec { id: String::new(), path_on_host: String::new(), root_device: false, read_only: false, }))); check_unsupported(runtime_request(VmmAction::SetMemoryHotplugDevice( - MemoryHotplugConfig::default(), + MemoryHotplugSpec::default(), ))); } } diff --git a/src/vmm/src/test_utils/mock_resources/mod.rs b/src/vmm/src/test_utils/mock_resources/mod.rs index f8485bf9678..28fa953a8f8 100644 --- a/src/vmm/src/test_utils/mock_resources/mod.rs +++ b/src/vmm/src/test_utils/mock_resources/mod.rs @@ -6,8 +6,8 @@ use std::path::PathBuf; use crate::cpu_config::templates::CustomCpuTemplate; use crate::resources::VmResources; -use crate::vmm_config::boot_source::BootSourceConfig; -use crate::vmm_config::machine_config::{MachineConfig, MachineConfigUpdate}; +use crate::vmm_config::boot_source::BootSourceSpec; +use crate::vmm_config::machine_config::{MachineSpec, MachineSpecUpdate}; pub const DEFAULT_BOOT_ARGS: &str = "reboot=k panic=1 pci=off"; #[cfg(target_arch = "x86_64")] @@ -37,11 +37,11 @@ macro_rules! generate_from { } #[derive(Debug)] -pub struct MockBootSourceConfig(BootSourceConfig); +pub struct MockBootSourceConfig(BootSourceSpec); impl MockBootSourceConfig { pub fn new() -> MockBootSourceConfig { - MockBootSourceConfig(BootSourceConfig { + MockBootSourceConfig(BootSourceSpec { kernel_image_path: kernel_image_path(None), initrd_path: None, boot_args: None, @@ -74,24 +74,24 @@ impl MockVmResources { MockVmResources::default() } - pub fn with_boot_source(mut self, boot_source_cfg: BootSourceConfig) -> Self { - self.0.build_boot_source(boot_source_cfg).unwrap(); + pub fn with_boot_source(mut self, boot_source_spec: BootSourceSpec) -> Self { + self.0.build_boot_source(boot_source_spec).unwrap(); self } - pub fn with_vm_config(mut self, vm_config: MachineConfig) -> Self { - let machine_config = MachineConfigUpdate::from(vm_config); - self.0.update_machine_config(&machine_config).unwrap(); + pub fn with_vm_config(mut self, vm_spec: MachineSpec) -> Self { + let machine_spec_update = MachineSpecUpdate::from(vm_spec); + self.0.update_machine_spec(&machine_spec_update).unwrap(); self } pub fn set_cpu_template(&mut self, cpu_template: CustomCpuTemplate) { - self.0.machine_config.set_custom_cpu_template(cpu_template); + self.0.machine_spec.set_custom_cpu_template(cpu_template); } } #[derive(Debug, Default)] -pub struct MockVmConfig(MachineConfig); +pub struct MockVmConfig(MachineSpec); impl MockVmConfig { pub fn new() -> MockVmConfig { @@ -104,6 +104,6 @@ impl MockVmConfig { } } -generate_from!(MockBootSourceConfig, BootSourceConfig); +generate_from!(MockBootSourceConfig, BootSourceSpec); generate_from!(MockVmResources, VmResources); -generate_from!(MockVmConfig, MachineConfig); +generate_from!(MockVmConfig, MachineSpec); diff --git a/src/vmm/src/test_utils/mod.rs b/src/vmm/src/test_utils/mod.rs index 41809b71b34..1a5c3fb720c 100644 --- a/src/vmm/src/test_utils/mod.rs +++ b/src/vmm/src/test_utils/mod.rs @@ -12,10 +12,10 @@ use crate::builder::build_microvm_for_boot; use crate::resources::VmResources; use crate::seccomp::get_empty_filters; use crate::test_utils::mock_resources::{MockBootSourceConfig, MockVmConfig, MockVmResources}; -use crate::vmm_config::boot_source::BootSourceConfig; +use crate::vmm_config::boot_source::BootSourceSpec; use crate::vmm_config::instance_info::InstanceInfo; use crate::vmm_config::machine_config::HugePageConfig; -use crate::vmm_config::memory_hotplug::MemoryHotplugConfig; +use crate::vmm_config::memory_hotplug::MemoryHotplugSpec; use crate::vstate::memory::{self, GuestMemoryMmap, GuestRegionMmap, GuestRegionMmapExt}; use crate::{EventManager, Vmm}; @@ -78,15 +78,15 @@ pub fn create_vmm( let mut event_manager = EventManager::new().unwrap(); let empty_seccomp_filters = get_empty_filters(); - let boot_source_cfg = MockBootSourceConfig::new().with_default_boot_args(); + let boot_source_spec = MockBootSourceConfig::new().with_default_boot_args(); #[cfg(target_arch = "aarch64")] - let boot_source_cfg: BootSourceConfig = boot_source_cfg.into(); + let boot_source_spec: BootSourceSpec = boot_source_spec.into(); #[cfg(target_arch = "x86_64")] - let boot_source_cfg: BootSourceConfig = match _kernel_image { - Some(kernel) => boot_source_cfg.with_kernel(kernel).into(), - None => boot_source_cfg.into(), + let boot_source_spec: BootSourceSpec = match _kernel_image { + Some(kernel) => boot_source_spec.with_kernel(kernel).into(), + None => boot_source_spec.into(), }; - let mock_vm_res = MockVmResources::new().with_boot_source(boot_source_cfg); + let mock_vm_res = MockVmResources::new().with_boot_source(boot_source_spec); let mut resources: VmResources = if is_diff { mock_vm_res .with_vm_config(MockVmConfig::new().with_dirty_page_tracking().into()) @@ -98,7 +98,7 @@ pub fn create_vmm( resources.pci_enabled = pci_enabled; if memory_hotplug_enabled { - resources.memory_hotplug = Some(MemoryHotplugConfig { + resources.memory_hotplug = Some(MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 128, diff --git a/src/vmm/src/vmm_config/balloon.rs b/src/vmm/src/vmm_config/balloon.rs index 7151a68e99f..b43223f891f 100644 --- a/src/vmm/src/vmm_config/balloon.rs +++ b/src/vmm/src/vmm_config/balloon.rs @@ -13,7 +13,7 @@ type MutexBalloon = Arc>; /// Errors associated with the operations allowed on the balloon. #[derive(Debug, derive_more::From, thiserror::Error, displaydoc::Display)] -pub enum BalloonConfigError { +pub enum BalloonSpecError { /// No balloon device found. DeviceNotFound, /// Amount of pages requested is too large. @@ -26,7 +26,7 @@ pub enum BalloonConfigError { /// from balloon related requests. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct BalloonDeviceConfig { +pub struct BalloonDeviceSpec { /// Target balloon size in MiB. pub amount_mib: u32, /// Option to deflate the balloon in case the guest is out of memory. @@ -42,9 +42,9 @@ pub struct BalloonDeviceConfig { pub free_page_reporting: bool, } -impl From for BalloonDeviceConfig { +impl From for BalloonDeviceSpec { fn from(state: BalloonConfig) -> Self { - BalloonDeviceConfig { + BalloonDeviceSpec { amount_mib: state.amount_mib, deflate_on_oom: state.deflate_on_oom, stats_polling_interval_s: state.stats_polling_interval_s, @@ -58,7 +58,7 @@ impl From for BalloonDeviceConfig { /// of pages and the stats polling interval can be updated. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct BalloonUpdateConfig { +pub struct BalloonUpdateSpec { /// Target balloon size in MiB. pub amount_mib: u32, } @@ -69,12 +69,12 @@ pub struct BalloonUpdateConfig { /// if the statistics were activated in the device configuration. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct BalloonUpdateStatsConfig { +pub struct BalloonUpdateStatsSpec { /// Interval in seconds between refreshing statistics. pub stats_polling_interval_s: u16, } -/// A builder for `Balloon` devices from 'BalloonDeviceConfig'. +/// A builder for `Balloon` devices from 'BalloonDeviceSpec'. #[cfg_attr(not(test), derive(Default))] #[derive(Debug)] pub struct BalloonBuilder { @@ -89,13 +89,13 @@ impl BalloonBuilder { /// Inserts a Balloon device in the store. /// If an entry already exists, it will overwrite it. - pub fn set(&mut self, cfg: BalloonDeviceConfig) -> Result<(), BalloonConfigError> { + pub fn set(&mut self, spec: BalloonDeviceSpec) -> Result<(), BalloonSpecError> { self.inner = Some(Arc::new(Mutex::new(Balloon::new( - cfg.amount_mib, - cfg.deflate_on_oom, - cfg.stats_polling_interval_s, - cfg.free_page_hinting, - cfg.free_page_reporting, + spec.amount_mib, + spec.deflate_on_oom, + spec.stats_polling_interval_s, + spec.free_page_hinting, + spec.free_page_reporting, )?))); Ok(()) @@ -112,11 +112,11 @@ impl BalloonBuilder { } /// Returns the same structure that was used to configure the device. - pub fn get_config(&self) -> Result { + pub fn get_config(&self) -> Result { self.get() - .ok_or(BalloonConfigError::DeviceNotFound) + .ok_or(BalloonSpecError::DeviceNotFound) .map(|balloon_mutex| balloon_mutex.lock().expect("Poisoned lock").config()) - .map(BalloonDeviceConfig::from) + .map(BalloonDeviceSpec::from) } } @@ -124,7 +124,7 @@ impl BalloonBuilder { impl Default for BalloonBuilder { fn default() -> BalloonBuilder { let mut balloon = BalloonBuilder::new(); - balloon.set(BalloonDeviceConfig::default()).unwrap(); + balloon.set(BalloonDeviceSpec::default()).unwrap(); balloon } } @@ -133,8 +133,8 @@ impl Default for BalloonBuilder { pub(crate) mod tests { use super::*; - pub(crate) fn default_config() -> BalloonDeviceConfig { - BalloonDeviceConfig { + pub(crate) fn default_config() -> BalloonDeviceSpec { + BalloonDeviceSpec { amount_mib: 0, deflate_on_oom: false, stats_polling_interval_s: 0, @@ -145,31 +145,31 @@ pub(crate) mod tests { #[test] fn test_balloon_create() { - let default_balloon_config = default_config(); - let balloon_config = BalloonDeviceConfig { + let default_balloon_spec = default_config(); + let balloon_spec = BalloonDeviceSpec { amount_mib: 0, deflate_on_oom: false, stats_polling_interval_s: 0, free_page_hinting: false, free_page_reporting: false, }; - assert_eq!(default_balloon_config, balloon_config); + assert_eq!(default_balloon_spec, balloon_spec); let mut builder = BalloonBuilder::new(); assert!(builder.get().is_none()); - builder.set(balloon_config).unwrap(); + builder.set(balloon_spec).unwrap(); assert_eq!(builder.get().unwrap().lock().unwrap().num_pages(), 0); - assert_eq!(builder.get_config().unwrap(), default_balloon_config); + assert_eq!(builder.get_config().unwrap(), default_balloon_spec); - let _update_config = BalloonUpdateConfig { amount_mib: 5 }; - let _stats_update_config = BalloonUpdateStatsConfig { + let _update_spec = BalloonUpdateSpec { amount_mib: 5 }; + let _stats_update_spec = BalloonUpdateStatsSpec { stats_polling_interval_s: 5, }; } #[test] fn test_from_balloon_state() { - let expected_balloon_config = BalloonDeviceConfig { + let expected_balloon_spec = BalloonDeviceSpec { amount_mib: 5, deflate_on_oom: false, stats_polling_interval_s: 3, @@ -177,7 +177,7 @@ pub(crate) mod tests { free_page_reporting: false, }; - let actual_balloon_config = BalloonDeviceConfig::from(BalloonConfig { + let actual_balloon_spec = BalloonDeviceSpec::from(BalloonConfig { amount_mib: 5, deflate_on_oom: false, stats_polling_interval_s: 3, @@ -185,7 +185,7 @@ pub(crate) mod tests { free_page_reporting: false, }); - assert_eq!(expected_balloon_config, actual_balloon_config); + assert_eq!(expected_balloon_spec, actual_balloon_spec); } #[test] diff --git a/src/vmm/src/vmm_config/boot_source.rs b/src/vmm/src/vmm_config/boot_source.rs index 0b887ee54b5..ed01db92354 100644 --- a/src/vmm/src/vmm_config/boot_source.rs +++ b/src/vmm/src/vmm_config/boot_source.rs @@ -22,7 +22,7 @@ pub const DEFAULT_KERNEL_CMDLINE: &str = "reboot=k panic=1 nomodule 8250.nr_uart /// microvm. #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(deny_unknown_fields)] -pub struct BootSourceConfig { +pub struct BootSourceSpec { /// Path of the kernel image. pub kernel_image_path: String, /// Path of the initrd, if there is one. @@ -32,9 +32,9 @@ pub struct BootSourceConfig { pub boot_args: Option, } -/// Errors associated with actions on `BootSourceConfig`. +/// Errors associated with actions on `BootSourceSpec`. #[derive(Debug, thiserror::Error, displaydoc::Display)] -pub enum BootSourceConfigError { +pub enum BootSourceSpecError { /// The kernel file cannot be opened: {0} InvalidKernelPath(io::Error), /// The initrd file cannot be opened due to invalid path or invalid permissions. {0} @@ -46,14 +46,14 @@ pub enum BootSourceConfigError { /// Holds the kernel specification (both configuration as well as runtime details). #[derive(Debug, Default)] pub struct BootSource { - /// The boot source configuration. - pub config: BootSourceConfig, + /// The boot source specification. + pub spec: BootSourceSpec, /// The boot source builder (a boot source allocated and validated). /// It is an option cause a resumed microVM does not need it. pub builder: Option, } -/// Holds the kernel builder (created and validates based on BootSourceConfig). +/// Holds the kernel builder (created and validates based on BootSourceSpec). #[derive(Debug)] pub struct BootConfig { /// The commandline validated against correctness. @@ -65,20 +65,20 @@ pub struct BootConfig { } impl BootConfig { - /// Creates the BootConfig based on a given configuration. - pub fn new(cfg: &BootSourceConfig) -> Result { - use self::BootSourceConfigError::{ + /// Creates the BootSpec based on a given configuration. + pub fn new(spec: &BootSourceSpec) -> Result { + use self::BootSourceSpecError::{ InvalidInitrdPath, InvalidKernelCommandLine, InvalidKernelPath, }; // Validate boot source config. - let kernel_file = File::open(&cfg.kernel_image_path).map_err(InvalidKernelPath)?; - let initrd_file: Option = match &cfg.initrd_path { + let kernel_file = File::open(&spec.kernel_image_path).map_err(InvalidKernelPath)?; + let initrd_file: Option = match &spec.initrd_path { Some(path) => Some(File::open(path).map_err(InvalidInitrdPath)?), None => None, }; - let cmdline_str = match cfg.boot_args.as_ref() { + let cmdline_str = match spec.boot_args.as_ref() { None => DEFAULT_KERNEL_CMDLINE, Some(str) => str.as_str(), }; @@ -106,13 +106,13 @@ pub(crate) mod tests { let kernel_file = TempFile::new().unwrap(); let kernel_path = kernel_file.as_path().to_str().unwrap().to_string(); - let boot_src_cfg = BootSourceConfig { + let boot_src_spec = BootSourceSpec { boot_args: None, initrd_path: None, kernel_image_path: kernel_path, }; - let boot_cfg = BootConfig::new(&boot_src_cfg).unwrap(); + let boot_cfg = BootConfig::new(&boot_src_spec).unwrap(); assert!(boot_cfg.initrd_file.is_none()); assert_eq!( boot_cfg.cmdline.as_cstring().unwrap().as_bytes_with_nul(), @@ -122,19 +122,19 @@ pub(crate) mod tests { #[test] fn test_serde() { - let boot_src_cfg = BootSourceConfig { + let boot_src_spec = BootSourceSpec { boot_args: Some(DEFAULT_KERNEL_CMDLINE.to_string()), initrd_path: Some("/tmp/initrd".to_string()), kernel_image_path: "./vmlinux.bin".to_string(), }; let mut snapshot_data = vec![0u8; 1000]; - Snapshot::new(&boot_src_cfg) + Snapshot::new(&boot_src_spec) .save(&mut snapshot_data.as_mut_slice()) .unwrap(); let restored_boot_cfg = Snapshot::load_without_crc_check(snapshot_data.as_slice()) .unwrap() .data; - assert_eq!(boot_src_cfg, restored_boot_cfg); + assert_eq!(boot_src_spec, restored_boot_cfg); } } diff --git a/src/vmm/src/vmm_config/drive.rs b/src/vmm/src/vmm_config/drive.rs index adf8083f74d..6e150b6fb09 100644 --- a/src/vmm/src/vmm_config/drive.rs +++ b/src/vmm/src/vmm_config/drive.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; -use super::RateLimiterConfig; +use super::RateLimiterSpec; use crate::VmmError; use crate::devices::virtio::block::device::Block; pub use crate::devices::virtio::block::virtio::device::FileEngineType; @@ -31,7 +31,7 @@ pub enum DriveError { /// Use this structure to set up the Block Device before booting the kernel. #[derive(Debug, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct BlockDeviceConfig { +pub struct BlockDeviceSpec { /// Unique identifier of the drive. pub drive_id: String, /// Part-UUID. Represents the unique id of the boot partition of this device. It is @@ -53,7 +53,7 @@ pub struct BlockDeviceConfig { /// Path of the drive. pub path_on_host: Option, /// Rate Limiter for I/O operations. - pub rate_limiter: Option, + pub rate_limiter: Option, /// The type of IO engine used by the device. // #[serde(default)] // #[serde(rename = "io_engine")] @@ -70,7 +70,7 @@ pub struct BlockDeviceConfig { /// are missing, they will not be updated. #[derive(Debug, Default, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct BlockDeviceUpdateConfig { +pub struct BlockDeviceUpdateSpec { /// The drive ID, as provided by the user at creation time. pub drive_id: String, @@ -78,7 +78,7 @@ pub struct BlockDeviceUpdateConfig { /// New block file path on the host. Only provided data will be updated. pub path_on_host: Option, /// New rate limiter config. - pub rate_limiter: Option, + pub rate_limiter: Option, } /// Wrapper for the collection that holds all the Block Devices @@ -129,14 +129,10 @@ impl BlockBuilder { /// Inserts a `Block` in the block devices list using the specified configuration. /// If a block with the same id already exists, it will overwrite it. /// Inserting a secondary root block device will fail. - pub fn insert( - &mut self, - config: BlockDeviceConfig, - has_pmem_root: bool, - ) -> Result<(), DriveError> { - let position = self.get_index_of_drive_id(&config.drive_id); + pub fn insert(&mut self, spec: BlockDeviceSpec, has_pmem_root: bool) -> Result<(), DriveError> { + let position = self.get_index_of_drive_id(&spec.drive_id); let has_root_device = self.has_root_device(); - let configured_as_root = config.is_root_device; + let configured_as_root = spec.is_root_device; if configured_as_root && has_pmem_root { return Err(DriveError::AddingSecondRootDevice); @@ -149,7 +145,7 @@ impl BlockBuilder { } let block_dev = Arc::new(Mutex::new( - Block::new(config).map_err(DriveError::CreateBlockDevice)?, + Block::new(spec).map_err(DriveError::CreateBlockDevice)?, )); // If the id of the drive already exists in the list, the operation is update/overwrite. @@ -177,7 +173,7 @@ impl BlockBuilder { } /// Returns a vec with the structures used to configure the devices. - pub fn configs(&self) -> Vec { + pub fn configs(&self) -> Vec { self.devices .iter() .map(|b| b.lock().unwrap().config()) @@ -200,9 +196,9 @@ mod tests { // This implementation is used only in tests. // We cannot directly derive clone because RateLimiter does not implement clone. - impl Clone for BlockDeviceConfig { + impl Clone for BlockDeviceSpec { fn clone(&self) -> Self { - BlockDeviceConfig { + BlockDeviceSpec { drive_id: self.drive_id.clone(), partuuid: self.partuuid.clone(), is_root_device: self.is_root_device, @@ -229,7 +225,7 @@ mod tests { let dummy_file = TempFile::new().unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); let dummy_id = String::from("1"); - let dummy_block_device = BlockDeviceConfig { + let dummy_block_device = BlockDeviceSpec { drive_id: dummy_id.clone(), partuuid: None, is_root_device: false, @@ -263,7 +259,7 @@ mod tests { let dummy_file = TempFile::new().unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let dummy_block_device = BlockDeviceConfig { + let dummy_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -295,7 +291,7 @@ mod tests { let dummy_file = TempFile::new().unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let dummy_block_device = BlockDeviceConfig { + let dummy_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -324,7 +320,7 @@ mod tests { fn test_add_two_root_block_devs() { let dummy_file_1 = TempFile::new().unwrap(); let dummy_path_1 = dummy_file_1.as_path().to_str().unwrap().to_string(); - let root_block_device_1 = BlockDeviceConfig { + let root_block_device_1 = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -340,7 +336,7 @@ mod tests { let dummy_file_2 = TempFile::new().unwrap(); let dummy_path_2 = dummy_file_2.as_path().to_str().unwrap().to_string(); - let root_block_device_2 = BlockDeviceConfig { + let root_block_device_2 = BlockDeviceSpec { drive_id: String::from("2"), partuuid: None, is_root_device: true, @@ -367,7 +363,7 @@ mod tests { fn test_add_root_block_device_first() { let dummy_file_1 = TempFile::new().unwrap(); let dummy_path_1 = dummy_file_1.as_path().to_str().unwrap().to_string(); - let root_block_device = BlockDeviceConfig { + let root_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -383,7 +379,7 @@ mod tests { let dummy_file_2 = TempFile::new().unwrap(); let dummy_path_2 = dummy_file_2.as_path().to_str().unwrap().to_string(); - let dummy_block_dev_2 = BlockDeviceConfig { + let dummy_block_dev_2 = BlockDeviceSpec { drive_id: String::from("2"), partuuid: None, is_root_device: false, @@ -399,7 +395,7 @@ mod tests { let dummy_file_3 = TempFile::new().unwrap(); let dummy_path_3 = dummy_file_3.as_path().to_str().unwrap().to_string(); - let dummy_block_dev_3 = BlockDeviceConfig { + let dummy_block_dev_3 = BlockDeviceSpec { drive_id: String::from("3"), partuuid: None, is_root_device: false, @@ -440,7 +436,7 @@ mod tests { fn test_root_block_device_add_last() { let dummy_file_1 = TempFile::new().unwrap(); let dummy_path_1 = dummy_file_1.as_path().to_str().unwrap().to_string(); - let root_block_device = BlockDeviceConfig { + let root_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -456,7 +452,7 @@ mod tests { let dummy_file_2 = TempFile::new().unwrap(); let dummy_path_2 = dummy_file_2.as_path().to_str().unwrap().to_string(); - let dummy_block_dev_2 = BlockDeviceConfig { + let dummy_block_dev_2 = BlockDeviceSpec { drive_id: String::from("2"), partuuid: None, is_root_device: false, @@ -472,7 +468,7 @@ mod tests { let dummy_file_3 = TempFile::new().unwrap(); let dummy_path_3 = dummy_file_3.as_path().to_str().unwrap().to_string(); - let dummy_block_dev_3 = BlockDeviceConfig { + let dummy_block_dev_3 = BlockDeviceSpec { drive_id: String::from("3"), partuuid: None, is_root_device: false, @@ -514,7 +510,7 @@ mod tests { fn test_update() { let dummy_file_1 = TempFile::new().unwrap(); let dummy_path_1 = dummy_file_1.as_path().to_str().unwrap().to_string(); - let root_block_device = BlockDeviceConfig { + let root_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -530,7 +526,7 @@ mod tests { let dummy_file_2 = TempFile::new().unwrap(); let dummy_path_2 = dummy_file_2.as_path().to_str().unwrap().to_string(); - let mut dummy_block_device_2 = BlockDeviceConfig { + let mut dummy_block_device_2 = BlockDeviceSpec { drive_id: String::from("2"), partuuid: None, is_root_device: false, @@ -602,7 +598,7 @@ mod tests { Err(DriveError::RootBlockDeviceAlreadyAdded) ); - let root_block_device = BlockDeviceConfig { + let root_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -618,7 +614,7 @@ mod tests { // Switch roots and add a PARTUUID for the new one. let mut root_block_device_old = root_block_device; root_block_device_old.is_root_device = false; - let root_block_device_new = BlockDeviceConfig { + let root_block_device_new = BlockDeviceSpec { drive_id: String::from("2"), partuuid: Some("0eaa91a0-01".to_string()), is_root_device: true, @@ -644,7 +640,7 @@ mod tests { fn test_block_config() { let dummy_file = TempFile::new().unwrap(); - let dummy_block_device = BlockDeviceConfig { + let dummy_block_device = BlockDeviceSpec { drive_id: String::from("1"), partuuid: None, is_root_device: true, @@ -674,7 +670,7 @@ mod tests { let backing_file = TempFile::new().unwrap(); let block_id = "test_id"; - let config = BlockDeviceConfig { + let spec = BlockDeviceSpec { drive_id: block_id.to_string(), partuuid: None, is_root_device: true, @@ -688,7 +684,7 @@ mod tests { socket: None, }; - let block = Block::new(config).unwrap(); + let block = Block::new(spec).unwrap(); block_devs.add_virtio_device(Arc::new(Mutex::new(block))); assert_eq!(block_devs.devices.len(), 1); diff --git a/src/vmm/src/vmm_config/entropy.rs b/src/vmm/src/vmm_config/entropy.rs index 439657c90f6..1efc010b419 100644 --- a/src/vmm/src/vmm_config/entropy.rs +++ b/src/vmm/src/vmm_config/entropy.rs @@ -6,22 +6,22 @@ use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; -use super::RateLimiterConfig; +use super::RateLimiterSpec; use crate::devices::virtio::rng::{Entropy, EntropyError}; /// This struct represents the strongly typed equivalent of the json body from entropy device /// related requests. #[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct EntropyDeviceConfig { +pub struct EntropyDeviceSpec { /// Configuration for RateLimiter of Entropy device - pub rate_limiter: Option, + pub rate_limiter: Option, } -impl From<&Entropy> for EntropyDeviceConfig { +impl From<&Entropy> for EntropyDeviceSpec { fn from(dev: &Entropy) -> Self { - let rate_limiter: RateLimiterConfig = dev.rate_limiter().into(); - EntropyDeviceConfig { + let rate_limiter: RateLimiterSpec = dev.rate_limiter().into(); + EntropyDeviceSpec { rate_limiter: rate_limiter.into_option(), } } @@ -50,11 +50,11 @@ impl EntropyDeviceBuilder { /// Build an entropy device and return a (counted) reference to it protected by a mutex pub fn build( &mut self, - config: EntropyDeviceConfig, + spec: EntropyDeviceSpec, ) -> Result>, EntropyDeviceError> { - let rate_limiter = config + let rate_limiter = spec .rate_limiter - .map(RateLimiterConfig::try_into) + .map(RateLimiterSpec::try_into) .transpose()?; let dev = Arc::new(Mutex::new(Entropy::new(rate_limiter.unwrap_or_default())?)); self.0 = Some(dev.clone()); @@ -63,8 +63,8 @@ impl EntropyDeviceBuilder { } /// Insert a new entropy device from a configuration object - pub fn insert(&mut self, config: EntropyDeviceConfig) -> Result<(), EntropyDeviceError> { - let _ = self.build(config)?; + pub fn insert(&mut self, spec: EntropyDeviceSpec) -> Result<(), EntropyDeviceError> { + let _ = self.build(spec)?; Ok(()) } @@ -74,10 +74,10 @@ impl EntropyDeviceBuilder { } /// Get the configuration of the entropy device (if any) - pub fn config(&self) -> Option { + pub fn config(&self) -> Option { self.0 .as_ref() - .map(|dev| EntropyDeviceConfig::from(dev.lock().unwrap().deref())) + .map(|dev| EntropyDeviceSpec::from(dev.lock().unwrap().deref())) } /// Set the entropy device from an already created object @@ -93,13 +93,13 @@ mod tests { #[test] fn test_entropy_device_create() { - let config = EntropyDeviceConfig::default(); + let spec = EntropyDeviceSpec::default(); let mut builder = EntropyDeviceBuilder::new(); assert!(builder.get().is_none()); - builder.insert(config.clone()).unwrap(); + builder.insert(spec.clone()).unwrap(); assert!(builder.get().is_some()); - assert_eq!(builder.config().unwrap(), config); + assert_eq!(builder.config().unwrap(), spec); } #[test] diff --git a/src/vmm/src/vmm_config/machine_config.rs b/src/vmm/src/vmm_config/machine_config.rs index e337a5a9dcd..b0c5d9e79d5 100644 --- a/src/vmm/src/vmm_config/machine_config.rs +++ b/src/vmm/src/vmm_config/machine_config.rs @@ -15,7 +15,7 @@ pub const MAX_SUPPORTED_VCPUS: u8 = 32; /// Errors associated with configuring the microVM. #[rustfmt::skip] #[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] -pub enum MachineConfigError { +pub enum MachineSpecError { /// The memory size (MiB) is smaller than the previously set balloon device target size. IncompatibleBalloonSize, /// The memory size (MiB) is either 0, or not a multiple of the configured page size. @@ -90,7 +90,7 @@ impl From for Option { /// Struct used in PUT `/machine-config` API call. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct MachineConfig { +pub struct MachineSpec { /// Number of vcpu to start. pub vcpu_count: u8, /// The memory size in MiB. @@ -146,7 +146,7 @@ where template.serialize(serializer) } -impl Default for MachineConfig { +impl Default for MachineSpec { fn default() -> Self { Self { vcpu_count: 1, @@ -162,14 +162,14 @@ impl Default for MachineConfig { } /// Struct used in PATCH `/machine-config` API call. -/// Used to update `MachineConfig` in `VmResources`. -/// This struct mirrors all the fields in `MachineConfig`. +/// Used to update `MachineSpec` in `VmResources`. +/// This struct mirrors all the fields in `MachineSpec`. /// All fields are optional, but at least one needs to be specified. /// If a field is `Some(value)` then we assume an update is requested /// for that field. #[derive(Clone, Default, Debug, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct MachineConfigUpdate { +pub struct MachineSpecUpdate { /// Number of vcpu to start. #[serde(default)] pub vcpu_count: Option, @@ -194,7 +194,7 @@ pub struct MachineConfigUpdate { pub gdb_socket_path: Option, } -impl MachineConfigUpdate { +impl MachineSpecUpdate { /// Checks if the update request contains any data. /// Returns `true` if all fields are set to `None` which means that there is nothing /// to be updated. @@ -203,22 +203,22 @@ impl MachineConfigUpdate { } } -impl From for MachineConfigUpdate { - fn from(cfg: MachineConfig) -> Self { - MachineConfigUpdate { - vcpu_count: Some(cfg.vcpu_count), - mem_size_mib: Some(cfg.mem_size_mib), - smt: Some(cfg.smt), - cpu_template: cfg.static_template(), - track_dirty_pages: Some(cfg.track_dirty_pages), - huge_pages: Some(cfg.huge_pages), +impl From for MachineSpecUpdate { + fn from(spec: MachineSpec) -> Self { + MachineSpecUpdate { + vcpu_count: Some(spec.vcpu_count), + mem_size_mib: Some(spec.mem_size_mib), + smt: Some(spec.smt), + cpu_template: spec.static_template(), + track_dirty_pages: Some(spec.track_dirty_pages), + huge_pages: Some(spec.huge_pages), #[cfg(feature = "gdb")] - gdb_socket_path: cfg.gdb_socket_path, + gdb_socket_path: spec.gdb_socket_path, } } } -impl MachineConfig { +impl MachineSpec { /// Sets cpu tempalte field to `CpuTemplateType::Custom(cpu_template)`. pub fn set_custom_cpu_template(&mut self, cpu_template: CustomCpuTemplate) { self.cpu_template = Some(CpuTemplateType::Custom(cpu_template)); @@ -231,39 +231,36 @@ impl MachineConfig { } } - /// Updates [`MachineConfig`] with [`MachineConfigUpdate`]. + /// Updates [`MachineSpec`] with [`MachineSpecUpdate`]. /// Mapping for cpu template update: /// StaticCpuTemplate::None -> None /// StaticCpuTemplate::Other -> Some(CustomCpuTemplate::Static(Other)), - /// Returns the updated `MachineConfig` object. - pub fn update( - &self, - update: &MachineConfigUpdate, - ) -> Result { + /// Returns the updated `MachineSpec` object. + pub fn update(&self, update: &MachineSpecUpdate) -> Result { let vcpu_count = update.vcpu_count.unwrap_or(self.vcpu_count); let smt = update.smt.unwrap_or(self.smt); #[cfg(target_arch = "aarch64")] if smt { - return Err(MachineConfigError::SmtNotSupported); + return Err(MachineSpecError::SmtNotSupported); } if vcpu_count == 0 || vcpu_count > MAX_SUPPORTED_VCPUS { - return Err(MachineConfigError::InvalidVcpuCount); + return Err(MachineSpecError::InvalidVcpuCount); } // If SMT is enabled or is to be enabled in this call // only allow vcpu count to be 1 or even. if smt && vcpu_count > 1 && vcpu_count % 2 == 1 { - return Err(MachineConfigError::InvalidVcpuCount); + return Err(MachineSpecError::InvalidVcpuCount); } let mem_size_mib = update.mem_size_mib.unwrap_or(self.mem_size_mib); let page_config = update.huge_pages.unwrap_or(self.huge_pages); if mem_size_mib == 0 || !page_config.is_valid_mem_size(mem_size_mib) { - return Err(MachineConfigError::InvalidMemorySize); + return Err(MachineSpecError::InvalidMemorySize); } let cpu_template = match update.cpu_template { @@ -272,7 +269,7 @@ impl MachineConfig { Some(other) => Some(CpuTemplateType::Static(other)), }; - Ok(MachineConfig { + Ok(MachineSpec { vcpu_count, mem_size_mib, smt, @@ -288,11 +285,11 @@ impl MachineConfig { #[cfg(test)] mod tests { use crate::cpu_config::templates::{CpuTemplateType, CustomCpuTemplate, StaticCpuTemplate}; - use crate::vmm_config::machine_config::MachineConfig; + use crate::vmm_config::machine_config::MachineSpec; // Ensure the special (de)serialization logic for the cpu_template field works: // only static cpu templates can be specified via the machine-config endpoint, but - // we still cram custom cpu templates into the MachineConfig struct if they're set otherwise + // we still cram custom cpu templates into the MachineSpec struct if they're set otherwise // Ensure that during (de)serialization we preserve static templates, but we set custom // templates to None #[test] @@ -302,36 +299,36 @@ mod tests { #[cfg(target_arch = "x86_64")] const TEMPLATE: StaticCpuTemplate = StaticCpuTemplate::T2S; - let mconfig = MachineConfig { + let mspec = MachineSpec { cpu_template: None, ..Default::default() }; - let serialized = serde_json::to_string(&mconfig).unwrap(); - let deserialized = serde_json::from_str::(&serialized).unwrap(); + let serialized = serde_json::to_string(&mspec).unwrap(); + let deserialized = serde_json::from_str::(&serialized).unwrap(); assert!(deserialized.cpu_template.is_none()); - let mconfig = MachineConfig { + let mspec = MachineSpec { cpu_template: Some(CpuTemplateType::Static(TEMPLATE)), ..Default::default() }; - let serialized = serde_json::to_string(&mconfig).unwrap(); - let deserialized = serde_json::from_str::(&serialized).unwrap(); + let serialized = serde_json::to_string(&mspec).unwrap(); + let deserialized = serde_json::from_str::(&serialized).unwrap(); assert_eq!( deserialized.cpu_template, Some(CpuTemplateType::Static(TEMPLATE)) ); - let mconfig = MachineConfig { + let mspec = MachineSpec { cpu_template: Some(CpuTemplateType::Custom(CustomCpuTemplate::default())), ..Default::default() }; - let serialized = serde_json::to_string(&mconfig).unwrap(); - let deserialized = serde_json::from_str::(&serialized).unwrap(); + let serialized = serde_json::to_string(&mspec).unwrap(); + let deserialized = serde_json::from_str::(&serialized).unwrap(); assert!(deserialized.cpu_template.is_none()); } diff --git a/src/vmm/src/vmm_config/memory_hotplug.rs b/src/vmm/src/vmm_config/memory_hotplug.rs index 85cf45ee5e8..bdbf7914c80 100644 --- a/src/vmm/src/vmm_config/memory_hotplug.rs +++ b/src/vmm/src/vmm_config/memory_hotplug.rs @@ -9,7 +9,7 @@ use crate::devices::virtio::mem::{ /// Errors associated with memory hotplug configuration. #[derive(Debug, thiserror::Error, displaydoc::Display)] -pub enum MemoryHotplugConfigError { +pub enum MemoryHotplugSpecError { /// Block size must not be lower than {0} MiB BlockSizeTooSmall(usize), /// Block size must be a power of 2 @@ -35,7 +35,7 @@ fn default_slot_size_mib() -> usize { /// Configuration for memory hotplug device. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct MemoryHotplugConfig { +pub struct MemoryHotplugSpec { /// Total memory size in MiB that can be hotplugged. pub total_size_mib: usize, /// Block size in MiB. A block is the smallest unit the guest can hot(un)plug @@ -46,38 +46,36 @@ pub struct MemoryHotplugConfig { pub slot_size_mib: usize, } -impl MemoryHotplugConfig { +impl MemoryHotplugSpec { /// Validates the configuration. - pub fn validate(&self) -> Result<(), MemoryHotplugConfigError> { + pub fn validate(&self) -> Result<(), MemoryHotplugSpecError> { let min_block_size_mib = VIRTIO_MEM_DEFAULT_BLOCK_SIZE_MIB; if self.block_size_mib < min_block_size_mib { - return Err(MemoryHotplugConfigError::BlockSizeTooSmall( + return Err(MemoryHotplugSpecError::BlockSizeTooSmall( min_block_size_mib, )); } if !self.block_size_mib.is_power_of_two() { - return Err(MemoryHotplugConfigError::BlockSizeNotPowerOfTwo); + return Err(MemoryHotplugSpecError::BlockSizeNotPowerOfTwo); } let min_slot_size_mib = VIRTIO_MEM_DEFAULT_SLOT_SIZE_MIB; if self.slot_size_mib < min_slot_size_mib { - return Err(MemoryHotplugConfigError::SlotSizeTooSmall( - min_slot_size_mib, - )); + return Err(MemoryHotplugSpecError::SlotSizeTooSmall(min_slot_size_mib)); } if !self.slot_size_mib.is_multiple_of(self.block_size_mib) { - return Err(MemoryHotplugConfigError::SlotSizeNotMultipleOfBlockSize( + return Err(MemoryHotplugSpecError::SlotSizeNotMultipleOfBlockSize( self.block_size_mib, )); } if self.total_size_mib < self.slot_size_mib { - return Err(MemoryHotplugConfigError::TotalSizeTooSmall( + return Err(MemoryHotplugSpecError::TotalSizeTooSmall( self.slot_size_mib, )); } if !self.total_size_mib.is_multiple_of(self.slot_size_mib) { - return Err(MemoryHotplugConfigError::TotalSizeNotMultipleOfSlotSize( + return Err(MemoryHotplugSpecError::TotalSizeNotMultipleOfSlotSize( self.slot_size_mib, )); } @@ -102,62 +100,62 @@ mod tests { #[test] fn test_valid_config() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 128, }; - config.validate().unwrap(); + spec.validate().unwrap(); } #[test] fn test_block_size_too_small() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 1, slot_size_mib: 128, }; - match config.validate() { - Err(MemoryHotplugConfigError::BlockSizeTooSmall(min)) => assert_eq!(min, 2), + match spec.validate() { + Err(MemoryHotplugSpecError::BlockSizeTooSmall(min)) => assert_eq!(min, 2), _ => panic!("Expected InvalidBlockSizeTooSmall error"), } } #[test] fn test_block_size_not_power_of_two() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 3, slot_size_mib: 128, }; - match config.validate() { - Err(MemoryHotplugConfigError::BlockSizeNotPowerOfTwo) => {} + match spec.validate() { + Err(MemoryHotplugSpecError::BlockSizeNotPowerOfTwo) => {} _ => panic!("Expected InvalidBlockSizePowerOfTwo error"), } } #[test] fn test_slot_size_too_small() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 1, }; - match config.validate() { - Err(MemoryHotplugConfigError::SlotSizeTooSmall(min)) => assert_eq!(min, 128), + match spec.validate() { + Err(MemoryHotplugSpecError::SlotSizeTooSmall(min)) => assert_eq!(min, 128), _ => panic!("Expected InvalidSlotSizeTooSmall error"), } } #[test] fn test_slot_size_not_multiple_of_block_size() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 4, slot_size_mib: 130, }; - match config.validate() { - Err(MemoryHotplugConfigError::SlotSizeNotMultipleOfBlockSize(block_size)) => { + match spec.validate() { + Err(MemoryHotplugSpecError::SlotSizeNotMultipleOfBlockSize(block_size)) => { assert_eq!(block_size, 4) } _ => panic!("Expected InvalidSlotSizeMultiple error"), @@ -166,13 +164,13 @@ mod tests { #[test] fn test_total_size_too_small() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 64, block_size_mib: 2, slot_size_mib: 128, }; - match config.validate() { - Err(MemoryHotplugConfigError::TotalSizeTooSmall(slot_size)) => { + match spec.validate() { + Err(MemoryHotplugSpecError::TotalSizeTooSmall(slot_size)) => { assert_eq!(slot_size, 128) } _ => panic!("Expected InvalidTotalSizeTooSmall error"), @@ -181,13 +179,13 @@ mod tests { #[test] fn test_total_size_not_multiple_of_slot_size() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1000, block_size_mib: 2, slot_size_mib: 128, }; - match config.validate() { - Err(MemoryHotplugConfigError::TotalSizeNotMultipleOfSlotSize(slot_size)) => { + match spec.validate() { + Err(MemoryHotplugSpecError::TotalSizeNotMultipleOfSlotSize(slot_size)) => { assert_eq!(slot_size, 128) } _ => panic!("Expected InvalidTotalSizeMultiple error"), @@ -202,10 +200,10 @@ mod tests { let json = r#"{ "total_size_mib": 1024 }"#; - let deserialized: MemoryHotplugConfig = serde_json::from_str(json).unwrap(); + let deserialized: MemoryHotplugSpec = serde_json::from_str(json).unwrap(); assert_eq!( deserialized, - MemoryHotplugConfig { + MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 2, slot_size_mib: 128, @@ -215,13 +213,13 @@ mod tests { #[test] fn test_serde() { - let config = MemoryHotplugConfig { + let spec = MemoryHotplugSpec { total_size_mib: 1024, block_size_mib: 4, slot_size_mib: 256, }; - let json = serde_json::to_string(&config).unwrap(); - let deserialized: MemoryHotplugConfig = serde_json::from_str(&json).unwrap(); - assert_eq!(config, deserialized); + let json = serde_json::to_string(&spec).unwrap(); + let deserialized: MemoryHotplugSpec = serde_json::from_str(&json).unwrap(); + assert_eq!(spec, deserialized); } } diff --git a/src/vmm/src/vmm_config/metrics.rs b/src/vmm/src/vmm_config/metrics.rs index 9d44c35f6a3..3ba78668a1f 100644 --- a/src/vmm/src/vmm_config/metrics.rs +++ b/src/vmm/src/vmm_config/metrics.rs @@ -11,27 +11,27 @@ use crate::utils::open_file_write_nonblock; /// Strongly typed structure used to describe the metrics system. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct MetricsConfig { +pub struct MetricsSpec { /// Named pipe or file used as output for metrics. pub metrics_path: PathBuf, } -/// Errors associated with actions on the `MetricsConfig`. +/// Errors associated with actions on the `MetricsSpec`. #[derive(Debug, thiserror::Error, displaydoc::Display)] -pub enum MetricsConfigError { +pub enum MetricsSpecError { /// Cannot initialize the metrics system due to bad user input: {0} InitializationFailure(String), } -/// Configures the metrics as described in `metrics_cfg`. -pub fn init_metrics(metrics_cfg: MetricsConfig) -> Result<(), MetricsConfigError> { +/// Configures the metrics as described in `metrics_spec`. +pub fn init_metrics(metrics_spec: MetricsSpec) -> Result<(), MetricsSpecError> { let writer = FcLineWriter::new( - open_file_write_nonblock(&metrics_cfg.metrics_path) - .map_err(|err| MetricsConfigError::InitializationFailure(err.to_string()))?, + open_file_write_nonblock(&metrics_spec.metrics_path) + .map_err(|err| MetricsSpecError::InitializationFailure(err.to_string()))?, ); METRICS .init(writer) - .map_err(|err| MetricsConfigError::InitializationFailure(err.to_string())) + .map_err(|err| MetricsSpecError::InitializationFailure(err.to_string())) } #[cfg(test)] @@ -44,7 +44,7 @@ mod tests { fn test_init_metrics() { // Initializing metrics with valid pipe is ok. let metrics_file = TempFile::new().unwrap(); - let desc = MetricsConfig { + let desc = MetricsSpec { metrics_path: metrics_file.as_path().to_path_buf(), }; diff --git a/src/vmm/src/vmm_config/mmds.rs b/src/vmm/src/vmm_config/mmds.rs index 4c9cee2b7fd..1eb894951ca 100644 --- a/src/vmm/src/vmm_config/mmds.rs +++ b/src/vmm/src/vmm_config/mmds.rs @@ -7,24 +7,24 @@ use serde::{Deserialize, Serialize}; use crate::mmds::data_store; use crate::mmds::data_store::MmdsVersion; -/// Keeps the MMDS configuration. +/// Keeps the MMDS specification. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct MmdsConfig { +pub struct MmdsSpec { /// MMDS version. #[serde(default)] pub version: MmdsVersion, /// Network interfaces that allow forwarding packets to MMDS. pub network_interfaces: Vec, - /// MMDS IPv4 configured address. + /// MMDS IPv4 specified address. pub ipv4_address: Option, /// Compatibility with EC2 IMDS. #[serde(default)] pub imds_compat: bool, } -impl MmdsConfig { - /// Returns the MMDS version configured. +impl MmdsSpec { + /// Returns the MMDS version specified. pub fn version(&self) -> MmdsVersion { self.version } @@ -34,22 +34,22 @@ impl MmdsConfig { self.network_interfaces.clone() } - /// Returns the MMDS IPv4 address if one was configured. + /// Returns the MMDS IPv4 address if one was specified. /// Otherwise returns None. pub fn ipv4_addr(&self) -> Option { self.ipv4_address } } -/// MMDS configuration related errors. +/// MMDS specification related errors. #[rustfmt::skip] #[derive(Debug, thiserror::Error, displaydoc::Display)] -pub enum MmdsConfigError { +pub enum MmdsSpecError { /// The list of network interface IDs that allow forwarding MMDS requests is empty. EmptyNetworkIfaceList, /// The MMDS IPv4 address is not link local. InvalidIpv4Addr, - /// The list of network interface IDs provided contains at least one ID that does not correspond to any existing network interface. + /// The list of network interface IDs specified contains at least one ID that does not correspond to any existing network interface. InvalidNetworkInterfaceId, /// Failed to initialize MMDS data store: {0} InitMmdsDatastore(#[from] data_store::MmdsDatastoreError), diff --git a/src/vmm/src/vmm_config/mod.rs b/src/vmm/src/vmm_config/mod.rs index 9a4c104ce3a..80b64aefc4c 100644 --- a/src/vmm/src/vmm_config/mod.rs +++ b/src/vmm/src/vmm_config/mod.rs @@ -4,6 +4,7 @@ use std::convert::{From, TryInto}; use std::io; +use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use crate::rate_limiter::{BucketUpdate, RateLimiter, TokenBucket}; @@ -36,19 +37,45 @@ pub mod snapshot; /// Wrapper for configuring the vsock devices attached to the microVM. pub mod vsock; -// TODO: Migrate the VMM public-facing code (i.e. interface) to use stateless structures, -// for receiving data/args, such as the below `RateLimiterConfig` and `TokenBucketConfig`. -// Also todo: find a better suffix than `Config`; it should illustrate the static nature -// of the enclosed data. -// Currently, data is passed around using live/stateful objects. Switching to static/stateless -// objects will simplify both the ownership model and serialization. -// Public access would then be more tightly regulated via `VmmAction`s, consisting of tuples like -// (entry-point-into-VMM-logic, stateless-args-structure). +/// Marker trait for stateless payloads that can be sent through the VMM API without +/// carrying live state. +pub trait StatelessArgs: DeserializeOwned + Send + Sync + 'static {} + +impl StatelessArgs for T where T: DeserializeOwned + Send + Sync + 'static {} + +/// Tuple-like wrapper pairing a VMM entrypoint with stateless arguments. +#[derive(Debug)] +pub struct VmmActionPayload { + /// Function/closure that acts as the VMM entrypoint. + pub entrypoint: F, + /// Stateless arguments forwarded to the entrypoint. + pub args: A, +} + +impl VmmActionPayload { + /// Creates a new payload pairing an entrypoint with its arguments. + #[inline] + pub fn new(entrypoint: F, args: A) -> Self { + Self { entrypoint, args } + } +} + +impl VmmActionPayload +where + F: FnOnce(A) -> R, + A: StatelessArgs, +{ + /// Dispatches the entrypoint with the provided stateless arguments. + #[inline] + pub fn dispatch(self) -> R { + (self.entrypoint)(self.args) + } +} /// A public-facing, stateless structure, holding all the data we need to create a TokenBucket /// (live) object. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] -pub struct TokenBucketConfig { +pub struct TokenBucketSpec { /// See TokenBucket::size. pub size: u64, /// See TokenBucket::one_time_burst. @@ -57,13 +84,13 @@ pub struct TokenBucketConfig { pub refill_time: u64, } -impl From<&TokenBucket> for TokenBucketConfig { +impl From<&TokenBucket> for TokenBucketSpec { fn from(tb: &TokenBucket) -> Self { let one_time_burst = match tb.initial_one_time_burst() { 0 => None, v => Some(v), }; - TokenBucketConfig { + TokenBucketSpec { size: tb.capacity(), one_time_burst, refill_time: tb.refill_time_ms(), @@ -75,11 +102,11 @@ impl From<&TokenBucket> for TokenBucketConfig { /// (live) object. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct RateLimiterConfig { +pub struct RateLimiterSpec { /// Data used to initialize the RateLimiter::bandwidth bucket. - pub bandwidth: Option, + pub bandwidth: Option, /// Data used to initialize the RateLimiter::ops bucket. - pub ops: Option, + pub ops: Option, } /// A public-facing, stateless structure, specifying RateLimiter properties updates. @@ -91,14 +118,14 @@ pub struct RateLimiterUpdate { pub ops: BucketUpdate, } -fn get_bucket_update(tb_cfg: &Option) -> BucketUpdate { - match tb_cfg { +fn get_bucket_update(tb_spec: &Option) -> BucketUpdate { + match tb_spec { // There is data to update. - Some(tb_cfg) => { + Some(tb_spec) => { TokenBucket::new( - tb_cfg.size, - tb_cfg.one_time_burst.unwrap_or(0), - tb_cfg.refill_time, + tb_spec.size, + tb_spec.one_time_burst.unwrap_or(0), + tb_spec.refill_time, ) // Updated active rate-limiter. .map(BucketUpdate::Update) @@ -110,12 +137,12 @@ fn get_bucket_update(tb_cfg: &Option) -> BucketUpdate { } } -impl From> for RateLimiterUpdate { - fn from(cfg: Option) -> Self { - if let Some(cfg) = cfg { +impl From> for RateLimiterUpdate { + fn from(spec: Option) -> Self { + if let Some(spec) = spec { RateLimiterUpdate { - bandwidth: get_bucket_update(&cfg.bandwidth), - ops: get_bucket_update(&cfg.ops), + bandwidth: get_bucket_update(&spec.bandwidth), + ops: get_bucket_update(&spec.ops), } } else { // No update to the rate-limiter. @@ -127,7 +154,7 @@ impl From> for RateLimiterUpdate { } } -impl TryInto for RateLimiterConfig { +impl TryInto for RateLimiterSpec { type Error = io::Error; fn try_into(self) -> Result { @@ -144,19 +171,19 @@ impl TryInto for RateLimiterConfig { } } -impl From<&RateLimiter> for RateLimiterConfig { +impl From<&RateLimiter> for RateLimiterSpec { fn from(rl: &RateLimiter) -> Self { - RateLimiterConfig { - bandwidth: rl.bandwidth().map(TokenBucketConfig::from), - ops: rl.ops().map(TokenBucketConfig::from), + RateLimiterSpec { + bandwidth: rl.bandwidth().map(TokenBucketSpec::from), + ops: rl.ops().map(TokenBucketSpec::from), } } } -impl RateLimiterConfig { +impl RateLimiterSpec { /// [`Option`] already implements [`From`] so we have to use a custom /// one. - pub fn into_option(self) -> Option { + pub fn into_option(self) -> Option { if self.bandwidth.is_some() || self.ops.is_some() { Some(self) } else { @@ -175,19 +202,19 @@ mod tests { #[test] fn test_rate_limiter_configs() { - let rlconf = RateLimiterConfig { - bandwidth: Some(TokenBucketConfig { + let rl_spec = RateLimiterSpec { + bandwidth: Some(TokenBucketSpec { size: SIZE, one_time_burst: Some(ONE_TIME_BURST), refill_time: REFILL_TIME, }), - ops: Some(TokenBucketConfig { + ops: Some(TokenBucketSpec { size: SIZE * 2, one_time_burst: None, refill_time: REFILL_TIME * 2, }), }; - let rl: RateLimiter = rlconf.try_into().unwrap(); + let rl: RateLimiter = rl_spec.try_into().unwrap(); assert_eq!(rl.bandwidth().unwrap().capacity(), SIZE); assert_eq!(rl.bandwidth().unwrap().one_time_burst(), ONE_TIME_BURST); assert_eq!(rl.bandwidth().unwrap().refill_time_ms(), REFILL_TIME); @@ -198,22 +225,22 @@ mod tests { #[test] fn test_generate_configs() { - let bw_tb_cfg = TokenBucketConfig { + let bw_tb_spec = TokenBucketSpec { size: SIZE, one_time_burst: Some(ONE_TIME_BURST), refill_time: REFILL_TIME, }; let bw_tb = TokenBucket::new(SIZE, ONE_TIME_BURST, REFILL_TIME).unwrap(); - let generated_bw_tb_cfg = TokenBucketConfig::from(&bw_tb); - assert_eq!(generated_bw_tb_cfg, bw_tb_cfg); + let generated_bw_tb_spec = TokenBucketSpec::from(&bw_tb); + assert_eq!(generated_bw_tb_spec, bw_tb_spec); - let rl_conf = RateLimiterConfig { - bandwidth: Some(bw_tb_cfg), + let rl_spec = RateLimiterSpec { + bandwidth: Some(bw_tb_spec), ops: None, }; - let rl: RateLimiter = rl_conf.try_into().unwrap(); - let generated_rl_conf = RateLimiterConfig::from(&rl); - assert_eq!(generated_rl_conf, rl_conf); - assert_eq!(generated_rl_conf.into_option(), Some(rl_conf)); + let rl: RateLimiter = rl_spec.try_into().unwrap(); + let generated_rl_spec = RateLimiterSpec::from(&rl); + assert_eq!(generated_rl_spec, rl_spec); + assert_eq!(generated_rl_spec.into_option(), Some(rl_spec)); } } diff --git a/src/vmm/src/vmm_config/net.rs b/src/vmm/src/vmm_config/net.rs index 81a2db49f33..29032a36e72 100644 --- a/src/vmm/src/vmm_config/net.rs +++ b/src/vmm/src/vmm_config/net.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; -use super::RateLimiterConfig; +use super::RateLimiterSpec; use crate::VmmError; use crate::devices::virtio::net::{Net, TapError}; use crate::utils::net::mac::MacAddr; @@ -16,7 +16,7 @@ use crate::utils::net::mac::MacAddr; /// related requests. #[derive(Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct NetworkInterfaceConfig { +pub struct NetworkInterfaceSpec { /// ID of the guest network interface. pub iface_id: String, /// Host level path for the guest network interface. @@ -24,16 +24,16 @@ pub struct NetworkInterfaceConfig { /// Guest MAC address. pub guest_mac: Option, /// Rate Limiter for received packages. - pub rx_rate_limiter: Option, + pub rx_rate_limiter: Option, /// Rate Limiter for transmitted packages. - pub tx_rate_limiter: Option, + pub tx_rate_limiter: Option, } -impl From<&Net> for NetworkInterfaceConfig { +impl From<&Net> for NetworkInterfaceSpec { fn from(net: &Net) -> Self { - let rx_rl: RateLimiterConfig = net.rx_rate_limiter().into(); - let tx_rl: RateLimiterConfig = net.tx_rate_limiter().into(); - NetworkInterfaceConfig { + let rx_rl: RateLimiterSpec = net.rx_rate_limiter().into(); + let tx_rl: RateLimiterSpec = net.tx_rate_limiter().into(); + NetworkInterfaceSpec { iface_id: net.id().clone(), host_dev_name: net.iface_name(), guest_mac: net.guest_mac().copied(), @@ -47,15 +47,15 @@ impl From<&Net> for NetworkInterfaceConfig { /// can be updated. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct NetworkInterfaceUpdateConfig { +pub struct NetworkInterfaceUpdateSpec { /// The net iface ID, as provided by the user at iface creation time. pub iface_id: String, /// New RX rate limiter config. Only provided data will be updated. I.e. if any optional data /// is missing, it will not be nullified, but left unchanged. - pub rx_rate_limiter: Option, + pub rx_rate_limiter: Option, /// New TX rate limiter config. Only provided data will be updated. I.e. if any optional data /// is missing, it will not be nullified, but left unchanged. - pub tx_rate_limiter: Option, + pub tx_rate_limiter: Option, } /// Errors associated with the operations allowed on a net device. @@ -102,13 +102,13 @@ impl NetBuilder { /// in the builder's internal list. pub fn build( &mut self, - netif_config: NetworkInterfaceConfig, + netif_spec: NetworkInterfaceSpec, ) -> Result>, NetworkInterfaceError> { - if let Some(ref mac_address) = netif_config.guest_mac { + if let Some(ref mac_address) = netif_spec.guest_mac { let mac_conflict = |net: &Arc>| { let net = net.lock().expect("Poisoned lock"); // Check if another net dev has same MAC. - Some(mac_address) == net.guest_mac() && &netif_config.iface_id != net.id() + Some(mac_address) == net.guest_mac() && &netif_spec.iface_id != net.id() }; // Validate there is no Mac conflict. // No need to validate host_dev_name conflict. In such a case, @@ -124,36 +124,36 @@ impl NetBuilder { if let Some(index) = self .net_devices .iter() - .position(|net| net.lock().expect("Poisoned lock").id() == &netif_config.iface_id) + .position(|net| net.lock().expect("Poisoned lock").id() == &netif_spec.iface_id) { self.net_devices.swap_remove(index); } // Add new device. - let net = Arc::new(Mutex::new(Self::create_net(netif_config)?)); + let net = Arc::new(Mutex::new(Self::create_net(netif_spec)?)); self.net_devices.push(net.clone()); Ok(net) } - /// Creates a Net device from a NetworkInterfaceConfig. - pub fn create_net(cfg: NetworkInterfaceConfig) -> Result { - let rx_rate_limiter = cfg + /// Creates a Net device from a NetworkInterfaceSpec. + pub fn create_net(spec: NetworkInterfaceSpec) -> Result { + let rx_rate_limiter = spec .rx_rate_limiter - .map(super::RateLimiterConfig::try_into) + .map(super::RateLimiterSpec::try_into) .transpose() .map_err(NetworkInterfaceError::CreateRateLimiter)?; - let tx_rate_limiter = cfg + let tx_rate_limiter = spec .tx_rate_limiter - .map(super::RateLimiterConfig::try_into) + .map(super::RateLimiterSpec::try_into) .transpose() .map_err(NetworkInterfaceError::CreateRateLimiter)?; // Create and return the Net device crate::devices::virtio::net::Net::new( - cfg.iface_id, - &cfg.host_dev_name, - cfg.guest_mac, + spec.iface_id, + &spec.host_dev_name, + spec.guest_mac, rx_rate_limiter.unwrap_or_default(), tx_rate_limiter.unwrap_or_default(), ) @@ -161,10 +161,10 @@ impl NetBuilder { } /// Returns a vec with the structures used to configure the net devices. - pub fn configs(&self) -> Vec { + pub fn configs(&self) -> Vec { let mut ret = vec![]; for net in &self.net_devices { - ret.push(NetworkInterfaceConfig::from(net.lock().unwrap().deref())); + ret.push(NetworkInterfaceSpec::from(net.lock().unwrap().deref())); } ret } @@ -183,19 +183,19 @@ mod tests { } } - fn create_netif(id: &str, name: &str, mac: &str) -> NetworkInterfaceConfig { - NetworkInterfaceConfig { + fn create_netif(id: &str, name: &str, mac: &str) -> NetworkInterfaceSpec { + NetworkInterfaceSpec { iface_id: String::from(id), host_dev_name: String::from(name), guest_mac: Some(MacAddr::from_str(mac).unwrap()), - rx_rate_limiter: RateLimiterConfig::default().into_option(), - tx_rate_limiter: RateLimiterConfig::default().into_option(), + rx_rate_limiter: RateLimiterSpec::default().into_option(), + tx_rate_limiter: RateLimiterSpec::default().into_option(), } } - impl Clone for NetworkInterfaceConfig { + impl Clone for NetworkInterfaceSpec { fn clone(&self) -> Self { - NetworkInterfaceConfig { + NetworkInterfaceSpec { iface_id: self.iface_id.clone(), host_dev_name: self.host_dev_name.clone(), guest_mac: self.guest_mac, @@ -305,19 +305,19 @@ mod tests { let host_dev_name = "dev"; let guest_mac = "01:23:45:67:89:0b"; - let net_if_cfg = create_netif(net_id, host_dev_name, guest_mac); + let net_if_spec = create_netif(net_id, host_dev_name, guest_mac); assert_eq!( - net_if_cfg.guest_mac.unwrap(), + net_if_spec.guest_mac.unwrap(), MacAddr::from_str(guest_mac).unwrap() ); let mut net_builder = NetBuilder::new(); - net_builder.build(net_if_cfg.clone()).unwrap(); + net_builder.build(net_if_spec.clone()).unwrap(); assert_eq!(net_builder.net_devices.len(), 1); let configs = net_builder.configs(); assert_eq!(configs.len(), 1); - assert_eq!(configs.first().unwrap(), &net_if_cfg); + assert_eq!(configs.first().unwrap(), &net_if_spec); } #[test] diff --git a/src/vmm/src/vmm_config/pmem.rs b/src/vmm/src/vmm_config/pmem.rs index d680e9c36d7..00fb5b979f9 100644 --- a/src/vmm/src/vmm_config/pmem.rs +++ b/src/vmm/src/vmm_config/pmem.rs @@ -7,9 +7,9 @@ use serde::{Deserialize, Serialize}; use crate::devices::virtio::pmem::device::{Pmem, PmemError}; -/// Errors associated wit the operations allowed on a pmem device +/// Errors associated with the operations allowed on a pmem device #[derive(Debug, thiserror::Error, displaydoc::Display)] -pub enum PmemConfigError { +pub enum PmemSpecError { /// Attempt to add pmem as a root device while the root device defined as a block device AddingSecondRootDevice, /// A root pmem device already exist @@ -23,7 +23,7 @@ pub enum PmemConfigError { /// Use this structure to setup a Pmem device before boothing the kernel. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct PmemConfig { +pub struct PmemSpec { /// Unique identifier of the device. pub id: String, /// Path of the drive. @@ -48,37 +48,33 @@ impl PmemBuilder { pub fn has_root_device(&self) -> bool { self.devices .iter() - .any(|d| d.lock().unwrap().config.root_device) + .any(|d| d.lock().unwrap().spec.root_device) } /// Build a device from the config - pub fn build( - &mut self, - config: PmemConfig, - has_block_root: bool, - ) -> Result<(), PmemConfigError> { - if config.root_device && has_block_root { - return Err(PmemConfigError::AddingSecondRootDevice); + pub fn build(&mut self, spec: PmemSpec, has_block_root: bool) -> Result<(), PmemSpecError> { + if spec.root_device && has_block_root { + return Err(PmemSpecError::AddingSecondRootDevice); } let position = self .devices .iter() - .position(|d| d.lock().unwrap().config.id == config.id); + .position(|d| d.lock().unwrap().spec.id == spec.id); if let Some(index) = position { - if !self.devices[index].lock().unwrap().config.root_device - && config.root_device + if !self.devices[index].lock().unwrap().spec.root_device + && spec.root_device && self.has_root_device() { - return Err(PmemConfigError::RootPmemDeviceAlreadyExist); + return Err(PmemSpecError::RootPmemDeviceAlreadyExist); } - let pmem = Pmem::new(config)?; + let pmem = Pmem::new(spec)?; let pmem = Arc::new(Mutex::new(pmem)); self.devices[index] = pmem; } else { - if config.root_device && self.has_root_device() { - return Err(PmemConfigError::RootPmemDeviceAlreadyExist); + if spec.root_device && self.has_root_device() { + return Err(PmemSpecError::RootPmemDeviceAlreadyExist); } - let pmem = Pmem::new(config)?; + let pmem = Pmem::new(spec)?; let pmem = Arc::new(Mutex::new(pmem)); self.devices.push(pmem); } @@ -93,10 +89,10 @@ impl PmemBuilder { } /// Returns a vec with the structures used to configure the devices. - pub fn configs(&self) -> Vec { + pub fn configs(&self) -> Vec { self.devices .iter() - .map(|b| b.lock().unwrap().config.clone()) + .map(|b| b.lock().unwrap().spec.clone()) .collect() } } @@ -114,19 +110,19 @@ mod tests { let dummy_file = TempFile::new().unwrap(); dummy_file.as_file().set_len(Pmem::ALIGNMENT).unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let mut config = PmemConfig { + let mut spec = PmemSpec { id: "1".into(), path_on_host: dummy_path, root_device: true, read_only: false, }; - builder.build(config.clone(), false).unwrap(); + builder.build(spec.clone(), false).unwrap(); assert_eq!(builder.devices.len(), 1); assert!(builder.has_root_device()); // First device got replaced with new one - config.root_device = false; - builder.build(config, false).unwrap(); + spec.root_device = false; + builder.build(spec, false).unwrap(); assert_eq!(builder.devices.len(), 1); assert!(!builder.has_root_device()); } @@ -138,18 +134,18 @@ mod tests { let dummy_file = TempFile::new().unwrap(); dummy_file.as_file().set_len(Pmem::ALIGNMENT).unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let mut config = PmemConfig { + let mut spec = PmemSpec { id: "1".into(), path_on_host: dummy_path, root_device: true, read_only: false, }; - builder.build(config.clone(), false).unwrap(); + builder.build(spec.clone(), false).unwrap(); - config.id = "2".into(); + spec.id = "2".into(); assert!(matches!( - builder.build(config.clone(), false).unwrap_err(), - PmemConfigError::RootPmemDeviceAlreadyExist, + builder.build(spec.clone(), false).unwrap_err(), + PmemSpecError::RootPmemDeviceAlreadyExist, )); } @@ -160,15 +156,15 @@ mod tests { let dummy_file = TempFile::new().unwrap(); dummy_file.as_file().set_len(Pmem::ALIGNMENT).unwrap(); let dummy_path = dummy_file.as_path().to_str().unwrap().to_string(); - let config = PmemConfig { + let spec = PmemSpec { id: "1".into(), path_on_host: dummy_path, root_device: true, read_only: false, }; assert!(matches!( - builder.build(config, true).unwrap_err(), - PmemConfigError::AddingSecondRootDevice, + builder.build(spec, true).unwrap_err(), + PmemSpecError::AddingSecondRootDevice, )); } } diff --git a/src/vmm/src/vmm_config/serial.rs b/src/vmm/src/vmm_config/serial.rs index 0433df95940..e4a6b84dafc 100644 --- a/src/vmm/src/vmm_config/serial.rs +++ b/src/vmm/src/vmm_config/serial.rs @@ -8,7 +8,7 @@ use serde::Deserialize; /// The body of a PUT /serial request. #[derive(Debug, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct SerialConfig { +pub struct SerialSpec { /// Named pipe or file used as output for guest serial console. pub serial_out_path: Option, } diff --git a/src/vmm/src/vmm_config/snapshot.rs b/src/vmm/src/vmm_config/snapshot.rs index 13a87ba30c4..4952ddaf47c 100644 --- a/src/vmm/src/vmm_config/snapshot.rs +++ b/src/vmm/src/vmm_config/snapshot.rs @@ -58,12 +58,12 @@ pub struct NetworkOverride { } /// Stores the configuration that will be used for loading a snapshot. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Deserialize)] pub struct LoadSnapshotParams { /// Path to the file that contains the microVM state to be loaded. pub snapshot_path: PathBuf, /// Specifies guest memory backend configuration. - pub mem_backend: MemBackendConfig, + pub mem_backend: MemBackendSpec, /// Whether KVM dirty page tracking should be enabled, to space optimization /// of differential snapshots. pub track_dirty_pages: bool, @@ -77,7 +77,7 @@ pub struct LoadSnapshotParams { /// Stores the configuration for loading a snapshot that is provided by the user. #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] -pub struct LoadSnapshotConfig { +pub struct LoadSnapshotSpec { /// Path to the file that contains the microVM state to be loaded. pub snapshot_path: PathBuf, /// Path to the file that contains the guest memory to be loaded. To be used only if @@ -87,7 +87,7 @@ pub struct LoadSnapshotConfig { /// Guest memory backend configuration. Is not to be used in conjunction with `mem_file_path`. /// None value is allowed only if `mem_file_path` is present. #[serde(skip_serializing_if = "Option::is_none")] - pub mem_backend: Option, + pub mem_backend: Option, /// Whether or not to enable KVM dirty page tracking. #[serde(default)] #[deprecated] @@ -106,7 +106,7 @@ pub struct LoadSnapshotConfig { /// Stores the configuration used for managing snapshot memory. #[derive(Debug, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct MemBackendConfig { +pub struct MemBackendSpec { /// Path to the backend used to handle the guest memory. pub backend_path: PathBuf, /// Specifies the guest memory backend type. diff --git a/src/vmm/src/vmm_config/vsock.rs b/src/vmm/src/vmm_config/vsock.rs index 920e4a4d217..2ae72bec683 100644 --- a/src/vmm/src/vmm_config/vsock.rs +++ b/src/vmm/src/vmm_config/vsock.rs @@ -10,9 +10,9 @@ use crate::devices::virtio::vsock::{Vsock, VsockError, VsockUnixBackend, VsockUn type MutexVsockUnix = Arc>>; -/// Errors associated with `NetworkInterfaceConfig`. +/// Errors associated with `VsockDeviceSpec`. #[derive(Debug, derive_more::From, thiserror::Error, displaydoc::Display)] -pub enum VsockConfigError { +pub enum VsockSpecError { /// Cannot create backend for vsock device: {0} CreateVsockBackend(VsockUnixBackendError), /// Cannot create vsock device: {0} @@ -23,7 +23,7 @@ pub enum VsockConfigError { /// from vsock related requests. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct VsockDeviceConfig { +pub struct VsockDeviceSpec { #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] /// ID of the vsock device. @@ -40,10 +40,10 @@ struct VsockAndUnixPath { uds_path: String, } -impl From<&VsockAndUnixPath> for VsockDeviceConfig { +impl From<&VsockAndUnixPath> for VsockDeviceSpec { fn from(vsock: &VsockAndUnixPath) -> Self { let vsock_lock = vsock.vsock.lock().unwrap(); - VsockDeviceConfig { + VsockDeviceSpec { vsock_id: None, guest_cid: u32::try_from(vsock_lock.cid()).unwrap(), uds_path: vsock.uds_path.clone(), @@ -51,7 +51,7 @@ impl From<&VsockAndUnixPath> for VsockDeviceConfig { } } -/// A builder of Vsock with Unix backend from 'VsockDeviceConfig'. +/// A builder of Vsock with Unix backend from 'VsockDeviceSpec'. #[derive(Debug, Default)] pub struct VsockBuilder { inner: Option, @@ -78,14 +78,14 @@ impl VsockBuilder { /// Inserts a Unix backend Vsock in the store. /// If an entry already exists, it will overwrite it. - pub fn insert(&mut self, cfg: VsockDeviceConfig) -> Result<(), VsockConfigError> { + pub fn insert(&mut self, spec: VsockDeviceSpec) -> Result<(), VsockSpecError> { // Make sure to drop the old one and remove the socket before creating a new one. if let Some(existing) = self.inner.take() { std::fs::remove_file(existing.uds_path).map_err(VsockUnixBackendError::UnixBind)?; } self.inner = Some(VsockAndUnixPath { - uds_path: cfg.uds_path.clone(), - vsock: Arc::new(Mutex::new(Self::create_unixsock_vsock(cfg)?)), + uds_path: spec.uds_path.clone(), + vsock: Arc::new(Mutex::new(Self::create_unixsock_vsock(spec)?)), }); Ok(()) } @@ -95,18 +95,18 @@ impl VsockBuilder { self.inner.as_ref().map(|pair| &pair.vsock) } - /// Creates a Vsock device from a VsockDeviceConfig. + /// Creates a Vsock device from a VsockDeviceSpec. pub fn create_unixsock_vsock( - cfg: VsockDeviceConfig, - ) -> Result, VsockConfigError> { - let backend = VsockUnixBackend::new(u64::from(cfg.guest_cid), cfg.uds_path)?; + spec: VsockDeviceSpec, + ) -> Result, VsockSpecError> { + let backend = VsockUnixBackend::new(u64::from(spec.guest_cid), spec.uds_path)?; - Vsock::new(u64::from(cfg.guest_cid), backend).map_err(VsockConfigError::CreateVsockDevice) + Vsock::new(u64::from(spec.guest_cid), backend).map_err(VsockSpecError::CreateVsockDevice) } - /// Returns the structure used to configure the vsock device. - pub fn config(&self) -> Option { - self.inner.as_ref().map(VsockDeviceConfig::from) + /// Returns the structure used to specify the vsock device. + pub fn spec(&self) -> Option { + self.inner.as_ref().map(VsockDeviceSpec::from) } } @@ -117,8 +117,8 @@ pub(crate) mod tests { use super::*; use crate::devices::virtio::vsock::VSOCK_DEV_ID; - pub(crate) fn default_config(tmp_sock_file: &TempFile) -> VsockDeviceConfig { - VsockDeviceConfig { + pub(crate) fn default_spec(tmp_sock_file: &TempFile) -> VsockDeviceSpec { + VsockDeviceSpec { vsock_id: None, guest_cid: 3, uds_path: tmp_sock_file.as_path().to_str().unwrap().to_string(), @@ -129,8 +129,8 @@ pub(crate) mod tests { fn test_vsock_create() { let mut tmp_sock_file = TempFile::new().unwrap(); tmp_sock_file.remove().unwrap(); - let vsock_config = default_config(&tmp_sock_file); - VsockBuilder::create_unixsock_vsock(vsock_config).unwrap(); + let vsock_spec = default_spec(&tmp_sock_file); + VsockBuilder::create_unixsock_vsock(vsock_spec).unwrap(); } #[test] @@ -138,30 +138,30 @@ pub(crate) mod tests { let mut store = VsockBuilder::new(); let mut tmp_sock_file = TempFile::new().unwrap(); tmp_sock_file.remove().unwrap(); - let mut vsock_config = default_config(&tmp_sock_file); + let mut vsock_spec = default_spec(&tmp_sock_file); - store.insert(vsock_config.clone()).unwrap(); + store.insert(vsock_spec.clone()).unwrap(); let vsock = store.get().unwrap(); assert_eq!(vsock.lock().unwrap().id(), VSOCK_DEV_ID); - let new_cid = vsock_config.guest_cid + 1; - vsock_config.guest_cid = new_cid; - store.insert(vsock_config).unwrap(); + let new_cid = vsock_spec.guest_cid + 1; + vsock_spec.guest_cid = new_cid; + store.insert(vsock_spec).unwrap(); let vsock = store.get().unwrap(); assert_eq!(vsock.lock().unwrap().cid(), u64::from(new_cid)); } #[test] - fn test_vsock_config() { + fn test_vsock_spec() { let mut vsock_builder = VsockBuilder::new(); let mut tmp_sock_file = TempFile::new().unwrap(); tmp_sock_file.remove().unwrap(); - let vsock_config = default_config(&tmp_sock_file); - vsock_builder.insert(vsock_config.clone()).unwrap(); + let vsock_spec = default_spec(&tmp_sock_file); + vsock_builder.insert(vsock_spec.clone()).unwrap(); - let config = vsock_builder.config(); - assert!(config.is_some()); - assert_eq!(config.unwrap(), vsock_config); + let spec = vsock_builder.spec(); + assert!(spec.is_some()); + assert_eq!(spec.unwrap(), vsock_spec); } #[test] diff --git a/src/vmm/tests/integration_tests.rs b/src/vmm/tests/integration_tests.rs index 6a5e6a08a14..5a611e86bb0 100644 --- a/src/vmm/tests/integration_tests.rs +++ b/src/vmm/tests/integration_tests.rs @@ -19,16 +19,16 @@ use vmm::seccomp::get_empty_filters; use vmm::snapshot::Snapshot; use vmm::test_utils::mock_resources::{MockVmResources, NOISY_KERNEL_IMAGE}; use vmm::test_utils::{create_vmm, default_vmm, default_vmm_no_boot}; -use vmm::vmm_config::balloon::BalloonDeviceConfig; -use vmm::vmm_config::boot_source::BootSourceConfig; -use vmm::vmm_config::drive::BlockDeviceConfig; +use vmm::vmm_config::balloon::BalloonDeviceSpec; +use vmm::vmm_config::boot_source::BootSourceSpec; +use vmm::vmm_config::drive::BlockDeviceSpec; use vmm::vmm_config::instance_info::{InstanceInfo, VmState}; -use vmm::vmm_config::machine_config::{MachineConfig, MachineConfigUpdate}; -use vmm::vmm_config::net::NetworkInterfaceConfig; +use vmm::vmm_config::machine_config::{MachineSpec, MachineSpecUpdate}; +use vmm::vmm_config::net::NetworkInterfaceSpec; use vmm::vmm_config::snapshot::{ - CreateSnapshotParams, LoadSnapshotParams, MemBackendConfig, MemBackendType, SnapshotType, + CreateSnapshotParams, LoadSnapshotParams, MemBackendSpec, MemBackendType, SnapshotType, }; -use vmm::vmm_config::vsock::VsockDeviceConfig; +use vmm::vmm_config::vsock::VsockDeviceSpec; use vmm::{DumpCpuConfigError, EventManager, FcExitCode, Vmm}; use vmm_sys_util::tempfile::TempFile; @@ -211,7 +211,7 @@ fn verify_create_snapshot( memory_hotplug, ); let resources = VmResources { - machine_config: MachineConfig { + machine_spec: MachineSpec { mem_size_mib: 1, track_dirty_pages: is_diff, ..Default::default() @@ -295,7 +295,7 @@ fn verify_load_snapshot(snapshot_file: TempFile, memory_file: TempFile) { preboot_api_controller .handle_preboot_request(VmmAction::LoadSnapshot(LoadSnapshotParams { snapshot_path: snapshot_file.as_path().to_path_buf(), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: memory_file.as_path().to_path_buf(), backend_type: MemBackendType::File, }, @@ -379,7 +379,7 @@ fn verify_load_snap_disallowed_after_boot_resources(res: VmmAction, res_name: &s // Load snapshot should no longer be allowed. let req = VmmAction::LoadSnapshot(LoadSnapshotParams { snapshot_path: snapshot_file.as_path().to_path_buf(), - mem_backend: MemBackendConfig { + mem_backend: MemBackendSpec { backend_path: memory_file.as_path().to_path_buf(), backend_type: MemBackendType::File, }, @@ -403,13 +403,13 @@ fn test_preboot_load_snap_disallowed_after_boot_resources() { let tmp_file = TempFile::new().unwrap(); let tmp_file = tmp_file.as_path().to_str().unwrap().to_string(); // Verify LoadSnapshot not allowed after configuring various boot-specific resources. - let req = VmmAction::ConfigureBootSource(BootSourceConfig { + let req = VmmAction::ConfigureBootSource(BootSourceSpec { kernel_image_path: tmp_file.clone(), ..Default::default() }); verify_load_snap_disallowed_after_boot_resources(req, "ConfigureBootSource"); - let config = BlockDeviceConfig { + let spec = BlockDeviceSpec { drive_id: String::new(), partuuid: None, is_root_device: false, @@ -423,10 +423,10 @@ fn test_preboot_load_snap_disallowed_after_boot_resources() { socket: None, }; - let req = VmmAction::InsertBlockDevice(config); + let req = VmmAction::InsertBlockDevice(spec); verify_load_snap_disallowed_after_boot_resources(req, "InsertBlockDevice"); - let req = VmmAction::InsertNetworkDevice(NetworkInterfaceConfig { + let req = VmmAction::InsertNetworkDevice(NetworkInterfaceSpec { iface_id: String::new(), host_dev_name: String::new(), guest_mac: None, @@ -435,17 +435,16 @@ fn test_preboot_load_snap_disallowed_after_boot_resources() { }); verify_load_snap_disallowed_after_boot_resources(req, "InsertNetworkDevice"); - let req = VmmAction::SetBalloonDevice(BalloonDeviceConfig::default()); + let req = VmmAction::SetBalloonDevice(BalloonDeviceSpec::default()); verify_load_snap_disallowed_after_boot_resources(req, "SetBalloonDevice"); - let req = VmmAction::SetVsockDevice(VsockDeviceConfig { + let req = VmmAction::SetVsockDevice(VsockDeviceSpec { vsock_id: Some(String::new()), guest_cid: 0, uds_path: String::new(), }); verify_load_snap_disallowed_after_boot_resources(req, "SetVsockDevice"); - let req = - VmmAction::UpdateMachineConfiguration(MachineConfigUpdate::from(MachineConfig::default())); + let req = VmmAction::UpdateMachineSpec(MachineSpecUpdate::from(MachineSpec::default())); verify_load_snap_disallowed_after_boot_resources(req, "SetVmConfiguration"); }