diff --git a/api_client/src/lib.rs b/api_client/src/lib.rs index b2bd4d9d6..3f87afdcb 100644 --- a/api_client/src/lib.rs +++ b/api_client/src/lib.rs @@ -22,16 +22,16 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use Error::*; match self { - Socket(e) => write!(f, "Error writing to or reading from HTTP socket: {}", e), - SocketSendFds(e) => write!(f, "Error writing to or reading from HTTP socket: {}", e), - StatusCodeParsing(e) => write!(f, "Error parsing HTTP status code: {}", e), + Socket(e) => write!(f, "Error writing to or reading from HTTP socket: {e}"), + SocketSendFds(e) => write!(f, "Error writing to or reading from HTTP socket: {e}"), + StatusCodeParsing(e) => write!(f, "Error parsing HTTP status code: {e}"), MissingProtocol => write!(f, "HTTP output is missing protocol statement"), - ContentLengthParsing(e) => write!(f, "Error parsing HTTP Content-Length field: {}", e), + ContentLengthParsing(e) => write!(f, "Error parsing HTTP Content-Length field: {e}"), ServerResponse(s, o) => { if let Some(o) = o { - write!(f, "Server responded with an error: {:?}: {}", s, o) + write!(f, "Server responded with an error: {s:?}: {o}") } else { - write!(f, "Server responded with an error: {:?}", s) + write!(f, "Server responded with an error: {s:?}") } } } @@ -79,7 +79,7 @@ impl StatusCode { } fn get_header<'a>(res: &'a str, header: &'a str) -> Option<&'a str> { - let header_str = format!("{}: ", header); + let header_str = format!("{header}: "); res.find(&header_str) .map(|o| &res[o + header_str.len()..o + res[o..].find('\r').unwrap()]) } @@ -153,8 +153,7 @@ pub fn simple_api_full_command_with_fds_and_response( ) -> Result<(), Error> { // Create the full VM command. For VMM commands, use // simple_api_full_command(). - let full_command = format!("vm.{}", c); + let full_command = format!("vm.{c}"); simple_api_full_command_with_fds(socket, method, &full_command, request_body, request_fds) } diff --git a/arch/src/aarch64/fdt.rs b/arch/src/aarch64/fdt.rs index 094deba37..2d6978ec2 100644 --- a/arch/src/aarch64/fdt.rs +++ b/arch/src/aarch64/fdt.rs @@ -160,7 +160,7 @@ fn create_cpu_nodes( let num_cpus = vcpu_mpidr.len(); for (cpu_id, mpidr) in vcpu_mpidr.iter().enumerate().take(num_cpus) { - let cpu_name = format!("cpu@{:x}", cpu_id); + let cpu_name = format!("cpu@{cpu_id:x}"); let cpu_node = fdt.begin_node(&cpu_name)?; fdt.property_string("device_type", "cpu")?; fdt.property_string("compatible", "arm,arm-v8")?; @@ -192,15 +192,15 @@ fn create_cpu_nodes( // Create device tree nodes with regard of above mapping. for cluster_idx in 0..packages { - let cluster_name = format!("cluster{:x}", cluster_idx); + let cluster_name = format!("cluster{cluster_idx:x}"); let cluster_node = fdt.begin_node(&cluster_name)?; for core_idx in 0..cores_per_package { - let core_name = format!("core{:x}", core_idx); + let core_name = format!("core{core_idx:x}"); let core_node = fdt.begin_node(&core_name)?; for thread_idx in 0..threads_per_core { - let thread_name = format!("thread{:x}", thread_idx); + let thread_name = format!("thread{thread_idx:x}"); let thread_node = fdt.begin_node(&thread_name)?; let cpu_idx = threads_per_core * cores_per_package * cluster_idx + threads_per_core * core_idx @@ -247,7 +247,7 @@ fn create_memory_node( node_memory_addr = memory_region_start_addr; } } - let memory_node_name = format!("memory@{:x}", node_memory_addr); + let memory_node_name = format!("memory@{node_memory_addr:x}"); let memory_node = fdt.begin_node(&memory_node_name)?; fdt.property_string("device_type", "memory")?; fdt.property_array_u64("reg", &mem_reg_prop)?; @@ -667,7 +667,7 @@ fn create_pci_nodes( // See kernel document Documentation/devicetree/bindings/virtio/iommu.txt // for virtio-iommu node settings. - let virtio_iommu_node_name = format!("virtio_iommu@{:x}", virtio_iommu_bdf); + let virtio_iommu_node_name = format!("virtio_iommu@{virtio_iommu_bdf:x}"); let virtio_iommu_node = fdt.begin_node(&virtio_iommu_node_name)?; fdt.property_u32("#iommu-cells", 1)?; fdt.property_string("compatible", "virtio,pci-iommu")?; diff --git a/arch/src/aarch64/uefi.rs b/arch/src/aarch64/uefi.rs index b394b2835..e773f17e8 100644 --- a/arch/src/aarch64/uefi.rs +++ b/arch/src/aarch64/uefi.rs @@ -34,9 +34,7 @@ where if uefi_size > 0x300000 { return Err(Error::UefiTooBig); } - uefi_image - .seek(SeekFrom::Start(0)) - .map_err(|_| Error::SeekUefiStart)?; + uefi_image.rewind().map_err(|_| Error::SeekUefiStart)?; guest_mem .read_exact_from(guest_addr, uefi_image, uefi_size) .map_err(|_| Error::ReadUefiImage) diff --git a/arch/src/lib.rs b/arch/src/lib.rs index 817a6b222..dc1f90d95 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -145,7 +145,7 @@ pub const PAGE_SIZE: usize = 4096; impl fmt::Display for DeviceType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/arch/src/x86_64/mod.rs b/arch/src/x86_64/mod.rs index af45c272d..5e8d663eb 100644 --- a/arch/src/x86_64/mod.rs +++ b/arch/src/x86_64/mod.rs @@ -1320,6 +1320,6 @@ mod tests { add_memmap_entry(&mut memmap, 0, 0x1000, E820_RAM); add_memmap_entry(&mut memmap, 0x10000, 0xa000, E820_RESERVED); - assert_eq!(format!("{:?}", memmap), format!("{:?}", expected_memmap)); + assert_eq!(format!("{memmap:?}"), format!("{expected_memmap:?}")); } } diff --git a/arch/src/x86_64/mptable.rs b/arch/src/x86_64/mptable.rs index d41bb4ae8..320032bdc 100644 --- a/arch/src/x86_64/mptable.rs +++ b/arch/src/x86_64/mptable.rs @@ -300,7 +300,7 @@ mod tests { mpspec::MP_IOAPIC => mem::size_of::(), mpspec::MP_INTSRC => mem::size_of::(), mpspec::MP_LINTSRC => mem::size_of::(), - _ => panic!("unrecognized mpc table entry type: {}", type_), + _ => panic!("unrecognized mpc table entry type: {type_}"), } } diff --git a/arch/src/x86_64/smbios.rs b/arch/src/x86_64/smbios.rs index 7de5eceee..ef083dc8c 100644 --- a/arch/src/x86_64/smbios.rs +++ b/arch/src/x86_64/smbios.rs @@ -48,10 +48,10 @@ impl Display for Error { Clear => "Failure while zeroing out the memory for the SMBIOS table".to_string(), WriteSmbiosEp => "Failure to write SMBIOS entrypoint structure".to_string(), WriteData => "Failure to write additional data to memory".to_string(), - ParseUuid(e) => format!("Failure to parse uuid: {}", e), + ParseUuid(e) => format!("Failure to parse uuid: {e}"), }; - write!(f, "SMBIOS error: {}", description) + write!(f, "SMBIOS error: {description}") } } diff --git a/arch/src/x86_64/tdx/mod.rs b/arch/src/x86_64/tdx/mod.rs index 79604236c..828dd37e8 100644 --- a/arch/src/x86_64/tdx/mod.rs +++ b/arch/src/x86_64/tdx/mod.rs @@ -541,7 +541,7 @@ mod tests { let mut f = std::fs::File::open("tdvf.fd").unwrap(); let (sections, _) = parse_tdvf_sections(&mut f).unwrap(); for section in sections { - eprintln!("{:x?}", section) + eprintln!("{section:x?}") } } } diff --git a/build.rs b/build.rs index 8cbbf1c62..3c0c84df8 100644 --- a/build.rs +++ b/build.rs @@ -23,5 +23,5 @@ fn main() { // variable BUILT_VERSION, so that it can be reused from the binary. // Particularly, this is used from src/main.rs to display the exact // version. - println!("cargo:rustc-env=BUILT_VERSION={}", version); + println!("cargo:rustc-env=BUILT_VERSION={version}"); } diff --git a/devices/src/legacy/debug_port.rs b/devices/src/legacy/debug_port.rs index 2568e9c8c..14fecfe79 100644 --- a/devices/src/legacy/debug_port.rs +++ b/devices/src/legacy/debug_port.rs @@ -40,11 +40,11 @@ impl DebugIoPortRange { impl fmt::Display for DebugIoPortRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - DebugIoPortRange::Firmware => write!(f, "{}: Firmware", DEBUG_IOPORT_PREFIX), - DebugIoPortRange::Bootloader => write!(f, "{}: Bootloader", DEBUG_IOPORT_PREFIX), - DebugIoPortRange::Kernel => write!(f, "{}: Kernel", DEBUG_IOPORT_PREFIX), - DebugIoPortRange::Userspace => write!(f, "{}: Userspace", DEBUG_IOPORT_PREFIX), - DebugIoPortRange::Custom => write!(f, "{}: Custom", DEBUG_IOPORT_PREFIX), + DebugIoPortRange::Firmware => write!(f, "{DEBUG_IOPORT_PREFIX}: Firmware"), + DebugIoPortRange::Bootloader => write!(f, "{DEBUG_IOPORT_PREFIX}: Bootloader"), + DebugIoPortRange::Kernel => write!(f, "{DEBUG_IOPORT_PREFIX}: Kernel"), + DebugIoPortRange::Userspace => write!(f, "{DEBUG_IOPORT_PREFIX}: Userspace"), + DebugIoPortRange::Custom => write!(f, "{DEBUG_IOPORT_PREFIX}: Custom"), } } } diff --git a/devices/src/legacy/gpio_pl061.rs b/devices/src/legacy/gpio_pl061.rs index 4aa027056..ed52cad60 100644 --- a/devices/src/legacy/gpio_pl061.rs +++ b/devices/src/legacy/gpio_pl061.rs @@ -51,13 +51,13 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {}", offset), + Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {offset}"), Error::GpioInterruptDisabled => write!(f, "GPIO interrupt disabled by guest driver.",), Error::GpioInterruptFailure(ref e) => { - write!(f, "Could not trigger GPIO interrupt: {}.", e) + write!(f, "Could not trigger GPIO interrupt: {e}.") } Error::GpioTriggerKeyFailure(key) => { - write!(f, "Invalid GPIO Input key triggerd: {}.", key) + write!(f, "Invalid GPIO Input key triggerd: {key}.") } } } diff --git a/devices/src/legacy/rtc_pl031.rs b/devices/src/legacy/rtc_pl031.rs index 6d157cbc3..b9bd627bf 100644 --- a/devices/src/legacy/rtc_pl031.rs +++ b/devices/src/legacy/rtc_pl031.rs @@ -48,8 +48,8 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {}", offset), - Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {}", e), + Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {offset}"), + Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {e}"), } } } diff --git a/devices/src/legacy/uart_pl011.rs b/devices/src/legacy/uart_pl011.rs index c57b79e6c..538e0e404 100644 --- a/devices/src/legacy/uart_pl011.rs +++ b/devices/src/legacy/uart_pl011.rs @@ -60,11 +60,11 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Error::BadWriteOffset(offset) => write!(f, "pl011_write: Bad Write Offset: {}", offset), + Error::BadWriteOffset(offset) => write!(f, "pl011_write: Bad Write Offset: {offset}"), Error::DmaNotImplemented => write!(f, "pl011: DMA not implemented."), - Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {}", e), - Error::WriteAllFailure(e) => write!(f, "Failed to write: {}", e), - Error::FlushFailure(e) => write!(f, "Failed to flush: {}", e), + Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {e}"), + Error::WriteAllFailure(e) => write!(f, "Failed to write: {e}"), + Error::FlushFailure(e) => write!(f, "Failed to flush: {e}"), } } } diff --git a/devices/src/tpm.rs b/devices/src/tpm.rs index e38700358..bd9104da9 100644 --- a/devices/src/tpm.rs +++ b/devices/src/tpm.rs @@ -117,10 +117,7 @@ fn get_fields_map(reg: u32) -> phf::Map<&'static str, [u32; 2]> { CRB_INTF_ID2 => CRB_INTF_ID2_FIELDS, CRB_CTRL_STS => CRB_CTRL_STS_FIELDS, _ => { - panic!( - "Fields in '{:?}' register were accessed which are Invalid", - reg - ); + panic!("Fields in '{reg:?}' register were accessed which are Invalid"); } } } diff --git a/hypervisor/src/arch/emulator/mod.rs b/hypervisor/src/arch/emulator/mod.rs index 507918c95..f3a5d8417 100644 --- a/hypervisor/src/arch/emulator/mod.rs +++ b/hypervisor/src/arch/emulator/mod.rs @@ -24,10 +24,10 @@ impl Display for Exception { self.vector, self.ip, self.error - .map(|e| format!(": error {:x}", e)) + .map(|e| format!(": error {e:x}")) .unwrap_or_else(|| "".to_owned()), self.payload - .map(|payload| format!(": payload {:x}", payload)) + .map(|payload| format!(": payload {payload:x}")) .unwrap_or_else(|| "".to_owned()) ) } diff --git a/hypervisor/src/kvm/aarch64/mod.rs b/hypervisor/src/kvm/aarch64/mod.rs index 7712508ec..7d734b62d 100644 --- a/hypervisor/src/kvm/aarch64/mod.rs +++ b/hypervisor/src/kvm/aarch64/mod.rs @@ -97,8 +97,7 @@ pub fn is_system_register(regid: u64) -> bool { assert!( !(size != KVM_REG_SIZE_U32 && size != KVM_REG_SIZE_U64), - "Unexpected register size for system register {}", - size + "Unexpected register size for system register {size}" ); true diff --git a/net_util/src/mac.rs b/net_util/src/mac.rs index b0dcfe409..feb3492fb 100644 --- a/net_util/src/mac.rs +++ b/net_util/src/mac.rs @@ -125,7 +125,7 @@ impl<'de> Deserialize<'de> for MacAddr { { let s = String::deserialize(deserializer)?; MacAddr::parse_str(&s) - .map_err(|e| D::Error::custom(format!("The provided MAC address is invalid: {}", e))) + .map_err(|e| D::Error::custom(format!("The provided MAC address is invalid: {e}"))) } } @@ -161,7 +161,7 @@ mod tests { let mac = MacAddr::parse_str("12:34:56:78:9a:BC").unwrap(); - println!("parsed MAC address: {}", mac); + println!("parsed MAC address: {mac}"); let bytes = mac.get_bytes(); assert_eq!(bytes, [0x12u8, 0x34, 0x56, 0x78, 0x9a, 0xbc]); diff --git a/net_util/src/open_tap.rs b/net_util/src/open_tap.rs index 60dbf0c29..dd5d49868 100644 --- a/net_util/src/open_tap.rs +++ b/net_util/src/open_tap.rs @@ -41,7 +41,7 @@ type Result = std::result::Result; fn check_mq_support(if_name: &Option<&str>, queue_pairs: usize) -> Result<()> { if let Some(tap_name) = if_name { let mq = queue_pairs > 1; - let path = format!("/sys/class/net/{}/tun_flags", tap_name); + let path = format!("/sys/class/net/{tap_name}/tun_flags"); // interface does not exist, check is not required if !Path::new(&path).exists() { return Ok(()); diff --git a/net_util/src/tap.rs b/net_util/src/tap.rs index c795dd8f0..cec7b88b8 100644 --- a/net_util/src/tap.rs +++ b/net_util/src/tap.rs @@ -581,7 +581,7 @@ mod tests { let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); let t = Tap::new(1).unwrap(); - println!("created tap: {:?}", t); + println!("created tap: {t:?}"); } #[test] diff --git a/option_parser/src/lib.rs b/option_parser/src/lib.rs index 3da99bbc6..fb2dbfc83 100644 --- a/option_parser/src/lib.rs +++ b/option_parser/src/lib.rs @@ -28,10 +28,10 @@ pub enum OptionParserError { impl fmt::Display for OptionParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - OptionParserError::UnknownOption(s) => write!(f, "unknown option: {}", s), - OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{}", s), + OptionParserError::UnknownOption(s) => write!(f, "unknown option: {s}"), + OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{s}"), OptionParserError::Conversion(field, value) => { - write!(f, "unable to convert {} for {}", value, field) + write!(f, "unable to convert {value} for {field}") } } } diff --git a/pci/src/configuration.rs b/pci/src/configuration.rs index 061dabe02..2e714d04e 100644 --- a/pci/src/configuration.rs +++ b/pci/src/configuration.rs @@ -516,9 +516,9 @@ impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { - BarAddressInvalid(a, s) => write!(f, "address {} size {} too big", a, s), - BarInUse(b) => write!(f, "bar {} already used", b), - BarInUse64(b) => write!(f, "64bit bar {} already used(requires two regs)", b), + BarAddressInvalid(a, s) => write!(f, "address {a} size {s} too big"), + BarInUse(b) => write!(f, "bar {b} already used"), + BarInUse64(b) => write!(f, "64bit bar {b} already used(requires two regs)"), BarInvalid(b) => write!(f, "bar {} invalid, max {}", b, NUM_BAR_REGS - 1), BarInvalid64(b) => write!( f, @@ -526,18 +526,18 @@ impl Display for Error { b, NUM_BAR_REGS - 1 ), - BarSizeInvalid(s) => write!(f, "bar address {} not a power of two", s), + BarSizeInvalid(s) => write!(f, "bar address {s} not a power of two"), CapabilityEmpty => write!(f, "empty capabilities are invalid"), - CapabilityLengthInvalid(l) => write!(f, "Invalid capability length {}", l), - CapabilitySpaceFull(s) => write!(f, "capability of size {} doesn't fit", s), + CapabilityLengthInvalid(l) => write!(f, "Invalid capability length {l}"), + CapabilitySpaceFull(s) => write!(f, "capability of size {s} doesn't fit"), Decode32BarSize => write!(f, "failed to decode 32 bits BAR size"), Decode64BarSize => write!(f, "failed to decode 64 bits BAR size"), Encode32BarSize => write!(f, "failed to encode 32 bits BAR size"), Encode64BarSize => write!(f, "failed to encode 64 bits BAR size"), - RomBarAddressInvalid(a, s) => write!(f, "address {} size {} too big", a, s), - RomBarInUse(b) => write!(f, "rom bar {} already used", b), + RomBarAddressInvalid(a, s) => write!(f, "address {a} size {s} too big"), + RomBarInUse(b) => write!(f, "rom bar {b} already used"), RomBarInvalid(b) => write!(f, "rom bar {} invalid, max {}", b, NUM_BAR_REGS - 1), - RomBarSizeInvalid(s) => write!(f, "rom bar address {} not a power of two", s), + RomBarSizeInvalid(s) => write!(f, "rom bar address {s} not a power of two"), } } } diff --git a/pci/src/device.rs b/pci/src/device.rs index 1a49beb18..f51e3902f 100644 --- a/pci/src/device.rs +++ b/pci/src/device.rs @@ -31,15 +31,15 @@ impl Display for Error { use self::Error::*; match self { - CapabilitiesSetup(e) => write!(f, "failed to add capability {}", e), + CapabilitiesSetup(e) => write!(f, "failed to add capability {e}"), IoAllocationFailed(size) => { - write!(f, "failed to allocate space for an IO BAR, size={}", size) + write!(f, "failed to allocate space for an IO BAR, size={size}") } IoRegistrationFailed(addr, e) => { - write!(f, "failed to register an IO BAR, addr={} err={}", addr, e) + write!(f, "failed to register an IO BAR, addr={addr} err={e}") } MissingResource => write!(f, "failed to find expected resource"), - InvalidResource(r) => write!(f, "invalid resource {:?}", r), + InvalidResource(r) => write!(f, "invalid resource {r:?}"), } } } diff --git a/pci/src/vfio_user.rs b/pci/src/vfio_user.rs index 1d0eb1c86..5033b55dd 100644 --- a/pci/src/vfio_user.rs +++ b/pci/src/vfio_user.rs @@ -575,13 +575,13 @@ impl ExternalDmaMapping for VfioUserDmaMappi .map_err(|e| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Error mapping region: {}", e), + format!("Error mapping region: {e}"), ) }) } else { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("Region not found for 0x{:x}", gpa), + format!("Region not found for 0x{gpa:x}"), )) } } @@ -594,7 +594,7 @@ impl ExternalDmaMapping for VfioUserDmaMappi .map_err(|e| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Error unmapping region: {}", e), + format!("Error unmapping region: {e}"), ) }) } diff --git a/performance-metrics/build.rs b/performance-metrics/build.rs index 1e94e2b98..0898cac38 100644 --- a/performance-metrics/build.rs +++ b/performance-metrics/build.rs @@ -22,5 +22,5 @@ fn main() { // variable GIT_HUMAN_READABLE, so that it can be reused from the binary. // Particularly, this is used from the main.rs to display the exact // version information. - println!("cargo:rustc-env=GIT_HUMAN_READABLE={}", git_human_readable); + println!("cargo:rustc-env=GIT_HUMAN_READABLE={git_human_readable}"); } diff --git a/performance-metrics/src/main.rs b/performance-metrics/src/main.rs index ce1542196..c3394d913 100644 --- a/performance-metrics/src/main.rs +++ b/performance-metrics/src/main.rs @@ -117,7 +117,7 @@ pub struct PerformanceTestOverrides { impl fmt::Display for PerformanceTestOverrides { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(test_iterations) = self.test_iterations { - write!(f, "test_iterations = {}", test_iterations)?; + write!(f, "test_iterations = {test_iterations}")?; } Ok(()) @@ -141,19 +141,19 @@ impl fmt::Display for PerformanceTestControl { self.test_timeout, self.test_iterations ); if let Some(o) = self.num_queues { - output = format!("{}, num_queues = {}", output, o); + output = format!("{output}, num_queues = {o}"); } if let Some(o) = self.queue_size { - output = format!("{}, queue_size = {}", output, o); + output = format!("{output}, queue_size = {o}"); } if let Some(o) = self.net_rx { - output = format!("{}, net_rx = {}", output, o); + output = format!("{output}, net_rx = {o}"); } if let Some(o) = &self.fio_ops { - output = format!("{}, fio_ops = {}", output, o); + output = format!("{output}, fio_ops = {o}"); } - write!(f, "{}", output) + write!(f, "{output}") } } @@ -569,7 +569,7 @@ fn main() { metrics_report.results.push(r); } Err(e) => { - eprintln!("Aborting test due to error: '{:?}'", e); + eprintln!("Aborting test due to error: '{e:?}'"); std::process::exit(1); } }; @@ -583,7 +583,7 @@ fn main() { Box::new( std::fs::File::create(std::path::Path::new(file)) .map_err(|e| { - eprintln!("Error opening report file: {}: {}", file, e); + eprintln!("Error opening report file: {file}: {e}"); std::process::exit(1); }) .unwrap(), @@ -599,7 +599,7 @@ fn main() { .as_bytes(), ) .map_err(|e| { - eprintln!("Error writing report file: {}", e); + eprintln!("Error writing report file: {e}"); std::process::exit(1); }) .unwrap(); diff --git a/performance-metrics/src/performance_tests.rs b/performance-metrics/src/performance_tests.rs index 2c4966517..707ee8719 100644 --- a/performance-metrics/src/performance_tests.rs +++ b/performance-metrics/src/performance_tests.rs @@ -37,8 +37,7 @@ pub fn init_tests() { // The test image can not be created on tmpfs (e.g. /tmp) filesystem, // as tmpfs does not support O_DIRECT assert!(exec_host_command_output(&format!( - "dd if=/dev/zero of={} bs=1M count=4096", - BLK_IO_TEST_IMG + "dd if=/dev/zero of={BLK_IO_TEST_IMG} bs=1M count=4096" )) .status .success()); @@ -46,7 +45,7 @@ pub fn init_tests() { pub fn cleanup_tests() { fs::remove_file(BLK_IO_TEST_IMG) - .unwrap_or_else(|_| panic!("Failed to remove file '{}'.", BLK_IO_TEST_IMG)); + .unwrap_or_else(|_| panic!("Failed to remove file '{BLK_IO_TEST_IMG}'.")); } // Performance tests are expected to be executed sequentially, so we can @@ -92,7 +91,7 @@ pub fn performance_net_throughput(control: &PerformanceTestControl) -> f64 { ); let mut child = GuestCommand::new(&guest) - .args(["--cpus", &format!("boot={}", num_queues)]) + .args(["--cpus", &format!("boot={num_queues}")]) .args(["--memory", "size=4G"]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -133,7 +132,7 @@ pub fn performance_net_latency(control: &PerformanceTestControl) -> f64 { ); let mut child = GuestCommand::new(&guest) - .args(["--cpus", &format!("boot={}", num_queues)]) + .args(["--cpus", &format!("boot={num_queues}")]) .args(["--memory", "size=4G"]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -349,7 +348,7 @@ pub fn performance_block_io(control: &PerformanceTestControl) -> f64 { .to_string(); let mut child = GuestCommand::new(&guest) - .args(["--cpus", &format!("boot={}", num_queues)]) + .args(["--cpus", &format!("boot={num_queues}")]) .args(["--memory", "size=4G"]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -365,7 +364,7 @@ pub fn performance_block_io(control: &PerformanceTestControl) -> f64 { guest.disk_config.disk(DiskType::CloudInit).unwrap() ) .as_str(), - format!("path={}", BLK_IO_TEST_IMG).as_str(), + format!("path={BLK_IO_TEST_IMG}").as_str(), ]) .default_net() .args(["--api-socket", &api_socket]) @@ -381,8 +380,7 @@ pub fn performance_block_io(control: &PerformanceTestControl) -> f64 { let fio_command = format!( "sudo fio --filename=/dev/vdc --name=test --output-format=json \ --direct=1 --bs=4k --ioengine=io_uring --iodepth=64 \ - --rw={} --runtime={} --numjobs={}", - fio_ops, test_timeout, num_queues + --rw={fio_ops} --runtime={test_timeout} --numjobs={num_queues}" ); let output = guest .ssh_command(&fio_command) diff --git a/qcow/src/qcow.rs b/qcow/src/qcow.rs index c22e32dcb..40c2e16fe 100644 --- a/qcow/src/qcow.rs +++ b/qcow/src/qcow.rs @@ -80,45 +80,41 @@ impl Display for Error { match self { BackingFilesNotSupported => write!(f, "backing files not supported"), CompressedBlocksNotSupported => write!(f, "compressed blocks not supported"), - EvictingCache(e) => write!(f, "failed to evict cache: {}", e), - FileTooBig(size) => write!( - f, - "file larger than max of {}: {}", - MAX_QCOW_FILE_SIZE, size - ), - GettingFileSize(e) => write!(f, "failed to get file size: {}", e), - GettingRefcount(e) => write!(f, "failed to get refcount: {}", e), + EvictingCache(e) => write!(f, "failed to evict cache: {e}"), + FileTooBig(size) => write!(f, "file larger than max of {MAX_QCOW_FILE_SIZE}: {size}"), + GettingFileSize(e) => write!(f, "failed to get file size: {e}"), + GettingRefcount(e) => write!(f, "failed to get refcount: {e}"), InvalidClusterIndex => write!(f, "invalid cluster index"), InvalidClusterSize => write!(f, "invalid cluster size"), InvalidIndex => write!(f, "invalid index"), InvalidL1TableOffset => write!(f, "invalid L1 table offset"), - InvalidL1TableSize(size) => write!(f, "invalid L1 table size {}", size), + InvalidL1TableSize(size) => write!(f, "invalid L1 table size {size}"), InvalidMagic => write!(f, "invalid magic"), InvalidOffset(_) => write!(f, "invalid offset"), InvalidRefcountTableOffset => write!(f, "invalid refcount table offset"), - InvalidRefcountTableSize(size) => write!(f, "invalid refcount table size: {}", size), + InvalidRefcountTableSize(size) => write!(f, "invalid refcount table size: {size}"), NoFreeClusters => write!(f, "no free clusters"), NoRefcountClusters => write!(f, "no refcount clusters"), NotEnoughSpaceForRefcounts => write!(f, "not enough space for refcounts"), - OpeningFile(e) => write!(f, "failed to open file: {}", e), - ReadingData(e) => write!(f, "failed to read data: {}", e), - ReadingHeader(e) => write!(f, "failed to read header: {}", e), - ReadingPointers(e) => write!(f, "failed to read pointers: {}", e), - ReadingRefCountBlock(e) => write!(f, "failed to read ref count block: {}", e), - ReadingRefCounts(e) => write!(f, "failed to read ref counts: {}", e), - RebuildingRefCounts(e) => write!(f, "failed to rebuild ref counts: {}", e), + OpeningFile(e) => write!(f, "failed to open file: {e}"), + ReadingData(e) => write!(f, "failed to read data: {e}"), + ReadingHeader(e) => write!(f, "failed to read header: {e}"), + ReadingPointers(e) => write!(f, "failed to read pointers: {e}"), + ReadingRefCountBlock(e) => write!(f, "failed to read ref count block: {e}"), + ReadingRefCounts(e) => write!(f, "failed to read ref counts: {e}"), + RebuildingRefCounts(e) => write!(f, "failed to rebuild ref counts: {e}"), RefcountTableOffEnd => write!(f, "refcount table offset past file end"), RefcountTableTooLarge => write!(f, "too many clusters specified for refcount table"), - SeekingFile(e) => write!(f, "failed to seek file: {}", e), - SettingFileSize(e) => write!(f, "failed to set file size: {}", e), - SettingRefcountRefcount(e) => write!(f, "failed to set refcount refcount: {}", e), + SeekingFile(e) => write!(f, "failed to seek file: {e}"), + SettingFileSize(e) => write!(f, "failed to set file size: {e}"), + SettingRefcountRefcount(e) => write!(f, "failed to set refcount refcount: {e}"), SizeTooSmallForNumberOfClusters => write!(f, "size too small for number of clusters"), - TooManyL1Entries(count) => write!(f, "l1 entry table too large: {}", count), - TooManyRefcounts(count) => write!(f, "ref count table too large: {}", count), + TooManyL1Entries(count) => write!(f, "l1 entry table too large: {count}"), + TooManyRefcounts(count) => write!(f, "ref count table too large: {count}"), UnsupportedRefcountOrder => write!(f, "unsupported refcount order"), - UnsupportedVersion(v) => write!(f, "unsupported version: {}", v), - WritingData(e) => write!(f, "failed to write data: {}", e), - WritingHeader(e) => write!(f, "failed to write header: {}", e), + UnsupportedVersion(v) => write!(f, "unsupported version: {v}"), + WritingData(e) => write!(f, "failed to write data: {e}"), + WritingHeader(e) => write!(f, "failed to write header: {e}"), } } } @@ -190,7 +186,7 @@ pub struct QcowHeader { impl QcowHeader { /// Creates a QcowHeader from a reference to a file. pub fn new(f: &mut RawFile) -> Result { - f.seek(SeekFrom::Start(0)).map_err(Error::ReadingHeader)?; + f.rewind().map_err(Error::ReadingHeader)?; let magic = f.read_u32::().map_err(Error::ReadingHeader)?; if magic != QCOW_MAGIC { return Err(Error::InvalidMagic); @@ -559,7 +555,7 @@ impl QcowFile { /// Creates a new QcowFile at the given path. pub fn new(mut file: RawFile, version: u32, virtual_size: u64) -> Result { let header = QcowHeader::create_for_size(version, virtual_size); - file.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?; + file.rewind().map_err(Error::SeekingFile)?; header.write_to(&mut file)?; let mut qcow = Self::from(file)?; @@ -812,10 +808,7 @@ impl QcowFile { ) -> Result<()> { // Rewrite the header with lazy refcounts enabled while we are rebuilding the tables. header.compatible_features |= COMPATIBLE_FEATURES_LAZY_REFCOUNTS; - raw_file - .file_mut() - .seek(SeekFrom::Start(0)) - .map_err(Error::SeekingFile)?; + raw_file.file_mut().rewind().map_err(Error::SeekingFile)?; header.write_to(raw_file.file_mut())?; for (i, refblock_addr) in ref_table.iter().enumerate() { @@ -850,10 +843,7 @@ impl QcowFile { // Rewrite the header again, now with lazy refcounts disabled. header.compatible_features &= !COMPATIBLE_FEATURES_LAZY_REFCOUNTS; - raw_file - .file_mut() - .seek(SeekFrom::Start(0)) - .map_err(Error::SeekingFile)?; + raw_file.file_mut().rewind().map_err(Error::SeekingFile)?; header.write_to(raw_file.file_mut())?; Ok(()) @@ -1240,7 +1230,7 @@ impl QcowFile { .map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, - format!("failed to get cluster refcount: {}", e), + format!("failed to get cluster refcount: {e}"), ) })?; if refcount == 0 { @@ -1656,9 +1646,7 @@ where R: Read + Seek + SeekHole, { let src_size = reader.seek(SeekFrom::End(0)).map_err(Error::SeekingFile)?; - reader - .seek(SeekFrom::Start(0)) - .map_err(Error::SeekingFile)?; + reader.rewind().map_err(Error::SeekingFile)?; // Ensure the destination file is empty before writing to it. dst_file.set_len(0).map_err(Error::SettingFileSize)?; @@ -1700,10 +1688,8 @@ pub fn convert(mut src_file: RawFile, dst_file: RawFile, dst_type: ImageType) -> /// Detect the type of an image file by checking for a valid qcow2 header. pub fn detect_image_type(file: &mut RawFile) -> Result { - let orig_seek = file - .seek(SeekFrom::Current(0)) - .map_err(Error::SeekingFile)?; - file.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?; + let orig_seek = file.stream_position().map_err(Error::SeekingFile)?; + file.rewind().map_err(Error::SeekingFile)?; let magic = file.read_u32::().map_err(Error::ReadingHeader)?; let image_type = if magic == QCOW_MAGIC { ImageType::Qcow2 @@ -1794,7 +1780,7 @@ mod tests { let mut disk_file: RawFile = RawFile::new(TempFile::new().unwrap().into_file(), false); disk_file.write_all(header).unwrap(); disk_file.set_len(0x1_0000_0000).unwrap(); - disk_file.seek(SeekFrom::Start(0)).unwrap(); + disk_file.rewind().unwrap(); testfn(disk_file); // File closed when the function exits. } @@ -1816,7 +1802,7 @@ mod tests { header .write_to(&mut disk_file) .expect("Failed to write header to temporary file."); - disk_file.seek(SeekFrom::Start(0)).unwrap(); + disk_file.rewind().unwrap(); QcowFile::from(disk_file).expect("Failed to create Qcow from default Header"); } @@ -1827,7 +1813,7 @@ mod tests { header .write_to(&mut disk_file) .expect("Failed to write header to temporary file."); - disk_file.seek(SeekFrom::Start(0)).unwrap(); + disk_file.rewind().unwrap(); QcowFile::from(disk_file).expect("Failed to create Qcow from default Header"); } @@ -1955,7 +1941,7 @@ mod tests { q.write_all(b"test first bytes") .expect("Failed to write test string."); let mut buf = [0u8; 4]; - q.seek(SeekFrom::Start(0)).expect("Failed to seek."); + q.rewind().expect("Failed to seek."); q.read_exact(&mut buf).expect("Failed to read."); assert_eq!(&buf, b"test"); }); @@ -2007,15 +1993,15 @@ mod tests { let mut q = QcowFile::from(disk_file).unwrap(); // Write some test data. let b = [0x55u8; CHUNK_SIZE]; - q.seek(SeekFrom::Start(0)).expect("Failed to seek."); + q.rewind().expect("Failed to seek."); q.write_all(&b).expect("Failed to write test string."); // Overwrite the full cluster with zeroes. - q.seek(SeekFrom::Start(0)).expect("Failed to seek."); + q.rewind().expect("Failed to seek."); let nwritten = q.write_zeroes(CHUNK_SIZE).expect("Failed to write zeroes."); assert_eq!(nwritten, CHUNK_SIZE); // Verify that the data was zeroed out. let mut buf = [0u8; CHUNK_SIZE]; - q.seek(SeekFrom::Start(0)).expect("Failed to seek."); + q.rewind().expect("Failed to seek."); q.read_exact(&mut buf).expect("Failed to read."); assert_eq!(buf[0], 0); assert_eq!(buf[CHUNK_SIZE - 1], 0); @@ -2457,7 +2443,7 @@ mod tests { } } // Check that address 0 is still zeros. - qcow_file.seek(SeekFrom::Start(0)).expect("Failed to seek."); + qcow_file.rewind().expect("Failed to seek."); let nread = qcow_file.read(&mut readback).expect("Failed to read."); assert_eq!(nread, BLOCK_SIZE); for read in readback.iter() { @@ -2481,7 +2467,7 @@ mod tests { } fn seek_cur(file: &mut QcowFile) -> u64 { - file.seek(SeekFrom::Current(0)).unwrap() + file.stream_position().unwrap() } #[test] @@ -2545,7 +2531,7 @@ mod tests { assert_eq!(seek_cur(&mut file), 0xFFFF); // seek_hole at or after the end of the file should return None - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x30000).unwrap(), None); assert_eq!(seek_cur(&mut file), 0); assert_eq!(file.seek_hole(0x30001).unwrap(), None); @@ -2563,33 +2549,33 @@ mod tests { assert_eq!(seek_cur(&mut file), 0xFFFF); // seek_hole within data should return the next hole - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x10000).unwrap(), Some(0x20000)); assert_eq!(seek_cur(&mut file), 0x20000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x10001).unwrap(), Some(0x20000)); assert_eq!(seek_cur(&mut file), 0x20000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x1FFFF).unwrap(), Some(0x20000)); assert_eq!(seek_cur(&mut file), 0x20000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0xFFFF).unwrap(), Some(0xFFFF)); assert_eq!(seek_cur(&mut file), 0xFFFF); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x10000).unwrap(), Some(0x20000)); assert_eq!(seek_cur(&mut file), 0x20000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x1FFFF).unwrap(), Some(0x20000)); assert_eq!(seek_cur(&mut file), 0x20000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x20000).unwrap(), Some(0x20000)); assert_eq!(seek_cur(&mut file), 0x20000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x20001).unwrap(), Some(0x20001)); assert_eq!(seek_cur(&mut file), 0x20001); // seek_hole at EOF should return None - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x30000).unwrap(), None); assert_eq!(seek_cur(&mut file), 0); @@ -2600,10 +2586,10 @@ mod tests { // seek_hole within [0x20000, 0x30000) should now find the hole at EOF assert_eq!(file.seek_hole(0x20000).unwrap(), Some(0x30000)); assert_eq!(seek_cur(&mut file), 0x30000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x20001).unwrap(), Some(0x30000)); assert_eq!(seek_cur(&mut file), 0x30000); - file.seek(SeekFrom::Start(0)).unwrap(); + file.rewind().unwrap(); assert_eq!(file.seek_hole(0x30000).unwrap(), None); assert_eq!(seek_cur(&mut file), 0); }); diff --git a/qcow/src/refcount.rs b/qcow/src/refcount.rs index ab3968cb7..eee415d0a 100644 --- a/qcow/src/refcount.rs +++ b/qcow/src/refcount.rs @@ -31,16 +31,14 @@ impl Display for Error { use self::Error::*; match self { - EvictingRefCounts(e) => write!( - f, - "failed to write a refblock from the cache to disk: {}", - e - ), + EvictingRefCounts(e) => { + write!(f, "failed to write a refblock from the cache to disk: {e}") + } InvalidIndex => write!(f, "address requested is not within the range of the disk"), - NeedCluster(addr) => write!(f, "cluster with addr={} needs to be read", addr), + NeedCluster(addr) => write!(f, "cluster with addr={addr} needs to be read"), NeedNewCluster => write!(f, "new cluster needs to be allocated for refcounts"), ReadingRefCounts(e) => { - write!(f, "failed to read the file into the refcount cache: {}", e) + write!(f, "failed to read the file into the refcount cache: {e}") } } } diff --git a/rate_limiter/src/lib.rs b/rate_limiter/src/lib.rs index 9eefe934c..977704668 100644 --- a/rate_limiter/src/lib.rs +++ b/rate_limiter/src/lib.rs @@ -889,7 +889,7 @@ pub(crate) mod tests { fn test_rate_limiter_debug() { let l = RateLimiter::new(1, 2, 3, 4, 5, 6).unwrap(); assert_eq!( - format!("{:?}", l), + format!("{l:?}"), format!( "RateLimiter {{ bandwidth: {:?}, ops: {:?} }}", l.bandwidth(), diff --git a/src/bin/ch-remote.rs b/src/bin/ch-remote.rs index 2c83e7ba0..9620846d7 100644 --- a/src/bin/ch-remote.rs +++ b/src/bin/ch-remote.rs @@ -42,21 +42,21 @@ impl fmt::Display for Error { use Error::*; match self { ApiClient(e) => e.fmt(f), - Connect(e) => write!(f, "Error opening HTTP socket: {}", e), - InvalidCpuCount(e) => write!(f, "Error parsing CPU count: {}", e), - InvalidMemorySize(e) => write!(f, "Error parsing memory size: {:?}", e), - InvalidBalloonSize(e) => write!(f, "Error parsing balloon size: {:?}", e), - AddDeviceConfig(e) => write!(f, "Error parsing device syntax: {}", e), - AddDiskConfig(e) => write!(f, "Error parsing disk syntax: {}", e), - AddFsConfig(e) => write!(f, "Error parsing filesystem syntax: {}", e), - AddPmemConfig(e) => write!(f, "Error parsing persistent memory syntax: {}", e), - AddNetConfig(e) => write!(f, "Error parsing network syntax: {}", e), - AddUserDeviceConfig(e) => write!(f, "Error parsing user device syntax: {}", e), - AddVdpaConfig(e) => write!(f, "Error parsing vDPA device syntax: {}", e), - AddVsockConfig(e) => write!(f, "Error parsing vsock syntax: {}", e), - Restore(e) => write!(f, "Error parsing restore syntax: {}", e), - ReadingStdin(e) => write!(f, "Error reading from stdin: {}", e), - ReadingFile(e) => write!(f, "Error reading from file: {}", e), + Connect(e) => write!(f, "Error opening HTTP socket: {e}"), + InvalidCpuCount(e) => write!(f, "Error parsing CPU count: {e}"), + InvalidMemorySize(e) => write!(f, "Error parsing memory size: {e:?}"), + InvalidBalloonSize(e) => write!(f, "Error parsing balloon size: {e:?}"), + AddDeviceConfig(e) => write!(f, "Error parsing device syntax: {e}"), + AddDiskConfig(e) => write!(f, "Error parsing disk syntax: {e}"), + AddFsConfig(e) => write!(f, "Error parsing filesystem syntax: {e}"), + AddPmemConfig(e) => write!(f, "Error parsing persistent memory syntax: {e}"), + AddNetConfig(e) => write!(f, "Error parsing network syntax: {e}"), + AddUserDeviceConfig(e) => write!(f, "Error parsing user device syntax: {e}"), + AddVdpaConfig(e) => write!(f, "Error parsing vDPA device syntax: {e}"), + AddVsockConfig(e) => write!(f, "Error parsing vsock syntax: {e}"), + Restore(e) => write!(f, "Error parsing restore syntax: {e}"), + ReadingStdin(e) => write!(f, "Error reading from stdin: {e}"), + ReadingFile(e) => write!(f, "Error reading from file: {e}"), } } } @@ -688,7 +688,7 @@ fn main() { let matches = app.get_matches(); if let Err(e) = do_command(&matches) { - eprintln!("Error running command: {}", e); + eprintln!("Error running command: {e}"); process::exit(1) }; } diff --git a/src/main.rs b/src/main.rs index 4055addaf..e30540cdf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -479,7 +479,7 @@ fn start_vmm(cmd_arguments: ArgMatches) -> Result, Error> { "log" => SeccompAction::Log, _ => { // The user providing an invalid value will be rejected by clap - panic!("Invalid parameter {} for \"--seccomp\" flag", seccomp_value); + panic!("Invalid parameter {seccomp_value} for \"--seccomp\" flag"); } } } else { @@ -499,7 +499,7 @@ fn start_vmm(cmd_arguments: ArgMatches) -> Result, Error> { signal_hook::low_level::emulate_default_handler(SIGSYS).unwrap(); }) } - .map_err(|e| eprintln!("Error adding SIGSYS signal handler: {}", e)) + .map_err(|e| eprintln!("Error adding SIGSYS signal handler: {e}")) .ok(); } @@ -508,13 +508,13 @@ fn start_vmm(cmd_arguments: ArgMatches) -> Result, Error> { // dedicated signal handling thread we'll start in a bit. for sig in &vmm::vm::Vm::HANDLED_SIGNALS { if let Err(e) = block_signal(*sig) { - eprintln!("Error blocking signals: {}", e); + eprintln!("Error blocking signals: {e}"); } } for sig in &vmm::Vmm::HANDLED_SIGNALS { if let Err(e) = block_signal(*sig) { - eprintln!("Error blocking signals: {}", e); + eprintln!("Error blocking signals: {e}"); } } @@ -605,7 +605,7 @@ fn main() { 0 } Err(e) => { - eprintln!("{}", e); + eprintln!("{e}"); 1 } }; diff --git a/test_infra/src/lib.rs b/test_infra/src/lib.rs index 4e896a508..34093028a 100644 --- a/test_infra/src/lib.rs +++ b/test_infra/src/lib.rs @@ -148,13 +148,12 @@ impl GuestNetworkConfig { let duration = start.elapsed(); eprintln!( "\n\n==== Start 'wait_vm_boot' (FAILED) ====\n\n\ - duration =\"{:?}, timeout = {}s\"\n\ - listen_addr=\"{}\"\n\ - expected_guest_addr=\"{}\"\n\ - message=\"{}\"\n\ - error=\"{:?}\"\n\ - \n==== End 'wait_vm_boot' outout ====\n\n", - duration, timeout, listen_addr, expected_guest_addr, s, e + duration =\"{duration:?}, timeout = {timeout}s\"\n\ + listen_addr=\"{listen_addr}\"\n\ + expected_guest_addr=\"{expected_guest_addr}\"\n\ + message=\"{s}\"\n\ + error=\"{e:?}\"\n\ + \n==== End 'wait_vm_boot' outout ====\n\n" ); Err(e) @@ -435,7 +434,7 @@ impl DiskConfig for WindowsDiskConfig { .output() .expect("Expect device mapper nodes to be ready"); - self.osdisk_path = format!("/dev/mapper/{}", windows_snapshot); + self.osdisk_path = format!("/dev/mapper/{windows_snapshot}"); self.windows_snapshot_cow = windows_snapshot_cow; self.windows_snapshot = windows_snapshot; } @@ -463,10 +462,7 @@ pub fn rate_limited_copy, Q: AsRef>(from: P, to: Q) -> io:: // Make sure there is at least 6 GiB of space if free_bytes < 6 << 30 { - eprintln!( - "Not enough space on disk ({}). Attempt {} of 10. Sleeping.", - free_bytes, i - ); + eprintln!("Not enough space on disk ({free_bytes}). Attempt {i} of 10. Sleeping."); thread::sleep(std::time::Duration::new(60, 0)); continue; } @@ -475,7 +471,7 @@ pub fn rate_limited_copy, Q: AsRef>(from: P, to: Q) -> io:: Err(e) => { if let Some(errno) = e.raw_os_error() { if errno == libc::ENOSPC { - eprintln!("Copy returned ENOSPC. Attempt {} of 10. Sleeping.", i); + eprintln!("Copy returned ENOSPC. Attempt {i} of 10. Sleeping."); thread::sleep(std::time::Duration::new(60, 0)); continue; } @@ -510,7 +506,7 @@ pub fn handle_child_output( ); } Some(code) => { - eprintln!("\n\n==== child exit code: {} ====", code); + eprintln!("\n\n==== child exit code: {code} ===="); } } @@ -564,7 +560,7 @@ fn scp_to_guest_with_auth( loop { match (|| -> Result<(), SshCommandError> { let tcp = - TcpStream::connect(format!("{}:22", ip)).map_err(SshCommandError::Connection)?; + TcpStream::connect(format!("{ip}:22")).map_err(SshCommandError::Connection)?; let mut sess = Session::new().unwrap(); sess.set_tcp_stream(tcp); sess.handshake().map_err(SshCommandError::Handshake)?; @@ -602,13 +598,12 @@ fn scp_to_guest_with_auth( if counter >= retries { eprintln!( "\n\n==== Start scp command output (FAILED) ====\n\n\ - path =\"{:?}\"\n\ - remote_path =\"{:?}\"\n\ - auth=\"{:#?}\"\n\ - ip=\"{}\"\n\ - error=\"{:?}\"\n\ - \n==== End scp command outout ====\n\n", - path, remote_path, auth, ip, e + path =\"{path:?}\"\n\ + remote_path =\"{remote_path:?}\"\n\ + auth=\"{auth:#?}\"\n\ + ip=\"{ip}\"\n\ + error=\"{e:?}\"\n\ + \n==== End scp command outout ====\n\n" ); return Err(e); @@ -653,7 +648,7 @@ pub fn ssh_command_ip_with_auth( loop { match (|| -> Result<(), SshCommandError> { let tcp = - TcpStream::connect(format!("{}:22", ip)).map_err(SshCommandError::Connection)?; + TcpStream::connect(format!("{ip}:22")).map_err(SshCommandError::Connection)?; let mut sess = Session::new().unwrap(); sess.set_tcp_stream(tcp); sess.handshake().map_err(SshCommandError::Handshake)?; @@ -687,13 +682,12 @@ pub fn ssh_command_ip_with_auth( if counter >= retries { eprintln!( "\n\n==== Start ssh command output (FAILED) ====\n\n\ - command=\"{}\"\n\ - auth=\"{:#?}\"\n\ - ip=\"{}\"\n\ - output=\"{}\"\n\ - error=\"{:?}\"\n\ - \n==== End ssh command outout ====\n\n", - command, auth, ip, s, e + command=\"{command}\"\n\ + auth=\"{auth:#?}\"\n\ + ip=\"{ip}\"\n\ + output=\"{s}\"\n\ + error=\"{e:?}\"\n\ + \n==== End ssh command outout ====\n\n" ); return Err(e); @@ -727,14 +721,14 @@ pub fn exec_host_command_status(command: &str) -> ExitStatus { std::process::Command::new("bash") .args(["-c", command]) .status() - .unwrap_or_else(|_| panic!("Expected '{}' to run", command)) + .unwrap_or_else(|_| panic!("Expected '{command}' to run")) } pub fn exec_host_command_output(command: &str) -> Output { std::process::Command::new("bash") .args(["-c", command]) .output() - .unwrap_or_else(|_| panic!("Expected '{}' to run", command)) + .unwrap_or_else(|_| panic!("Expected '{command}' to run")) } pub const PIPE_SIZE: i32 = 32 << 20; @@ -755,15 +749,15 @@ impl Guest { let tmp_dir = TempDir::new_with_prefix("/tmp/ch").unwrap(); let network = GuestNetworkConfig { - guest_ip: format!("{}.{}.2", class, id), - l2_guest_ip1: format!("{}.{}.3", class, id), - l2_guest_ip2: format!("{}.{}.4", class, id), - l2_guest_ip3: format!("{}.{}.5", class, id), - host_ip: format!("{}.{}.1", class, id), - guest_mac: format!("12:34:56:78:90:{:02x}", id), - l2_guest_mac1: format!("de:ad:be:ef:12:{:02x}", id), - l2_guest_mac2: format!("de:ad:be:ef:34:{:02x}", id), - l2_guest_mac3: format!("de:ad:be:ef:56:{:02x}", id), + guest_ip: format!("{class}.{id}.2"), + l2_guest_ip1: format!("{class}.{id}.3"), + l2_guest_ip2: format!("{class}.{id}.4"), + l2_guest_ip3: format!("{class}.{id}.5"), + host_ip: format!("{class}.{id}.1"), + guest_mac: format!("12:34:56:78:90:{id:02x}"), + l2_guest_mac1: format!("de:ad:be:ef:12:{id:02x}"), + l2_guest_mac2: format!("de:ad:be:ef:34:{id:02x}"), + l2_guest_mac3: format!("de:ad:be:ef:56:{id:02x}"), tcp_listener_port: DEFAULT_TCP_LISTENER_PORT + id as u16, }; @@ -900,9 +894,8 @@ impl Guest { pub fn get_numa_node_memory(&self, node_id: usize) -> Result { self.ssh_command( format!( - "grep MemTotal /sys/devices/system/node/node{}/meminfo \ - | cut -d \":\" -f 2 | grep -o \"[0-9]*\"", - node_id + "grep MemTotal /sys/devices/system/node/node{node_id}/meminfo \ + | cut -d \":\" -f 2 | grep -o \"[0-9]*\"" ) .as_str(), )? @@ -919,10 +912,7 @@ impl Guest { pub fn check_numa_node_cpus(&self, node_id: usize, cpus: Vec) -> Result<(), Error> { for cpu in cpus.iter() { - let cmd = format!( - "[ -d \"/sys/devices/system/node/node{}/cpu{}\" ]", - node_id, cpu - ); + let cmd = format!("[ -d \"/sys/devices/system/node/node{node_id}/cpu{cpu}\" ]"); self.ssh_command(cmd.as_str())?; } @@ -934,7 +924,7 @@ impl Guest { node_id: usize, distances: &str, ) -> Result { - let cmd = format!("cat /sys/devices/system/node/node{}/distance", node_id); + let cmd = format!("cat /sys/devices/system/node/node{node_id}/distance"); if self.ssh_command(cmd.as_str())?.trim() == distances { Ok(true) } else { @@ -1047,8 +1037,7 @@ impl Guest { // Write something to vsock from the host assert!(exec_host_command_status(&format!( - "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{}", - socket + "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{socket}" )) .success()); @@ -1113,7 +1102,7 @@ impl Guest { } // Check if the console is usable if let Some(console_text) = console_text { - let console_cmd = format!("echo {} | sudo tee /dev/hvc0", console_text); + let console_cmd = format!("echo {console_text} | sudo tee /dev/hvc0"); self.ssh_command(&console_cmd).unwrap(); } // The net device is 'automatically' exercised through the above 'ssh' commands @@ -1121,13 +1110,11 @@ impl Guest { // Check if the pmem device is usable if let Some(pmem_path) = pmem_path { assert_eq!( - self.ssh_command(&format!("ls {}", pmem_path)) - .unwrap() - .trim(), + self.ssh_command(&format!("ls {pmem_path}")).unwrap().trim(), pmem_path ); assert_eq!( - self.ssh_command(&format!("sudo mount {} /mnt", pmem_path)) + self.ssh_command(&format!("sudo mount {pmem_path} /mnt")) .unwrap(), "" ); @@ -1138,7 +1125,7 @@ impl Guest { assert_eq!(self.ssh_command("ls /mnt").unwrap(), ""); assert_eq!( - self.ssh_command(&format!("sudo mount {} /mnt", pmem_path)) + self.ssh_command(&format!("sudo mount {pmem_path} /mnt")) .unwrap(), "" ); @@ -1261,8 +1248,7 @@ impl<'a> GuestCommand<'a> { Err(std::io::Error::new( std::io::ErrorKind::Other, format!( - "resizing pipe w/ 'fnctl' failed: stdout pipesize {}, stderr pipesize {}", - pipesize, pipesize1 + "resizing pipe w/ 'fnctl' failed: stdout pipesize {pipesize}, stderr pipesize {pipesize1}" ), )) } @@ -1320,8 +1306,8 @@ impl<'a> GuestCommand<'a> { pub fn clh_command(cmd: &str) -> String { env::var("BUILD_TARGET").map_or( - format!("target/x86_64-unknown-linux-gnu/release/{}", cmd), - |target| format!("target/{}/release/{}", target, cmd), + format!("target/x86_64-unknown-linux-gnu/release/{cmd}"), + |target| format!("target/{target}/release/{cmd}"), ) } @@ -1422,8 +1408,7 @@ pub fn parse_fio_output(output: &str, fio_ops: &FioOps, num_jobs: u32) -> Result }) .map_err(|_| { eprintln!( - "=============== Fio output ===============\n\n{}\n\n===========end============\n\n", - output + "=============== Fio output ===============\n\n{output}\n\n===========end============\n\n" ); Error::FioOutputParse }) @@ -1478,8 +1463,7 @@ pub fn parse_fio_output_iops(output: &str, fio_ops: &FioOps, num_jobs: u32) -> R }) .map_err(|_| { eprintln!( - "=============== Fio output ===============\n\n{}\n\n===========end============\n\n", - output + "=============== Fio output ===============\n\n{output}\n\n===========end============\n\n" ); Error::FioOutputParse }) @@ -1532,7 +1516,7 @@ pub fn measure_virtio_net_throughput( "-p", &format!("{}", default_port + n), "-t", - &format!("{}", test_timeout), + &format!("{test_timeout}"), ]); // For measuring the guest transmit throughput (as a sender), // use reverse mode of the iperf3 client on the host @@ -1626,7 +1610,7 @@ pub fn measure_virtio_net_latency(guest: &Guest, test_timeout: u32) -> Result /dev/null &", ethr_remote_path))?; + guest.ssh_command(&format!("{ethr_remote_path} -s &> /dev/null &"))?; thread::sleep(Duration::new(10, 0)); @@ -1647,7 +1631,7 @@ pub fn measure_virtio_net_latency(guest: &Guest, test_timeout: u32) -> Result) -> bool { let mut cmd = Command::new(clh_command("ch-remote")); - cmd.args([&format!("--api-socket={}", api_socket), command]); + cmd.args([&format!("--api-socket={api_socket}"), command]); if let Some(arg) = arg { cmd.arg(arg); @@ -261,14 +259,14 @@ fn remote_command(api_socket: &str, command: &str, arg: Option<&str>) -> bool { } else { eprintln!("Error running ch-remote command: {:?}", &cmd); let stderr = String::from_utf8_lossy(&output.stderr); - eprintln!("stderr: {}", stderr); + eprintln!("stderr: {stderr}"); false } } fn remote_command_w_output(api_socket: &str, command: &str, arg: Option<&str>) -> (bool, Vec) { let mut cmd = Command::new(clh_command("ch-remote")); - cmd.args([&format!("--api-socket={}", api_socket), command]); + cmd.args([&format!("--api-socket={api_socket}"), command]); if let Some(arg) = arg { cmd.arg(arg); @@ -287,18 +285,18 @@ fn resize_command( event_file: Option<&str>, ) -> bool { let mut cmd = Command::new(clh_command("ch-remote")); - cmd.args([&format!("--api-socket={}", api_socket), "resize"]); + cmd.args([&format!("--api-socket={api_socket}"), "resize"]); if let Some(desired_vcpus) = desired_vcpus { - cmd.arg(format!("--cpus={}", desired_vcpus)); + cmd.arg(format!("--cpus={desired_vcpus}")); } if let Some(desired_ram) = desired_ram { - cmd.arg(format!("--memory={}", desired_ram)); + cmd.arg(format!("--memory={desired_ram}")); } if let Some(desired_balloon) = desired_balloon { - cmd.arg(format!("--balloon={}", desired_balloon)); + cmd.arg(format!("--balloon={desired_balloon}")); } let ret = cmd.status().expect("Failed to launch ch-remote").success(); @@ -323,10 +321,10 @@ fn resize_command( fn resize_zone_command(api_socket: &str, id: &str, desired_size: &str) -> bool { let mut cmd = Command::new(clh_command("ch-remote")); cmd.args([ - &format!("--api-socket={}", api_socket), + &format!("--api-socket={api_socket}"), "resize-zone", - &format!("--id={}", id), - &format!("--size={}", desired_size), + &format!("--id={id}"), + &format!("--size={desired_size}"), ]); cmd.status().expect("Failed to launch ch-remote").success() @@ -394,12 +392,11 @@ fn setup_ovs_dpdk_guests( guest1 .ssh_command(&format!( - "sudo ip addr add 172.100.0.1/24 dev {}", - guest_net_iface + "sudo ip addr add 172.100.0.1/24 dev {guest_net_iface}" )) .unwrap(); guest1 - .ssh_command(&format!("sudo ip link set up dev {}", guest_net_iface)) + .ssh_command(&format!("sudo ip link set up dev {guest_net_iface}")) .unwrap(); let guest_ip = guest1.network.guest_ip.clone(); @@ -440,12 +437,11 @@ fn setup_ovs_dpdk_guests( guest2 .ssh_command(&format!( - "sudo ip addr add 172.100.0.2/24 dev {}", - guest_net_iface + "sudo ip addr add 172.100.0.2/24 dev {guest_net_iface}" )) .unwrap(); guest2 - .ssh_command(&format!("sudo ip link set up dev {}", guest_net_iface)) + .ssh_command(&format!("sudo ip link set up dev {guest_net_iface}")) .unwrap(); // Check the connection works properly between the two VMs @@ -589,8 +585,7 @@ fn test_cpu_topology(threads_per_core: u8, cores_per_package: u8, packages: u8, .args([ "--cpus", &format!( - "boot={},topology={}:{}:1:{}", - total_vcpus, threads_per_core, cores_per_package, packages + "boot={total_vcpus},topology={threads_per_core}:{cores_per_package}:1:{packages}" ), ]) .args(["--memory", "size=512M"]) @@ -804,7 +799,7 @@ fn test_vhost_user_net( vunet_socket_path, num_queues, if let Some(host_mac) = host_mac { - format!(",host_mac={}", host_mac) + format!(",host_mac={host_mac}") } else { "".to_owned() }, @@ -845,12 +840,12 @@ fn test_vhost_user_net( guest.wait_vm_boot(None).unwrap(); if let Some(tap_name) = tap { - let tap_count = exec_host_command_output(&format!("ip link | grep -c {}", tap_name)); + let tap_count = exec_host_command_output(&format!("ip link | grep -c {tap_name}")); assert_eq!(String::from_utf8_lossy(&tap_count.stdout).trim(), "1"); } if let Some(host_mac) = tap { - let mac_count = exec_host_command_output(&format!("ip link | grep -c {}", host_mac)); + let mac_count = exec_host_command_output(&format!("ip link | grep -c {host_mac}")); assert_eq!(String::from_utf8_lossy(&mac_count.stdout).trim(), "1"); } @@ -861,7 +856,7 @@ fn test_vhost_user_net( assert_eq!( guest - .ssh_command(format!("cat /sys/class/net/{}/mtu", iface).as_str()) + .ssh_command(format!("cat /sys/class/net/{iface}/mtu").as_str()) .unwrap() .trim(), "3000" @@ -956,15 +951,14 @@ fn test_vhost_user_blk( ( format!( - "vhost_user=true,socket={},num_queues={},queue_size=128", - vubd_socket_path, num_queues, + "vhost_user=true,socket={vubd_socket_path},num_queues={num_queues},queue_size=128", ), Some(daemon_child), ) }; let mut child = GuestCommand::new(&guest) - .args(["--cpus", format!("boot={}", num_queues).as_str()]) + .args(["--cpus", format!("boot={num_queues}").as_str()]) .args(["--memory", "size=512M,hotplug_size=2048M,shared=on"]) .args(["--kernel", kernel_path.to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -1030,11 +1024,7 @@ fn test_vhost_user_blk( guest.ssh_command("mkdir mount_image").unwrap(); guest .ssh_command( - format!( - "sudo mount -o {} -t ext4 /dev/vdc mount_image/", - mount_ro_rw_flag - ) - .as_str(), + format!("sudo mount -o {mount_ro_rw_flag} -t ext4 /dev/vdc mount_image/").as_str(), ) .unwrap(); @@ -1109,15 +1099,14 @@ fn test_boot_from_vhost_user_blk( ( format!( - "vhost_user=true,socket={},num_queues={},queue_size=128", - vubd_socket_path, num_queues, + "vhost_user=true,socket={vubd_socket_path},num_queues={num_queues},queue_size=128", ), Some(daemon_child), ) }; let mut child = GuestCommand::new(&guest) - .args(["--cpus", format!("boot={}", num_queues).as_str()]) + .args(["--cpus", format!("boot={num_queues}").as_str()]) .args(["--memory", "size=512M,shared=on"]) .args(["--kernel", kernel_path.to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -1206,7 +1195,7 @@ fn _test_virtio_fs( "id=myfs0,tag=myfs,socket={},num_queues=1,queue_size=1024{}", virtiofsd_socket_path, if let Some(pci_segment) = pci_segment { - format!(",pci_segment={}", pci_segment) + format!(",pci_segment={pci_segment}") } else { "".to_owned() } @@ -1229,8 +1218,7 @@ fn _test_virtio_fs( if let Some(pci_segment) = pci_segment { assert!(String::from_utf8_lossy(&cmd_output).contains(&format!( - "{{\"id\":\"myfs0\",\"bdf\":\"{:04x}:00:01.0\"}}", - pci_segment + "{{\"id\":\"myfs0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { assert!(String::from_utf8_lossy(&cmd_output) @@ -1299,7 +1287,7 @@ fn _test_virtio_fs( "id=myfs0,tag=myfs,socket={},num_queues=1,queue_size=1024{}", virtiofsd_socket_path, if let Some(pci_segment) = pci_segment { - format!(",pci_segment={}", pci_segment) + format!(",pci_segment={pci_segment}") } else { "".to_owned() } @@ -1311,8 +1299,7 @@ fn _test_virtio_fs( assert!(cmd_success); if let Some(pci_segment) = pci_segment { assert!(String::from_utf8_lossy(&cmd_output).contains(&format!( - "{{\"id\":\"myfs0\",\"bdf\":\"{:04x}:00:01.0\"}}", - pci_segment + "{{\"id\":\"myfs0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { assert!(String::from_utf8_lossy(&cmd_output) @@ -1426,7 +1413,7 @@ fn test_virtio_pmem(discard_writes: bool, specify_size: bool) { } fn get_fd_count(pid: u32) -> usize { - fs::read_dir(format!("/proc/{}/fd", pid)).unwrap().count() + fs::read_dir(format!("/proc/{pid}/fd")).unwrap().count() } fn _test_virtio_vsock(hotplug: bool) { @@ -1455,7 +1442,7 @@ fn _test_virtio_vsock(hotplug: bool) { cmd.default_net(); if !hotplug { - cmd.args(["--vsock", format!("cid=3,socket={}", socket).as_str()]); + cmd.args(["--vsock", format!("cid=3,socket={socket}").as_str()]); } let mut child = cmd.capture_output().spawn().unwrap(); @@ -1467,7 +1454,7 @@ fn _test_virtio_vsock(hotplug: bool) { let (cmd_success, cmd_output) = remote_command_w_output( &api_socket, "add-vsock", - Some(format!("cid=3,socket={},id=test0", socket).as_str()), + Some(format!("cid=3,socket={socket},id=test0").as_str()), ); assert!(cmd_success); assert!(String::from_utf8_lossy(&cmd_output) @@ -1521,7 +1508,7 @@ fn test_memory_mergeable(mergeable: bool) { let guest1 = Guest::new(Box::new(focal1)); let mut child1 = GuestCommand::new(&guest1) .args(["--cpus", "boot=1"]) - .args(["--memory", format!("size=512M,{}", memory_param).as_str()]) + .args(["--memory", format!("size=512M,{memory_param}").as_str()]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .default_disks() @@ -1547,7 +1534,7 @@ fn test_memory_mergeable(mergeable: bool) { let guest2 = Guest::new(Box::new(focal2)); let mut child2 = GuestCommand::new(&guest2) .args(["--cpus", "boot=1"]) - .args(["--memory", format!("size=512M,{}", memory_param).as_str()]) + .args(["--memory", format!("size=512M,{memory_param}").as_str()]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .default_disks() @@ -1563,8 +1550,7 @@ fn test_memory_mergeable(mergeable: bool) { if mergeable { println!( - "ksm pages_shared after vm1 booted '{}', ksm pages_shared after vm2 booted '{}'", - ksm_ps_guest1, ksm_ps_guest2 + "ksm pages_shared after vm1 booted '{ksm_ps_guest1}', ksm pages_shared after vm2 booted '{ksm_ps_guest2}'" ); // We are expecting the number of shared pages to increase as the number of VM increases assert!(ksm_ps_guest1 < ksm_ps_guest2); @@ -1584,7 +1570,7 @@ fn test_memory_mergeable(mergeable: bool) { } fn _get_vmm_overhead(pid: u32, guest_memory_size: u32) -> HashMap { - let smaps = fs::File::open(format!("/proc/{}/smaps", pid)).unwrap(); + let smaps = fs::File::open(format!("/proc/{pid}/smaps")).unwrap(); let reader = io::BufReader::new(smaps); let mut skip_map: bool = false; @@ -1629,7 +1615,7 @@ fn get_vmm_overhead(pid: u32, guest_memory_size: u32) -> u32 { let mut total = 0; for (region_name, value) in &_get_vmm_overhead(pid, guest_memory_size) { - eprintln!("{}: {}", region_name, value); + eprintln!("{region_name}: {value}"); total += value; } @@ -1637,7 +1623,7 @@ fn get_vmm_overhead(pid: u32, guest_memory_size: u32) -> u32 { } fn process_rss_kib(pid: u32) -> usize { - let command = format!("ps -q {} -o rss=", pid); + let command = format!("ps -q {pid} -o rss="); let rss = exec_host_command_output(&command); String::from_utf8_lossy(&rss.stdout).trim().parse().unwrap() } @@ -1842,9 +1828,7 @@ fn _test_virtio_iommu(acpi: bool) { let iommu_group = !acpi as i32; assert_eq!( guest - .ssh_command( - format!("ls /sys/kernel/iommu_groups/{}/devices", iommu_group).as_str() - ) + .ssh_command(format!("ls /sys/kernel/iommu_groups/{iommu_group}/devices").as_str()) .unwrap() .trim(), "0000:00:02.0" @@ -1854,9 +1838,7 @@ fn _test_virtio_iommu(acpi: bool) { let iommu_group = if acpi { 1 } else { 2 }; assert_eq!( guest - .ssh_command( - format!("ls /sys/kernel/iommu_groups/{}/devices", iommu_group).as_str() - ) + .ssh_command(format!("ls /sys/kernel/iommu_groups/{iommu_group}/devices").as_str()) .unwrap() .trim(), "0000:00:03.0" @@ -1866,9 +1848,7 @@ fn _test_virtio_iommu(acpi: bool) { let iommu_group = if acpi { 2 } else { 3 }; assert_eq!( guest - .ssh_command( - format!("ls /sys/kernel/iommu_groups/{}/devices", iommu_group).as_str() - ) + .ssh_command(format!("ls /sys/kernel/iommu_groups/{iommu_group}/devices").as_str()) .unwrap() .trim(), "0000:00:04.0" @@ -1899,8 +1879,7 @@ fn enable_guest_watchdog(guest: &Guest, watchdog_sec: u32) { // Enable systemd watchdog guest .ssh_command(&format!( - "echo RuntimeWatchdogSec={}s | sudo tee -a /etc/systemd/system.conf", - watchdog_sec + "echo RuntimeWatchdogSec={watchdog_sec}s | sudo tee -a /etc/systemd/system.conf" )) .unwrap(); } @@ -1947,7 +1926,7 @@ mod common_parallel { .default_disks() .default_net() .args(["--serial", "tty", "--console", "off"]) - .args(["--event-monitor", format!("path={}", event_path).as_str()]) + .args(["--event-monitor", format!("path={event_path}").as_str()]) .capture_output() .spawn() .unwrap(); @@ -2085,7 +2064,7 @@ mod common_parallel { let guest = Guest::new(Box::new(focal)); let max_phys_bits: u8 = 36; let mut child = GuestCommand::new(&guest) - .args(["--cpus", &format!("max_phys_bits={}", max_phys_bits)]) + .args(["--cpus", &format!("max_phys_bits={max_phys_bits}")]) .args(["--memory", "size=512M"]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -2144,9 +2123,9 @@ mod common_parallel { let r = std::panic::catch_unwind(|| { guest.wait_vm_boot(None).unwrap(); let pid = child.id(); - let taskset_vcpu0 = exec_host_command_output(format!("taskset -pc $(ps -T -p {} | grep vcpu0 | xargs | cut -f 2 -d \" \") | cut -f 6 -d \" \"", pid).as_str()); + let taskset_vcpu0 = exec_host_command_output(format!("taskset -pc $(ps -T -p {pid} | grep vcpu0 | xargs | cut -f 2 -d \" \") | cut -f 6 -d \" \"").as_str()); assert_eq!(String::from_utf8_lossy(&taskset_vcpu0.stdout).trim(), "0,2"); - let taskset_vcpu1 = exec_host_command_output(format!("taskset -pc $(ps -T -p {} | grep vcpu1 | xargs | cut -f 2 -d \" \") | cut -f 6 -d \" \"", pid).as_str()); + let taskset_vcpu1 = exec_host_command_output(format!("taskset -pc $(ps -T -p {pid} | grep vcpu1 | xargs | cut -f 2 -d \" \") | cut -f 6 -d \" \"").as_str()); assert_eq!(String::from_utf8_lossy(&taskset_vcpu1.stdout).trim(), "1,3"); }); @@ -2319,12 +2298,9 @@ mod common_parallel { .unwrap(), ); assert!( - exec_host_command_status(format!("truncate {} -s 4M", test_disk_path).as_str()) - .success() - ); - assert!( - exec_host_command_status(format!("mkfs.ext4 {}", test_disk_path).as_str()).success() + exec_host_command_status(format!("truncate {test_disk_path} -s 4M").as_str()).success() ); + assert!(exec_host_command_status(format!("mkfs.ext4 {test_disk_path}").as_str()).success()); let api_socket = temp_api_path(&guest.tmp_dir); let mut cmd = GuestCommand::new(&guest); @@ -2444,7 +2420,7 @@ mod common_parallel { assert_eq!( guest .ssh_command( - format!("sudo ethtool -K {} rx-gro-hw off && echo success", iface).as_str() + format!("sudo ethtool -K {iface} rx-gro-hw off && echo success").as_str() ) .unwrap() .trim(), @@ -2452,7 +2428,7 @@ mod common_parallel { ); assert_eq!( guest - .ssh_command(format!("cat /sys/class/net/{}/mtu", iface).as_str()) + .ssh_command(format!("cat /sys/class/net/{iface}/mtu").as_str()) .unwrap() .trim(), "3000" @@ -2481,12 +2457,9 @@ mod common_parallel { .unwrap(), ); assert!( - exec_host_command_status(format!("truncate {} -s 4M", test_disk_path).as_str()) - .success() - ); - assert!( - exec_host_command_status(format!("mkfs.ext4 {}", test_disk_path).as_str()).success() + exec_host_command_status(format!("truncate {test_disk_path} -s 4M").as_str()).success() ); + assert!(exec_host_command_status(format!("mkfs.ext4 {test_disk_path}").as_str()).success()); let mut cmd = GuestCommand::new(&guest); cmd.args(["--cpus", "boot=1"]) @@ -2506,7 +2479,7 @@ mod common_parallel { guest.disk_config.disk(DiskType::CloudInit).unwrap() ) .as_str(), - format!("path={},pci_segment=15", test_disk_path).as_str(), + format!("path={test_disk_path},pci_segment=15").as_str(), ]) .capture_output() .default_net(); @@ -2811,7 +2784,7 @@ mod common_parallel { guest.disk_config.disk(DiskType::CloudInit).unwrap() ) .as_str(), - format!("path={}", vhdx_path).as_str(), + format!("path={vhdx_path}").as_str(), ]) .default_net() .capture_output() @@ -3101,7 +3074,7 @@ mod common_parallel { let s1 = "io.systemd.credential:xx=yy"; let s2 = "This is a test string"; - let oem_strings = format!("oem_strings=[{},{}]", s1, s2); + let oem_strings = format!("oem_strings=[{s1},{s2}]"); let mut child = GuestCommand::new(&guest) .args(["--cpus", "boot=1"]) @@ -3650,7 +3623,7 @@ mod common_parallel { .unwrap(); let text = String::from("On a branch floating down river a cricket, singing."); - let cmd = format!("echo {} | sudo tee /dev/hvc0", text); + let cmd = format!("echo {text} | sudo tee /dev/hvc0"); let r = std::panic::catch_unwind(|| { guest.wait_vm_boot(None).unwrap(); @@ -3714,8 +3687,7 @@ mod common_parallel { if !buf.contains(CONSOLE_TEST_STRING) { eprintln!( - "\n\n==== Console file output ====\n\n{}\n\n==== End console file output ====", - buf + "\n\n==== Console file output ====\n\n{buf}\n\n==== End console file output ====" ); } assert!(buf.contains(CONSOLE_TEST_STRING)); @@ -3809,8 +3781,7 @@ mod common_parallel { .args([ "--cmdline", format!( - "{} kvm-intel.nested=1 vfio_iommu_type1.allow_unsafe_interrupts", - DIRECT_KERNEL_BOOT_CMDLINE + "{DIRECT_KERNEL_BOOT_CMDLINE} kvm-intel.nested=1 vfio_iommu_type1.allow_unsafe_interrupts" ) .as_str(), ]) @@ -4003,7 +3974,7 @@ mod common_parallel { .args(["--kernel", kernel_path.to_str().unwrap()]) .args([ "--cmdline", - format!("{} acpi=off", DIRECT_KERNEL_BOOT_CMDLINE).as_str(), + format!("{DIRECT_KERNEL_BOOT_CMDLINE} acpi=off").as_str(), ]) .default_disks() .default_net() @@ -4760,10 +4731,7 @@ mod common_parallel { let mut child = GuestCommand::new(&guest) .args(["--cpus", "boot=1"]) - .args([ - "--memory", - format!("size={}K", guest_memory_size_kb).as_str(), - ]) + .args(["--memory", format!("size={guest_memory_size_kb}K").as_str()]) .args(["--kernel", kernel_path.to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .default_disks() @@ -4775,10 +4743,7 @@ mod common_parallel { let r = std::panic::catch_unwind(|| { let overhead = get_vmm_overhead(child.id(), guest_memory_size_kb); - eprintln!( - "Guest memory overhead: {} vs {}", - overhead, MAXIMUM_VMM_OVERHEAD_KB - ); + eprintln!("Guest memory overhead: {overhead} vs {MAXIMUM_VMM_OVERHEAD_KB}"); assert!(overhead <= MAXIMUM_VMM_OVERHEAD_KB); }); @@ -5018,7 +4983,7 @@ mod common_parallel { } // Create loop device path - let loop_device_path = format!("{}{}", LOOP_DEVICE_PREFIX, loop_device_number); + let loop_device_path = format!("{LOOP_DEVICE_PREFIX}{loop_device_number}"); // Open loop device let loop_device_file = OpenOptions::new() @@ -5093,10 +5058,7 @@ mod common_parallel { if !output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); - panic!( - "qemu-img command failed\nstdout\n{}\nstderr\n{}", - stdout, stderr - ); + panic!("qemu-img command failed\nstdout\n{stdout}\nstderr\n{stderr}"); } let loop_dev = create_loop_device(test_disk_path.to_str().unwrap(), 4096, 5); @@ -5203,7 +5165,7 @@ mod common_parallel { thread::sleep(std::time::Duration::new(20, 0)); let orig_balloon = balloon_size(&api_socket); - println!("The original balloon memory size is {} bytes", orig_balloon); + println!("The original balloon memory size is {orig_balloon} bytes"); assert!(orig_balloon == 2147483648); // Two steps to verify if the 'deflate_on_oom' parameter works. @@ -5218,10 +5180,7 @@ mod common_parallel { // 2nd: check balloon_mem's value to verify balloon has been automatically deflated let deflated_balloon = balloon_size(&api_socket); - println!( - "After deflating, balloon memory size is {} bytes", - deflated_balloon - ); + println!("After deflating, balloon memory size is {deflated_balloon} bytes"); // Verify the balloon size deflated assert!(deflated_balloon < 2147483648); }); @@ -5256,7 +5215,7 @@ mod common_parallel { // Check the initial RSS is less than 1GiB let rss = process_rss_kib(pid); - println!("RSS {} < 1048576", rss); + println!("RSS {rss} < 1048576"); assert!(rss < 1048576); // Spawn a command inside the guest to consume 2GiB of RAM for 60 @@ -5276,7 +5235,7 @@ mod common_parallel { // the expected amount of memory. thread::sleep(std::time::Duration::new(50, 0)); let rss = process_rss_kib(pid); - println!("RSS {} >= 2097152", rss); + println!("RSS {rss} >= 2097152"); assert!(rss >= 2097152); // Wait for an extra minute to make sure the stress command has @@ -5285,7 +5244,7 @@ mod common_parallel { // 2GiB. thread::sleep(std::time::Duration::new(60, 0)); let rss = process_rss_kib(pid); - println!("RSS {} < 2097152", rss); + println!("RSS {rss} < 2097152"); assert!(rss < 2097152); }); @@ -5360,7 +5319,7 @@ mod common_parallel { "file={},id=test0{}", pmem_temp_file.as_path().to_str().unwrap(), if let Some(pci_segment) = pci_segment { - format!(",pci_segment={}", pci_segment) + format!(",pci_segment={pci_segment}") } else { "".to_owned() } @@ -5369,8 +5328,7 @@ mod common_parallel { assert!(cmd_success); if let Some(pci_segment) = pci_segment { assert!(String::from_utf8_lossy(&cmd_output).contains(&format!( - "{{\"id\":\"test0\",\"bdf\":\"{:04x}:00:01.0\"}}", - pci_segment + "{{\"id\":\"test0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { assert!(String::from_utf8_lossy(&cmd_output) @@ -5486,7 +5444,7 @@ mod common_parallel { "{}{},id=test0", guest.default_net_string(), if let Some(pci_segment) = pci_segment { - format!(",pci_segment={}", pci_segment) + format!(",pci_segment={pci_segment}") } else { "".to_owned() } @@ -5498,8 +5456,7 @@ mod common_parallel { if let Some(pci_segment) = pci_segment { assert!(String::from_utf8_lossy(&cmd_output).contains(&format!( - "{{\"id\":\"test0\",\"bdf\":\"{:04x}:00:01.0\"}}", - pci_segment + "{{\"id\":\"test0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { assert!(String::from_utf8_lossy(&cmd_output) @@ -5531,7 +5488,7 @@ mod common_parallel { "{}{},id=test1", guest.default_net_string(), if let Some(pci_segment) = pci_segment { - format!(",pci_segment={}", pci_segment) + format!(",pci_segment={pci_segment}") } else { "".to_owned() } @@ -5543,8 +5500,7 @@ mod common_parallel { if let Some(pci_segment) = pci_segment { assert!(String::from_utf8_lossy(&cmd_output).contains(&format!( - "{{\"id\":\"test1\",\"bdf\":\"{:04x}:00:01.0\"}}", - pci_segment + "{{\"id\":\"test1\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { assert!(String::from_utf8_lossy(&cmd_output) @@ -5608,7 +5564,7 @@ mod common_parallel { initramfs_path.push("alpine_initramfs.img"); let test_string = String::from("axz34i9rylotd8n50wbv6kcj7f2qushme1pg"); - let cmdline = format!("console=hvc0 quiet TEST_STRING={}", test_string); + let cmdline = format!("console=hvc0 quiet TEST_STRING={test_string}"); kernels.iter().for_each(|k_path| { let mut child = GuestCommand::new(&guest) @@ -5676,7 +5632,7 @@ mod common_parallel { let mut child = GuestCommand::new(&guest) .args(["--api-socket", &api_socket_source]) - .args(["--event-monitor", format!("path={}", event_path).as_str()]) + .args(["--event-monitor", format!("path={event_path}").as_str()]) .args(["--cpus", "boot=4"]) .args(["--memory", mem_params]) .args(["--balloon", "size=0"]) @@ -5691,7 +5647,7 @@ mod common_parallel { cloudinit_params.as_str(), ]) .args(["--net", net_params.as_str()]) - .args(["--vsock", format!("cid=3,socket={}", socket).as_str()]) + .args(["--vsock", format!("cid=3,socket={socket}").as_str()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .capture_output() .spawn() @@ -5783,7 +5739,7 @@ mod common_parallel { assert!(remote_command( &api_socket_source, "snapshot", - Some(format!("file://{}", snapshot_dir).as_str()), + Some(format!("file://{snapshot_dir}").as_str()), )); // Wait to make sure the snapshot is completed @@ -5828,11 +5784,11 @@ mod common_parallel { .args(["--api-socket", &api_socket_restored]) .args([ "--event-monitor", - format!("path={}", event_path_restored).as_str(), + format!("path={event_path_restored}").as_str(), ]) .args([ "--restore", - format!("source_url=file://{}", snapshot_dir).as_str(), + format!("source_url=file://{snapshot_dir}").as_str(), ]) .capture_output() .spawn() @@ -5988,19 +5944,17 @@ mod common_parallel { assert!(remote_command( &api_socket, "coredump", - Some(format!("file://{}", vmcore_file).as_str()), + Some(format!("file://{vmcore_file}").as_str()), )); // the num of CORE notes should equals to vcpu - let readelf_core_num_cmd = format!( - "readelf --all {} |grep CORE |grep -v Type |wc -l", - vmcore_file - ); + let readelf_core_num_cmd = + format!("readelf --all {vmcore_file} |grep CORE |grep -v Type |wc -l"); let core_num_in_elf = exec_host_command_output(&readelf_core_num_cmd); assert_eq!(String::from_utf8_lossy(&core_num_in_elf.stdout).trim(), "4"); // the num of QEMU notes should equals to vcpu - let readelf_vmm_num_cmd = format!("readelf --all {} |grep QEMU |wc -l", vmcore_file); + let readelf_vmm_num_cmd = format!("readelf --all {vmcore_file} |grep QEMU |wc -l"); let vmm_num_in_elf = exec_host_command_output(&readelf_vmm_num_cmd); assert_eq!(String::from_utf8_lossy(&vmm_num_in_elf.stdout).trim(), "4"); }); @@ -6108,7 +6062,7 @@ mod common_parallel { .unwrap(); let mut child = GuestCommand::new(&guest) - .args(["--cpus", &format!("boot={}", num_queue_pairs)]) + .args(["--cpus", &format!("boot={num_queue_pairs}")]) .args(["--memory", "size=512M"]) .args(["--kernel", kernel_path.to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -6182,8 +6136,7 @@ mod common_parallel { // Create a macvtap interface for the guest VM to use assert!(exec_host_command_status(&format!( - "sudo ip link add link {} name {} type macvtap mod bridge", - phy_net, guest_macvtap_name + "sudo ip link add link {phy_net} name {guest_macvtap_name} type macvtap mod bridge" )) .success()); assert!(exec_host_command_status(&format!( @@ -6192,17 +6145,14 @@ mod common_parallel { )) .success()); assert!( - exec_host_command_status(&format!("sudo ip link show {}", guest_macvtap_name)) - .success() + exec_host_command_status(&format!("sudo ip link show {guest_macvtap_name}")).success() ); let tap_index = - fs::read_to_string(format!("/sys/class/net/{}/ifindex", guest_macvtap_name)).unwrap(); + fs::read_to_string(format!("/sys/class/net/{guest_macvtap_name}/ifindex")).unwrap(); let tap_device = format!("/dev/tap{}", tap_index.trim()); - assert!( - exec_host_command_status(&format!("sudo chown $UID.$UID {}", tap_device)).success() - ); + assert!(exec_host_command_status(&format!("sudo chown $UID.$UID {tap_device}")).success()); let cstr_tap_device = std::ffi::CString::new(tap_device).unwrap(); let tap_fd1 = unsafe { libc::open(cstr_tap_device.as_ptr(), libc::O_RDWR) }; @@ -6213,8 +6163,7 @@ mod common_parallel { // Create a macvtap on the same physical net interface for // the host machine to use assert!(exec_host_command_status(&format!( - "sudo ip link add link {} name {} type macvtap mod bridge", - phy_net, host_macvtap_name + "sudo ip link add link {phy_net} name {host_macvtap_name} type macvtap mod bridge" )) .success()); // Use default mask "255.255.255.0" @@ -6223,11 +6172,10 @@ mod common_parallel { guest.network.host_ip, host_macvtap_name )) .success()); - assert!(exec_host_command_status(&format!( - "sudo ip link set dev {} up", - host_macvtap_name - )) - .success()); + assert!( + exec_host_command_status(&format!("sudo ip link set dev {host_macvtap_name} up")) + .success() + ); let mut guest_command = GuestCommand::new(&guest); guest_command @@ -6285,8 +6233,8 @@ mod common_parallel { let _ = child.kill(); - exec_host_command_status(&format!("sudo ip link del {}", guest_macvtap_name)); - exec_host_command_status(&format!("sudo ip link del {}", host_macvtap_name)); + exec_host_command_status(&format!("sudo ip link del {guest_macvtap_name}")); + exec_host_command_status(&format!("sudo ip link del {host_macvtap_name}")); let output = child.wait_with_output().unwrap(); @@ -6354,7 +6302,7 @@ mod common_parallel { assert!(remote_command( &api_socket_source, "snapshot", - Some(format!("file://{}", snapshot_dir).as_str()), + Some(format!("file://{snapshot_dir}").as_str()), )); // Wait to make sure the snapshot is completed @@ -6379,7 +6327,7 @@ mod common_parallel { .args(["--api-socket", &api_socket_restored]) .args([ "--restore", - format!("source_url=file://{}", snapshot_dir).as_str(), + format!("source_url=file://{snapshot_dir}").as_str(), ]) .capture_output() .spawn() @@ -6886,7 +6834,7 @@ mod windows { let id = *guard; *guard = id + 1; - let img = PathBuf::from(format!("/tmp/test-hotplug-{}.raw", id)); + let img = PathBuf::from(format!("/tmp/test-hotplug-{id}.raw")); let _ = fs::remove_file(&img); // Create an image file @@ -6896,12 +6844,12 @@ mod windows { "-f", "raw", img.to_str().unwrap(), - format!("{}m", sz).as_str(), + format!("{sz}m").as_str(), ]) .output() .expect("qemu-img command failed") .stdout; - println!("{:?}", out); + println!("{out:?}"); // Associate image to a loop device let out = Command::new("losetup") @@ -6911,7 +6859,7 @@ mod windows { .stdout; let _tmp = String::from_utf8_lossy(&out); let loop_dev = _tmp.trim(); - println!("{:?}", out); + println!("{out:?}"); // Create a partition table // echo 'type=7' | sudo sfdisk "${LOOP}" @@ -6925,7 +6873,7 @@ mod windows { .write_all("type=7".as_bytes()) .expect("failed to write stdin"); let out = child.wait_with_output().expect("sfdisk failed").stdout; - println!("{:?}", out); + println!("{out:?}"); // Disengage the loop device let out = Command::new("losetup") @@ -6933,7 +6881,7 @@ mod windows { .output() .expect("loop device not found") .stdout; - println!("{:?}", out); + println!("{out:?}"); // Re-associate loop device pointing to the partition only let out = Command::new("losetup") @@ -6949,28 +6897,28 @@ mod windows { .stdout; let _tmp = String::from_utf8_lossy(&out); let loop_dev = _tmp.trim(); - println!("{:?}", out); + println!("{out:?}"); // Create filesystem. let fs_cmd = match fs { WindowsGuest::FS_FAT => "mkfs.msdos", WindowsGuest::FS_NTFS => "mkfs.ntfs", - _ => panic!("Unknown filesystem type '{}'", fs), + _ => panic!("Unknown filesystem type '{fs}'"), }; let out = Command::new(fs_cmd) .args([&loop_dev]) .output() - .unwrap_or_else(|_| panic!("{} failed", fs_cmd)) + .unwrap_or_else(|_| panic!("{fs_cmd} failed")) .stdout; - println!("{:?}", out); + println!("{out:?}"); // Disengage the loop device let out = Command::new("losetup") .args(["-d", loop_dev]) .output() - .unwrap_or_else(|_| panic!("loop device '{}' not found", loop_dev)) + .unwrap_or_else(|_| panic!("loop device '{loop_dev}' not found")) .stdout; - println!("{:?}", out); + println!("{out:?}"); img.to_str().unwrap().to_string() } @@ -6985,15 +6933,13 @@ mod windows { fn disk_file_put(&self, fname: &str, data: &str) { let _ = self.ssh_cmd(&format!( - "powershell -Command \"'{}' | Set-Content -Path {}\"", - data, fname + "powershell -Command \"'{data}' | Set-Content -Path {fname}\"" )); } fn disk_file_read(&self, fname: &str) -> String { self.ssh_cmd(&format!( - "powershell -Command \"Get-Content -Path {}\"", - fname + "powershell -Command \"Get-Content -Path {fname}\"" )) } @@ -7034,7 +6980,7 @@ mod windows { fn vcpu_threads_count(pid: u32) -> u8 { // ps -T -p 12345 | grep vcpu | wc -l let out = Command::new("ps") - .args(["-T", "-p", format!("{}", pid).as_str()]) + .args(["-T", "-p", format!("{pid}").as_str()]) .output() .expect("ps command failed") .stdout; @@ -7044,7 +6990,7 @@ mod windows { fn netdev_ctrl_threads_count(pid: u32) -> u8 { // ps -T -p 12345 | grep "_net[0-9]*_ctrl" | wc -l let out = Command::new("ps") - .args(["-T", "-p", format!("{}", pid).as_str()]) + .args(["-T", "-p", format!("{pid}").as_str()]) .output() .expect("ps command failed") .stdout; @@ -7058,7 +7004,7 @@ mod windows { fn disk_ctrl_threads_count(pid: u32) -> u8 { // ps -T -p 15782 | grep "_disk[0-9]*_q0" | wc -l let out = Command::new("ps") - .args(["-T", "-p", format!("{}", pid).as_str()]) + .args(["-T", "-p", format!("{pid}").as_str()]) .output() .expect("ps command failed") .stdout; @@ -7223,7 +7169,7 @@ mod windows { assert!(remote_command( &api_socket_source, "snapshot", - Some(format!("file://{}", snapshot_dir).as_str()), + Some(format!("file://{snapshot_dir}").as_str()), )); // Wait to make sure the snapshot is completed @@ -7239,7 +7185,7 @@ mod windows { .args(["--api-socket", &api_socket_restored]) .args([ "--restore", - format!("source_url=file://{}", snapshot_dir).as_str(), + format!("source_url=file://{snapshot_dir}").as_str(), ]) .capture_output() .spawn() @@ -7530,7 +7476,7 @@ mod windows { let (cmd_success, cmd_output) = remote_command_w_output( &api_socket, "add-disk", - Some(format!("path={},readonly=off", disk).as_str()), + Some(format!("path={disk},readonly=off").as_str()), ); assert!(cmd_success); assert!(String::from_utf8_lossy(&cmd_output).contains("\"id\":\"_disk2\"")); @@ -7560,7 +7506,7 @@ mod windows { let (cmd_success, _cmd_output) = remote_command_w_output( &api_socket, "add-disk", - Some(format!("path={},readonly=off", disk).as_str()), + Some(format!("path={disk},readonly=off").as_str()), ); assert!(cmd_success); thread::sleep(std::time::Duration::new(5, 0)); @@ -7642,11 +7588,11 @@ mod windows { let (cmd_success, cmd_output) = remote_command_w_output( &api_socket, "add-disk", - Some(format!("path={},readonly=off", disk).as_str()), + Some(format!("path={disk},readonly=off").as_str()), ); assert!(cmd_success); assert!(String::from_utf8_lossy(&cmd_output) - .contains(format!("\"id\":\"{}\"", disk_id).as_str())); + .contains(format!("\"id\":\"{disk_id}\"").as_str())); thread::sleep(std::time::Duration::new(5, 0)); // Online disk devices windows_guest.disks_set_rw(); @@ -7683,7 +7629,7 @@ mod windows { let (cmd_success, _cmd_output) = remote_command_w_output( &api_socket, "add-disk", - Some(format!("path={},readonly=off", disk).as_str()), + Some(format!("path={disk},readonly=off").as_str()), ); assert!(cmd_success); thread::sleep(std::time::Duration::new(5, 0)); @@ -7901,8 +7847,7 @@ mod vfio { .args([ "--cmdline", format!( - "{} kvm-intel.nested=1 vfio_iommu_type1.allow_unsafe_interrupts", - DIRECT_KERNEL_BOOT_CMDLINE + "{DIRECT_KERNEL_BOOT_CMDLINE} kvm-intel.nested=1 vfio_iommu_type1.allow_unsafe_interrupts" ) .as_str(), ]) @@ -8091,7 +8036,7 @@ mod vfio { .args(["--cpus", "boot=4"]) .args([ "--memory", - format!("size=4G,hotplug_size=4G,hotplug_method={}", hotplug_method).as_str(), + format!("size=4G,hotplug_size=4G,hotplug_method={hotplug_method}").as_str(), ]) .args(["--kernel", fw_path(FwType::RustHypervisorFirmware).as_str()]) .args(["--device", "path=/sys/bus/pci/devices/0000:31:00.0/"]) @@ -8226,9 +8171,9 @@ mod live_migration { // Start to receive migration from the destintion VM let mut receive_migration = Command::new(clh_command("ch-remote")) .args([ - &format!("--api-socket={}", dest_api_socket), + &format!("--api-socket={dest_api_socket}"), "receive-migration", - &format! {"unix:{}", migration_socket}, + &format! {"unix:{migration_socket}"}, ]) .stderr(Stdio::piped()) .stdout(Stdio::piped()) @@ -8241,7 +8186,7 @@ mod live_migration { let mut args = [ format!("--api-socket={}", &src_api_socket), "send-migration".to_string(), - format! {"unix:{}", migration_socket}, + format! {"unix:{migration_socket}"}, ] .to_vec(); @@ -8334,7 +8279,7 @@ mod live_migration { cleanup_ovs_dpdk(); } - panic!("Test failed: {}", message) + panic!("Test failed: {message}") } // This test exercises the local live-migration between two Cloud Hypervisor VMs on the @@ -8384,7 +8329,7 @@ mod live_migration { src_vm_cmd .args([ "--cpus", - format!("boot={},max={}", boot_vcpus, max_vcpus).as_str(), + format!("boot={boot_vcpus},max={max_vcpus}").as_str(), ]) .args(memory_param) .args(["--kernel", kernel_path.to_str().unwrap()]) @@ -8548,7 +8493,7 @@ mod live_migration { src_vm_cmd .args([ "--cpus", - format!("boot={},max={}", boot_vcpus, max_vcpus).as_str(), + format!("boot={boot_vcpus},max={max_vcpus}").as_str(), ]) .args(memory_param) .args(["--kernel", kernel_path.to_str().unwrap()]) @@ -8749,7 +8694,7 @@ mod live_migration { src_vm_cmd .args([ "--cpus", - format!("boot={},max={}", boot_vcpus, max_vcpus).as_str(), + format!("boot={boot_vcpus},max={max_vcpus}").as_str(), ]) .args(memory_param) .args(["--kernel", kernel_path.to_str().unwrap()]) @@ -8974,7 +8919,7 @@ mod live_migration { src_vm_cmd .args([ "--cpus", - format!("boot={},max={}", boot_vcpus, max_vcpus).as_str(), + format!("boot={boot_vcpus},max={max_vcpus}").as_str(), ]) .args(memory_param) .args(["--kernel", kernel_path.to_str().unwrap()]) @@ -9450,8 +9395,7 @@ mod rate_limiter { } eprintln!( - "\n\n==== check_rate_limit failed! ====\n\nmeasured={}, , lower_limit={}, upper_limit={}\n\n", - measured, lower_limit, upper_limit + "\n\n==== check_rate_limit failed! ====\n\nmeasured={measured}, , lower_limit={lower_limit}, upper_limit={upper_limit}\n\n" ); false @@ -9533,26 +9477,23 @@ mod rate_limiter { // Create the test block image assert!(exec_host_command_output(&format!( - "dd if=/dev/zero of={} bs=1M count=1024", - blk_rate_limiter_test_img + "dd if=/dev/zero of={blk_rate_limiter_test_img} bs=1M count=1024" )) .status .success()); let test_blk_params = if bandwidth { format!( - "path={},bw_size={},bw_refill_time={}", - blk_rate_limiter_test_img, bw_size, bw_refill_time + "path={blk_rate_limiter_test_img},bw_size={bw_size},bw_refill_time={bw_refill_time}" ) } else { format!( - "path={},ops_size={},ops_refill_time={}", - blk_rate_limiter_test_img, bw_size, bw_refill_time + "path={blk_rate_limiter_test_img},ops_size={bw_size},ops_refill_time={bw_refill_time}" ) }; let mut child = GuestCommand::new(&guest) - .args(["--cpus", &format!("boot={}", num_queues)]) + .args(["--cpus", &format!("boot={num_queues}")]) .args(["--memory", "size=4G"]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) @@ -9582,8 +9523,7 @@ mod rate_limiter { let fio_command = format!( "sudo fio --filename=/dev/vdc --name=test --output-format=json \ --direct=1 --bs=4k --ioengine=io_uring --iodepth=64 \ - --rw={} --runtime={} --numjobs={}", - fio_ops, test_timeout, num_queues + --rw={fio_ops} --runtime={test_timeout} --numjobs={num_queues}" ); let output = guest.ssh_command(&fio_command).unwrap(); diff --git a/tracer/src/tracer.rs b/tracer/src/tracer.rs index 9d641cfa6..298f046fe 100644 --- a/tracer/src/tracer.rs +++ b/tracer/src/tracer.rs @@ -80,7 +80,7 @@ impl Tracer { if let Some(depth) = self.thread_depths.get_mut(thread_name) { depth.fetch_sub(1, Ordering::SeqCst); } else { - panic!("Unmatched decreas for thread: {}", thread_name); + panic!("Unmatched decreas for thread: {thread_name}"); } } diff --git a/vhdx/src/vhdx.rs b/vhdx/src/vhdx.rs index 73261fe8d..78a0cb638 100644 --- a/vhdx/src/vhdx.rs +++ b/vhdx/src/vhdx.rs @@ -105,8 +105,7 @@ impl Read for Vhdx { std::io::Error::new( std::io::ErrorKind::Other, format!( - "Failed reading {} sectors from VHDx at index {}: {}", - sector_count, sector_index, e + "Failed reading {sector_count} sectors from VHDx at index {sector_index}: {e}" ), ) }) @@ -130,7 +129,7 @@ impl Write for Vhdx { self.vhdx_header.update(&mut self.file).map_err(|e| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Failed to update VHDx header: {}", e), + format!("Failed to update VHDx header: {e}"), ) })?; } @@ -148,8 +147,7 @@ impl Write for Vhdx { std::io::Error::new( std::io::ErrorKind::Other, format!( - "Failed writing {} sectors on VHDx at index {}: {}", - sector_count, sector_index, e + "Failed writing {sector_count} sectors on VHDx at index {sector_index}: {e}" ), ) }) diff --git a/vhost_user_block/src/lib.rs b/vhost_user_block/src/lib.rs index e073a4a1d..a5286e03d 100644 --- a/vhost_user_block/src/lib.rs +++ b/vhost_user_block/src/lib.rs @@ -77,7 +77,7 @@ pub const SYNTAX: &str = "vhost-user-block backend parameters \ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "vhost_user_block_error: {:?}", self) + write!(f, "vhost_user_block_error: {self:?}") } } @@ -502,7 +502,7 @@ pub fn start_block_backend(backend_command: &str) { let backend_config = match VhostUserBlkBackendConfig::parse(backend_command) { Ok(config) => config, Err(e) => { - println!("Failed parsing parameters {:?}", e); + println!("Failed parsing parameters {e:?}"); process::exit(1); } }; diff --git a/vhost_user_net/src/lib.rs b/vhost_user_net/src/lib.rs index b76b0c0b6..975e03bd7 100644 --- a/vhost_user_net/src/lib.rs +++ b/vhost_user_net/src/lib.rs @@ -62,7 +62,7 @@ num_queues=,queue_size=,tap=\""; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "vhost_user_net_error: {:?}", self) + write!(f, "vhost_user_net_error: {self:?}") } } @@ -346,7 +346,7 @@ pub fn start_net_backend(backend_command: &str) { let backend_config = match VhostUserNetBackendConfig::parse(backend_command) { Ok(config) => config, Err(e) => { - eprintln!("Failed parsing parameters {:?}", e); + eprintln!("Failed parsing parameters {e:?}"); process::exit(1); } }; diff --git a/virtio-devices/src/block.rs b/virtio-devices/src/block.rs index cd893e0e3..706a8b8c9 100644 --- a/virtio-devices/src/block.rs +++ b/virtio-devices/src/block.rs @@ -456,7 +456,7 @@ impl Block { let disk_size = disk_image.size().map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("Failed getting disk size: {}", e), + format!("Failed getting disk size: {e}"), ) })?; if disk_size % SECTOR_SIZE != 0 { diff --git a/virtio-devices/src/iommu.rs b/virtio-devices/src/iommu.rs index ead40d812..6c09105a1 100644 --- a/virtio-devices/src/iommu.rs +++ b/virtio-devices/src/iommu.rs @@ -793,7 +793,7 @@ impl DmaRemapping for IommuMapping { Err(io::Error::new( io::ErrorKind::Other, - format!("failed to translate GVA addr 0x{:x}", addr), + format!("failed to translate GVA addr 0x{addr:x}"), )) } @@ -821,7 +821,7 @@ impl DmaRemapping for IommuMapping { Err(io::Error::new( io::ErrorKind::Other, - format!("failed to translate GPA addr 0x{:x}", addr), + format!("failed to translate GPA addr 0x{addr:x}"), )) } } diff --git a/virtio-devices/src/mem.rs b/virtio-devices/src/mem.rs index d2c767ada..1a7ea6f1f 100644 --- a/virtio-devices/src/mem.rs +++ b/virtio-devices/src/mem.rs @@ -729,10 +729,7 @@ impl Mem { if region_len != region_len / VIRTIO_MEM_ALIGN_SIZE * VIRTIO_MEM_ALIGN_SIZE { return Err(io::Error::new( io::ErrorKind::Other, - format!( - "Virtio-mem size is not aligned with {}", - VIRTIO_MEM_ALIGN_SIZE - ), + format!("Virtio-mem size is not aligned with {VIRTIO_MEM_ALIGN_SIZE}"), )); } @@ -763,8 +760,7 @@ impl Mem { io::Error::new( io::ErrorKind::Other, format!( - "Failed to resize virtio-mem configuration to {}: {:?}", - initial_size, e + "Failed to resize virtio-mem configuration to {initial_size}: {e:?}" ), ) })?; @@ -780,7 +776,7 @@ impl Mem { config.validate().map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("Invalid virtio-mem configuration: {:?}", e), + format!("Invalid virtio-mem configuration: {e:?}"), ) })?; diff --git a/virtio-devices/src/vdpa.rs b/virtio-devices/src/vdpa.rs index ec395d065..74ebf1899 100644 --- a/virtio-devices/src/vdpa.rs +++ b/virtio-devices/src/vdpa.rs @@ -548,9 +548,8 @@ impl ExternalDmaMapping for VdpaDmaMapping ExternalDmaMapping for VdpaDmaMapping ExternalDmaMapping for VdpaDmaMapping VhostUserEpollHandler { .map_err(|e| { EpollHelperError::IoError(std::io::Error::new( std::io::ErrorKind::Other, - format!("failed connecting vhost-user backend {:?}", e), + format!("failed connecting vhost-user backend {e:?}"), )) })?; @@ -237,7 +237,7 @@ impl VhostUserEpollHandler { .map_err(|e| { EpollHelperError::IoError(std::io::Error::new( std::io::ErrorKind::Other, - format!("failed reconnecting vhost-user backend{:?}", e), + format!("failed reconnecting vhost-user backend{e:?}"), )) })?; diff --git a/virtio-devices/src/vsock/csm/connection.rs b/virtio-devices/src/vsock/csm/connection.rs index 3d5c7b9f9..a67d74bf7 100644 --- a/virtio-devices/src/vsock/csm/connection.rs +++ b/virtio-devices/src/vsock/csm/connection.rs @@ -853,7 +853,7 @@ mod tests { assert_eq!(pkt.op(), uapi::VSOCK_OP_RESPONSE); conn } - other => panic!("invalid ctx state: {:?}", other), + other => panic!("invalid ctx state: {other:?}"), }; assert_eq!(conn.state, conn_state); Self { @@ -971,7 +971,7 @@ mod tests { // There's no more data in the stream, so `recv_pkt` should yield `VsockError::NoData`. match ctx.conn.recv_pkt(&mut ctx.pkt) { Err(VsockError::NoData) => (), - other => panic!("{:?}", other), + other => panic!("{other:?}"), } // A recv attempt in an invalid state should yield an instant reset packet. diff --git a/virtio-devices/src/vsock/csm/txbuf.rs b/virtio-devices/src/vsock/csm/txbuf.rs index c4e4f6728..d36e28fb7 100644 --- a/virtio-devices/src/vsock/csm/txbuf.rs +++ b/virtio-devices/src/vsock/csm/txbuf.rs @@ -234,7 +234,7 @@ mod tests { txbuf.push(tmp.as_slice()).unwrap(); match txbuf.push(&[1, 2]) { Err(Error::TxBufFull) => (), - other => panic!("Unexpected result: {:?}", other), + other => panic!("Unexpected result: {other:?}"), } } @@ -267,7 +267,7 @@ mod tests { sink.set_err(io_err); match txbuf.flush_to(&mut sink) { Err(Error::TxBufFlush(ref err)) if err.kind() == ErrorKind::PermissionDenied => (), - other => panic!("Unexpected result: {:?}", other), + other => panic!("Unexpected result: {other:?}"), } } } diff --git a/virtio-devices/src/vsock/device.rs b/virtio-devices/src/vsock/device.rs index 8762cbe13..057760c78 100644 --- a/virtio-devices/src/vsock/device.rs +++ b/virtio-devices/src/vsock/device.rs @@ -598,7 +598,7 @@ mod tests { .activate(memory.clone(), Arc::new(NoopVirtioInterrupt {}), Vec::new()); match bad_activate { Err(ActivateError::BadActivate) => (), - other => panic!("{:?}", other), + other => panic!("{other:?}"), } // Test a correct activation. diff --git a/virtio-devices/src/vsock/unix/muxer.rs b/virtio-devices/src/vsock/unix/muxer.rs index 20922db6e..106eca978 100644 --- a/virtio-devices/src/vsock/unix/muxer.rs +++ b/virtio-devices/src/vsock/unix/muxer.rs @@ -852,7 +852,7 @@ mod tests { None, ) .unwrap(); - let uds_path = format!("test_vsock_{}.sock", name); + let uds_path = format!("test_vsock_{name}.sock"); let muxer = VsockMuxer::new(PEER_CID, uds_path).unwrap(); Self { @@ -932,7 +932,7 @@ mod tests { let (local_lsn_count, _) = self.count_epoll_listeners(); assert_eq!(local_lsn_count, init_local_lsn_count + 1); - let buf = format!("CONNECT {}\n", peer_port); + let buf = format!("CONNECT {peer_port}\n"); stream.write_all(buf.as_bytes()).unwrap(); // The muxer would now get notified that data is available for reading from the locally // initiated connection. @@ -966,7 +966,7 @@ mod tests { let mut buf = vec![0u8; 32]; let len = stream.read(&mut buf[..]).unwrap(); - assert_eq!(&buf[..len], format!("OK {}\n", local_port).as_bytes()); + assert_eq!(&buf[..len], format!("OK {local_port}\n").as_bytes()); (stream, local_port) } diff --git a/vm-device/src/bus.rs b/vm-device/src/bus.rs index 09784bbfc..6e581c9a9 100644 --- a/vm-device/src/bus.rs +++ b/vm-device/src/bus.rs @@ -40,7 +40,7 @@ pub type Result = result::Result; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "bus_error: {:?}", self) + write!(f, "bus_error: {self:?}") } } @@ -275,7 +275,7 @@ mod tests { let result = bus.insert(dummy.clone(), 0x0f, 0x10); assert!(result.is_err()); - assert_eq!(format!("{:?}", result), "Err(Overlap)"); + assert_eq!(format!("{result:?}"), "Err(Overlap)"); assert!(bus.insert(dummy.clone(), 0x10, 0x10).is_err()); assert!(bus.insert(dummy.clone(), 0x10, 0x15).is_err()); diff --git a/vm-device/src/dma_mapping/vfio.rs b/vm-device/src/dma_mapping/vfio.rs index 5ed7f5168..aac86e30e 100644 --- a/vm-device/src/dma_mapping/vfio.rs +++ b/vm-device/src/dma_mapping/vfio.rs @@ -37,9 +37,8 @@ impl ExternalDmaMapping for VfioDmaMapping ExternalDmaMapping for VfioDmaMapping ExternalDmaMapping for VfioDmaMapping "watchdog", VirtioDeviceType::Unknown => "UNKNOWN", }; - write!(f, "{}", output) + write!(f, "{output}") } } diff --git a/vmm/src/api/http.rs b/vmm/src/api/http.rs index 6cff020cb..fd5188271 100644 --- a/vmm/src/api/http.rs +++ b/vmm/src/api/http.rs @@ -52,7 +52,7 @@ const HTTP_ROOT: &str = "/api/v1"; pub fn error_response(error: HttpError, status: StatusCode) -> Response { let mut response = Response::new(Version::Http11, status); - response.set_body(Body::new(format!("{:?}", error))); + response.set_body(Body::new(format!("{error:?}"))); response } diff --git a/vmm/src/config.rs b/vmm/src/config.rs index 7f81531c2..145494108 100644 --- a/vmm/src/config.rs +++ b/vmm/src/config.rs @@ -209,7 +209,7 @@ impl fmt::Display for ValidationError { write!(f, "Huge page size specified but huge pages not enabled") } InvalidHugePageSize(s) => { - write!(f, "Huge page size is not power of 2: {}", s) + write!(f, "Huge page size is not power of 2: {s}") } #[cfg(feature = "tdx")] TdxNoCpuHotplug => { @@ -231,56 +231,50 @@ impl fmt::Display for ValidationError { MemoryZoneReused(s, u1, u2) => { write!( f, - "Memory zone: {} belongs to multiple NUMA nodes {} and {}", - s, u1, u2 + "Memory zone: {s} belongs to multiple NUMA nodes {u1} and {u2}" ) } InvalidNumPciSegments(n) => { write!( f, - "Number of PCI segments ({}) not in range of 1 to {}", - n, MAX_NUM_PCI_SEGMENTS + "Number of PCI segments ({n}) not in range of 1 to {MAX_NUM_PCI_SEGMENTS}" ) } InvalidPciSegment(pci_segment) => { - write!(f, "Invalid PCI segment id: {}", pci_segment) + write!(f, "Invalid PCI segment id: {pci_segment}") } BalloonLargerThanRam(balloon_size, ram_size) => { write!( f, - "Ballon size ({}) greater than RAM ({})", - balloon_size, ram_size + "Ballon size ({balloon_size}) greater than RAM ({ram_size})" ) } OnIommuSegment(pci_segment) => { write!( f, - "Device is on an IOMMU PCI segment ({}) but not placed behind IOMMU", - pci_segment + "Device is on an IOMMU PCI segment ({pci_segment}) but not placed behind IOMMU" ) } IommuNotSupportedOnSegment(pci_segment) => { write!( f, - "Device is on an IOMMU PCI segment ({}) but does not support being placed behind IOMMU", - pci_segment + "Device is on an IOMMU PCI segment ({pci_segment}) but does not support being placed behind IOMMU" ) } IdentifierNotUnique(s) => { - write!(f, "Identifier {} is not unique", s) + write!(f, "Identifier {s} is not unique") } InvalidIdentifier(s) => { - write!(f, "Identifier {} is invalid", s) + write!(f, "Identifier {s} is invalid") } IommuNotSupported => { write!(f, "Device does not support being placed behind IOMMU") } - DuplicateDevicePath(p) => write!(f, "Duplicated device path: {}", p), + DuplicateDevicePath(p) => write!(f, "Duplicated device path: {p}"), &InvalidMtu(mtu) => { write!( f, - "Provided MTU {} is lower than 1280 (expected by VIRTIO specification)", - mtu + "Provided MTU {mtu} is lower than 1280 (expected by VIRTIO specification)" ) } } @@ -291,51 +285,51 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { - ParseConsole(o) => write!(f, "Error parsing --console: {}", o), + ParseConsole(o) => write!(f, "Error parsing --console: {o}"), ParseConsoleInvalidModeGiven => { write!(f, "Error parsing --console: invalid console mode given") } - ParseCpus(o) => write!(f, "Error parsing --cpus: {}", o), - InvalidCpuFeatures(o) => write!(f, "Invalid feature in --cpus features list: {}", o), - ParseDevice(o) => write!(f, "Error parsing --device: {}", o), + ParseCpus(o) => write!(f, "Error parsing --cpus: {o}"), + InvalidCpuFeatures(o) => write!(f, "Invalid feature in --cpus features list: {o}"), + ParseDevice(o) => write!(f, "Error parsing --device: {o}"), ParseDevicePathMissing => write!(f, "Error parsing --device: path missing"), - ParseFileSystem(o) => write!(f, "Error parsing --fs: {}", o), + ParseFileSystem(o) => write!(f, "Error parsing --fs: {o}"), ParseFsSockMissing => write!(f, "Error parsing --fs: socket missing"), ParseFsTagMissing => write!(f, "Error parsing --fs: tag missing"), - ParsePersistentMemory(o) => write!(f, "Error parsing --pmem: {}", o), + ParsePersistentMemory(o) => write!(f, "Error parsing --pmem: {o}"), ParsePmemFileMissing => write!(f, "Error parsing --pmem: file missing"), - ParseVsock(o) => write!(f, "Error parsing --vsock: {}", o), + ParseVsock(o) => write!(f, "Error parsing --vsock: {o}"), ParseVsockCidMissing => write!(f, "Error parsing --vsock: cid missing"), ParseVsockSockMissing => write!(f, "Error parsing --vsock: socket missing"), - ParseMemory(o) => write!(f, "Error parsing --memory: {}", o), - ParseMemoryZone(o) => write!(f, "Error parsing --memory-zone: {}", o), + ParseMemory(o) => write!(f, "Error parsing --memory: {o}"), + ParseMemoryZone(o) => write!(f, "Error parsing --memory-zone: {o}"), ParseMemoryZoneIdMissing => write!(f, "Error parsing --memory-zone: id missing"), - ParseNetwork(o) => write!(f, "Error parsing --net: {}", o), - ParseDisk(o) => write!(f, "Error parsing --disk: {}", o), - ParseRng(o) => write!(f, "Error parsing --rng: {}", o), - ParseBalloon(o) => write!(f, "Error parsing --balloon: {}", o), - ParseRestore(o) => write!(f, "Error parsing --restore: {}", o), + ParseNetwork(o) => write!(f, "Error parsing --net: {o}"), + ParseDisk(o) => write!(f, "Error parsing --disk: {o}"), + ParseRng(o) => write!(f, "Error parsing --rng: {o}"), + ParseBalloon(o) => write!(f, "Error parsing --balloon: {o}"), + ParseRestore(o) => write!(f, "Error parsing --restore: {o}"), #[cfg(target_arch = "x86_64")] - ParseSgxEpc(o) => write!(f, "Error parsing --sgx-epc: {}", o), + ParseSgxEpc(o) => write!(f, "Error parsing --sgx-epc: {o}"), #[cfg(target_arch = "x86_64")] ParseSgxEpcIdMissing => write!(f, "Error parsing --sgx-epc: id missing"), - ParseNuma(o) => write!(f, "Error parsing --numa: {}", o), + ParseNuma(o) => write!(f, "Error parsing --numa: {o}"), ParseRestoreSourceUrlMissing => { write!(f, "Error parsing --restore: source_url missing") } ParseUserDeviceSocketMissing => { write!(f, "Error parsing --user-device: socket missing") } - ParseUserDevice(o) => write!(f, "Error parsing --user-device: {}", o), - Validation(v) => write!(f, "Error validating configuration: {}", v), + ParseUserDevice(o) => write!(f, "Error parsing --user-device: {o}"), + Validation(v) => write!(f, "Error validating configuration: {v}"), #[cfg(feature = "tdx")] - ParseTdx(o) => write!(f, "Error parsing --tdx: {}", o), + ParseTdx(o) => write!(f, "Error parsing --tdx: {o}"), #[cfg(feature = "tdx")] FirmwarePathMissing => write!(f, "TDX firmware missing"), - ParsePlatform(o) => write!(f, "Error parsing --platform: {}", o), - ParseVdpa(o) => write!(f, "Error parsing --vdpa: {}", o), + ParsePlatform(o) => write!(f, "Error parsing --platform: {o}"), + ParseVdpa(o) => write!(f, "Error parsing --vdpa: {o}"), ParseVdpaPathMissing => write!(f, "Error parsing --vdpa: path missing"), - ParseTpm(o) => write!(f, "Error parsing --tpm: {}", o), + ParseTpm(o) => write!(f, "Error parsing --tpm: {o}"), ParseTpmPathMissing => write!(f, "Error parsing --tpm: path missing"), } } diff --git a/vmm/src/cpu.rs b/vmm/src/cpu.rs index 7231d33eb..fcf5265d7 100644 --- a/vmm/src/cpu.rs +++ b/vmm/src/cpu.rs @@ -848,7 +848,7 @@ impl CpuManager { let handle = Some( thread::Builder::new() - .name(format!("vcpu{}", vcpu_id)) + .name(format!("vcpu{vcpu_id}")) .spawn(move || { // Schedule the thread to run on the expected CPU set if let Some(cpuset) = cpuset.as_ref() { @@ -1589,8 +1589,7 @@ impl CpuManager { 6 => 52, _ => { return Err(Error::TranslateVirtualAddress(anyhow!(format!( - "PA range not supported {}", - pa_range + "PA range not supported {pa_range}" )))) } }; diff --git a/vmm/src/device_manager.rs b/vmm/src/device_manager.rs index c14c8c6ee..cabd185a7 100644 --- a/vmm/src/device_manager.rs +++ b/vmm/src/device_manager.rs @@ -517,7 +517,7 @@ pub fn create_pty() -> io::Result<(File, File, PathBuf)> { return vmm_sys_util::errno::errno_result().map_err(|e| e.into()); } - let proc_path = PathBuf::from(format!("/proc/self/fd/{}", sub_fd)); + let proc_path = PathBuf::from(format!("/proc/self/fd/{sub_fd}")); let path = read_link(proc_path)?; // SAFETY: sub_fd is checked to be valid before being wrapped in File @@ -665,15 +665,14 @@ impl DeviceRelocation for AddressManager { return Err(io::Error::new( io::ErrorKind::Other, format!( - "Couldn't find a resource with base 0x{:x} for device {}", - old_base, id + "Couldn't find a resource with base 0x{old_base:x} for device {id}" ), )); } } else { return Err(io::Error::new( io::ErrorKind::Other, - format!("Couldn't find device {} from device tree", id), + format!("Couldn't find device {id} from device tree"), )); } } @@ -687,7 +686,7 @@ impl DeviceRelocation for AddressManager { self.vm.unregister_ioevent(event, &io_addr).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("failed to unregister ioevent: {:?}", e), + format!("failed to unregister ioevent: {e:?}"), ) })?; } @@ -698,7 +697,7 @@ impl DeviceRelocation for AddressManager { .map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("failed to register ioevent: {:?}", e), + format!("failed to register ioevent: {e:?}"), ) })?; } @@ -719,7 +718,7 @@ impl DeviceRelocation for AddressManager { self.vm.remove_user_memory_region(mem_region).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("failed to remove user memory region: {:?}", e), + format!("failed to remove user memory region: {e:?}"), ) })?; @@ -736,7 +735,7 @@ impl DeviceRelocation for AddressManager { self.vm.create_user_memory_region(mem_region).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("failed to create user memory regions: {:?}", e), + format!("failed to create user memory regions: {e:?}"), ) })?; @@ -745,7 +744,7 @@ impl DeviceRelocation for AddressManager { virtio_dev.set_shm_regions(shm_regions).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("failed to update shared memory regions: {:?}", e), + format!("failed to update shared memory regions: {e:?}"), ) })?; } @@ -3435,7 +3434,7 @@ impl DeviceManager { pci_segment_id: u16, dma_handler: Option>, ) -> DeviceManagerResult { - let id = format!("{}-{}", VIRTIO_PCI_DEVICE_NAME_PREFIX, virtio_device_id); + let id = format!("{VIRTIO_PCI_DEVICE_NAME_PREFIX}-{virtio_device_id}"); // Add the new virtio-pci node to the device tree. let mut node = device_node!(id); @@ -4237,7 +4236,7 @@ impl Aml for DeviceManager { let mut pci_scan_methods = Vec::new(); for i in 0..self.pci_segments.len() { pci_scan_methods.push(aml::MethodCall::new( - format!("\\_SB_.PCI{:X}.PCNT", i).as_str().into(), + format!("\\_SB_.PCI{i:X}.PCNT").as_str().into(), vec![], )); } diff --git a/vmm/src/gdb.rs b/vmm/src/gdb.rs index aecbb6088..50634631d 100644 --- a/vmm/src/gdb.rs +++ b/vmm/src/gdb.rs @@ -294,8 +294,8 @@ impl MultiThreadBase for GdbStub { }); Ok(()) } - Ok(s) => Err(format!("Unexpected response for ActiveVcpus: {:?}", s)), - Err(e) => Err(format!("Failed to request ActiveVcpus: {:?}", e)), + Ok(s) => Err(format!("Unexpected response for ActiveVcpus: {s:?}")), + Err(e) => Err(format!("Failed to request ActiveVcpus: {e:?}")), } } @@ -309,7 +309,7 @@ impl MultiThreadResume for GdbStub { fn resume(&mut self) -> Result<(), Self::Error> { match self.vm_request(GdbRequestPayload::Resume, 0) { Ok(_) => Ok(()), - Err(e) => Err(format!("Failed to resume the target: {:?}", e)), + Err(e) => Err(format!("Failed to resume the target: {e:?}")), } } @@ -320,7 +320,7 @@ impl MultiThreadResume for GdbStub { self.single_step = false; } Err(e) => { - return Err(format!("Failed to request SetSingleStep: {:?}", e)); + return Err(format!("Failed to request SetSingleStep: {e:?}")); } } } @@ -337,7 +337,7 @@ impl MultiThreadResume for GdbStub { } match self.vm_request(GdbRequestPayload::Resume, tid_to_cpuid(tid)) { Ok(_) => Ok(()), - Err(e) => Err(format!("Failed to resume the target: {:?}", e)), + Err(e) => Err(format!("Failed to resume the target: {e:?}")), } } @@ -363,13 +363,13 @@ impl MultiThreadSingleStep for GdbStub { self.single_step = true; } Err(e) => { - return Err(format!("Failed to request SetSingleStep: {:?}", e)); + return Err(format!("Failed to request SetSingleStep: {e:?}")); } } } match self.vm_request(GdbRequestPayload::Resume, tid_to_cpuid(tid)) { Ok(_) => Ok(()), - Err(e) => Err(format!("Failed to resume the target: {:?}", e)), + Err(e) => Err(format!("Failed to resume the target: {e:?}")), } } } diff --git a/vmm/src/interrupt.rs b/vmm/src/interrupt.rs index 074392e49..a9cc16f8a 100644 --- a/vmm/src/interrupt.rs +++ b/vmm/src/interrupt.rs @@ -44,7 +44,7 @@ impl InterruptRoute { vm.register_irqfd(&self.irq_fd, self.gsi).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("Failed registering irq_fd: {}", e), + format!("Failed registering irq_fd: {e}"), ) })?; @@ -60,7 +60,7 @@ impl InterruptRoute { vm.unregister_irqfd(&self.irq_fd, self.gsi).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("Failed unregistering irq_fd: {}", e), + format!("Failed unregistering irq_fd: {e}"), ) })?; @@ -109,7 +109,7 @@ impl MsiInterruptGroup { self.vm.set_gsi_routing(&entry_vec).map_err(|e| { io::Error::new( io::ErrorKind::Other, - format!("Failed setting GSI routing: {}", e), + format!("Failed setting GSI routing: {e}"), ) }) } @@ -153,7 +153,7 @@ impl InterruptSourceGroup for MsiInterruptGroup { Err(io::Error::new( io::ErrorKind::Other, - format!("trigger: Invalid interrupt index {}", index), + format!("trigger: Invalid interrupt index {index}"), )) } @@ -188,7 +188,7 @@ impl InterruptSourceGroup for MsiInterruptGroup { Err(io::Error::new( io::ErrorKind::Other, - format!("update: Invalid interrupt index {}", index), + format!("update: Invalid interrupt index {index}"), )) } } diff --git a/vmm/src/sigwinch_listener.rs b/vmm/src/sigwinch_listener.rs index e5e1dfe06..60188ef57 100644 --- a/vmm/src/sigwinch_listener.rs +++ b/vmm/src/sigwinch_listener.rs @@ -109,8 +109,7 @@ fn sigwinch_listener_main(seccomp_filter: BpfProgram, tx: File, pty: File) -> ! let e = io::Error::last_os_error(); assert!( matches!(e.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock), - "poll: {}", - e + "poll: {e}" ); } diff --git a/vmm/src/vm.rs b/vmm/src/vm.rs index 5c4138327..2cd815c03 100644 --- a/vmm/src/vm.rs +++ b/vmm/src/vm.rs @@ -862,9 +862,7 @@ impl Vm { .map_err(|_| Error::InitramfsLoad)? .try_into() .unwrap(); - initramfs - .seek(SeekFrom::Start(0)) - .map_err(|_| Error::InitramfsLoad)?; + initramfs.rewind().map_err(|_| Error::InitramfsLoad)?; let address = arch::initramfs_load_addr(guest_mem, size).map_err(|_| Error::InitramfsLoad)?; @@ -1829,9 +1827,7 @@ impl Vm { return Err(Error::InvalidPayloadType); } - payload_file - .seek(SeekFrom::Start(0)) - .map_err(Error::LoadPayload)?; + payload_file.rewind().map_err(Error::LoadPayload)?; mem.read_from( GuestAddress(section.address), payload_file, @@ -3174,7 +3170,7 @@ pub fn test_vm() { println!("HLT"); break; } - r => panic!("unexpected exit reason: {:?}", r), + r => panic!("unexpected exit reason: {r:?}"), } } }