xref: /cloud-hypervisor/test_infra/src/lib.rs (revision 4d7a4c598ac247aaf770b00dfb057cdac891f67d)
1 // Copyright © 2021 Intel Corporation
2 //
3 // SPDX-License-Identifier: Apache-2.0
4 //
5 
6 #![allow(clippy::undocumented_unsafe_blocks)]
7 
8 use once_cell::sync::Lazy;
9 use serde_json::Value;
10 use ssh2::Session;
11 use std::env;
12 use std::ffi::OsStr;
13 use std::io;
14 use std::io::{Read, Write};
15 use std::net::TcpListener;
16 use std::net::TcpStream;
17 use std::os::unix::fs::PermissionsExt;
18 use std::os::unix::io::{AsRawFd, FromRawFd};
19 use std::path::Path;
20 use std::process::{Child, Command, ExitStatus, Output, Stdio};
21 use std::str::FromStr;
22 use std::sync::Mutex;
23 use std::thread;
24 use std::time::Duration;
25 use std::{fmt, fs};
26 use vmm_sys_util::tempdir::TempDir;
27 use wait_timeout::ChildExt;
28 
29 #[derive(Debug)]
30 pub enum WaitTimeoutError {
31     Timedout,
32     ExitStatus,
33     General(std::io::Error),
34 }
35 
36 #[derive(Debug)]
37 pub enum Error {
38     Parsing(std::num::ParseIntError),
39     SshCommand(SshCommandError),
40     WaitForBoot(WaitForBootError),
41     EthrLogFile(std::io::Error),
42     EthrLogParse,
43     FioOutputParse,
44     Iperf3Parse,
45     Spawn(std::io::Error),
46     WaitTimeout(WaitTimeoutError),
47 }
48 
49 impl From<SshCommandError> for Error {
50     fn from(e: SshCommandError) -> Self {
51         Self::SshCommand(e)
52     }
53 }
54 
55 pub struct GuestNetworkConfig {
56     pub guest_ip: String,
57     pub l2_guest_ip1: String,
58     pub l2_guest_ip2: String,
59     pub l2_guest_ip3: String,
60     pub host_ip: String,
61     pub guest_mac: String,
62     pub l2_guest_mac1: String,
63     pub l2_guest_mac2: String,
64     pub l2_guest_mac3: String,
65     pub tcp_listener_port: u16,
66 }
67 
68 pub const DEFAULT_TCP_LISTENER_MESSAGE: &str = "booted";
69 pub const DEFAULT_TCP_LISTENER_PORT: u16 = 8000;
70 pub const DEFAULT_TCP_LISTENER_TIMEOUT: i32 = 120;
71 
72 #[derive(Debug)]
73 pub enum WaitForBootError {
74     EpollWait(std::io::Error),
75     Listen(std::io::Error),
76     EpollWaitTimeout,
77     WrongGuestAddr,
78     Accept(std::io::Error),
79 }
80 
81 impl GuestNetworkConfig {
82     pub fn wait_vm_boot(&self, custom_timeout: Option<i32>) -> Result<(), WaitForBootError> {
83         let start = std::time::Instant::now();
84         // The 'port' is unique per 'GUEST' and listening to wild-card ip avoids retrying on 'TcpListener::bind()'
85         let listen_addr = format!("0.0.0.0:{}", self.tcp_listener_port);
86         let expected_guest_addr = self.guest_ip.as_str();
87         let mut s = String::new();
88         let timeout = match custom_timeout {
89             Some(t) => t,
90             None => DEFAULT_TCP_LISTENER_TIMEOUT,
91         };
92 
93         match (|| -> Result<(), WaitForBootError> {
94             let listener =
95                 TcpListener::bind(listen_addr.as_str()).map_err(WaitForBootError::Listen)?;
96             listener
97                 .set_nonblocking(true)
98                 .expect("Cannot set non-blocking for tcp listener");
99 
100             // Reply on epoll w/ timeout to wait for guest connections faithfully
101             let epoll_fd = epoll::create(true).expect("Cannot create epoll fd");
102             // Use 'File' to enforce closing on 'epoll_fd'
103             let _epoll_file = unsafe { fs::File::from_raw_fd(epoll_fd) };
104             epoll::ctl(
105                 epoll_fd,
106                 epoll::ControlOptions::EPOLL_CTL_ADD,
107                 listener.as_raw_fd(),
108                 epoll::Event::new(epoll::Events::EPOLLIN, 0),
109             )
110             .expect("Cannot add 'tcp_listener' event to epoll");
111             let mut events = [epoll::Event::new(epoll::Events::empty(), 0); 1];
112             loop {
113                 let num_events = match epoll::wait(epoll_fd, timeout * 1000_i32, &mut events[..]) {
114                     Ok(num_events) => Ok(num_events),
115                     Err(e) => match e.raw_os_error() {
116                         Some(libc::EAGAIN) | Some(libc::EINTR) => continue,
117                         _ => Err(e),
118                     },
119                 }
120                 .map_err(WaitForBootError::EpollWait)?;
121                 if num_events == 0 {
122                     return Err(WaitForBootError::EpollWaitTimeout);
123                 }
124                 break;
125             }
126 
127             match listener.accept() {
128                 Ok((_, addr)) => {
129                     // Make sure the connection is from the expected 'guest_addr'
130                     if addr.ip() != std::net::IpAddr::from_str(expected_guest_addr).unwrap() {
131                         s = format!(
132                             "Expecting the guest ip '{}' while being connected with ip '{}'",
133                             expected_guest_addr,
134                             addr.ip()
135                         );
136                         return Err(WaitForBootError::WrongGuestAddr);
137                     }
138 
139                     Ok(())
140                 }
141                 Err(e) => {
142                     s = "TcpListener::accept() failed".to_string();
143                     Err(WaitForBootError::Accept(e))
144                 }
145             }
146         })() {
147             Err(e) => {
148                 let duration = start.elapsed();
149                 eprintln!(
150                     "\n\n==== Start 'wait_vm_boot' (FAILED) ==== \
151                     \n\nduration =\"{duration:?}, timeout = {timeout}s\" \
152                     \nlisten_addr=\"{listen_addr}\" \
153                     \nexpected_guest_addr=\"{expected_guest_addr}\" \
154                     \nmessage=\"{s}\" \
155                     \nerror=\"{e:?}\" \
156                     \n\n==== End 'wait_vm_boot' outout ====\n\n"
157                 );
158 
159                 Err(e)
160             }
161             Ok(_) => Ok(()),
162         }
163     }
164 }
165 
166 pub enum DiskType {
167     OperatingSystem,
168     CloudInit,
169 }
170 
171 pub trait DiskConfig {
172     fn prepare_files(&mut self, tmp_dir: &TempDir, network: &GuestNetworkConfig);
173     fn prepare_cloudinit(&self, tmp_dir: &TempDir, network: &GuestNetworkConfig) -> String;
174     fn disk(&self, disk_type: DiskType) -> Option<String>;
175 }
176 
177 #[derive(Clone)]
178 pub struct UbuntuDiskConfig {
179     osdisk_path: String,
180     cloudinit_path: String,
181     image_name: String,
182 }
183 
184 impl UbuntuDiskConfig {
185     pub fn new(image_name: String) -> Self {
186         UbuntuDiskConfig {
187             image_name,
188             osdisk_path: String::new(),
189             cloudinit_path: String::new(),
190         }
191     }
192 }
193 
194 pub struct WindowsDiskConfig {
195     image_name: String,
196     osdisk_path: String,
197     loopback_device: String,
198     windows_snapshot_cow: String,
199     windows_snapshot: String,
200 }
201 
202 impl WindowsDiskConfig {
203     pub fn new(image_name: String) -> Self {
204         WindowsDiskConfig {
205             image_name,
206             osdisk_path: String::new(),
207             loopback_device: String::new(),
208             windows_snapshot_cow: String::new(),
209             windows_snapshot: String::new(),
210         }
211     }
212 }
213 
214 impl Drop for WindowsDiskConfig {
215     fn drop(&mut self) {
216         // dmsetup remove windows-snapshot-1
217         std::process::Command::new("dmsetup")
218             .arg("remove")
219             .arg(self.windows_snapshot.as_str())
220             .output()
221             .expect("Expect removing Windows snapshot with 'dmsetup' to succeed");
222 
223         // dmsetup remove windows-snapshot-cow-1
224         std::process::Command::new("dmsetup")
225             .arg("remove")
226             .arg(self.windows_snapshot_cow.as_str())
227             .output()
228             .expect("Expect removing Windows snapshot CoW with 'dmsetup' to succeed");
229 
230         // losetup -d <loopback_device>
231         std::process::Command::new("losetup")
232             .args(["-d", self.loopback_device.as_str()])
233             .output()
234             .expect("Expect removing loopback device to succeed");
235     }
236 }
237 
238 impl DiskConfig for UbuntuDiskConfig {
239     fn prepare_cloudinit(&self, tmp_dir: &TempDir, network: &GuestNetworkConfig) -> String {
240         let cloudinit_file_path =
241             String::from(tmp_dir.as_path().join("cloudinit").to_str().unwrap());
242 
243         let cloud_init_directory = tmp_dir.as_path().join("cloud-init").join("ubuntu");
244 
245         fs::create_dir_all(&cloud_init_directory)
246             .expect("Expect creating cloud-init directory to succeed");
247 
248         let source_file_dir = std::env::current_dir()
249             .unwrap()
250             .join("test_data")
251             .join("cloud-init")
252             .join("ubuntu")
253             .join("ci");
254 
255         ["meta-data"].iter().for_each(|x| {
256             rate_limited_copy(source_file_dir.join(x), cloud_init_directory.join(x))
257                 .expect("Expect copying cloud-init meta-data to succeed");
258         });
259 
260         let mut user_data_string = String::new();
261         fs::File::open(source_file_dir.join("user-data"))
262             .unwrap()
263             .read_to_string(&mut user_data_string)
264             .expect("Expected reading user-data file in to succeed");
265         user_data_string = user_data_string.replace(
266             "@DEFAULT_TCP_LISTENER_MESSAGE",
267             DEFAULT_TCP_LISTENER_MESSAGE,
268         );
269         user_data_string = user_data_string.replace("@HOST_IP", &network.host_ip);
270         user_data_string =
271             user_data_string.replace("@TCP_LISTENER_PORT", &network.tcp_listener_port.to_string());
272 
273         fs::File::create(cloud_init_directory.join("user-data"))
274             .unwrap()
275             .write_all(user_data_string.as_bytes())
276             .expect("Expected writing out user-data to succeed");
277 
278         let mut network_config_string = String::new();
279 
280         fs::File::open(source_file_dir.join("network-config"))
281             .unwrap()
282             .read_to_string(&mut network_config_string)
283             .expect("Expected reading network-config file in to succeed");
284 
285         network_config_string = network_config_string.replace("192.168.2.1", &network.host_ip);
286         network_config_string = network_config_string.replace("192.168.2.2", &network.guest_ip);
287         network_config_string = network_config_string.replace("192.168.2.3", &network.l2_guest_ip1);
288         network_config_string = network_config_string.replace("192.168.2.4", &network.l2_guest_ip2);
289         network_config_string = network_config_string.replace("192.168.2.5", &network.l2_guest_ip3);
290         network_config_string =
291             network_config_string.replace("12:34:56:78:90:ab", &network.guest_mac);
292         network_config_string =
293             network_config_string.replace("de:ad:be:ef:12:34", &network.l2_guest_mac1);
294         network_config_string =
295             network_config_string.replace("de:ad:be:ef:34:56", &network.l2_guest_mac2);
296         network_config_string =
297             network_config_string.replace("de:ad:be:ef:56:78", &network.l2_guest_mac3);
298 
299         fs::File::create(cloud_init_directory.join("network-config"))
300             .unwrap()
301             .write_all(network_config_string.as_bytes())
302             .expect("Expected writing out network-config to succeed");
303 
304         std::process::Command::new("mkdosfs")
305             .args(["-n", "CIDATA"])
306             .args(["-C", cloudinit_file_path.as_str()])
307             .arg("8192")
308             .output()
309             .expect("Expect creating disk image to succeed");
310 
311         ["user-data", "meta-data", "network-config"]
312             .iter()
313             .for_each(|x| {
314                 std::process::Command::new("mcopy")
315                     .arg("-o")
316                     .args(["-i", cloudinit_file_path.as_str()])
317                     .args(["-s", cloud_init_directory.join(x).to_str().unwrap(), "::"])
318                     .output()
319                     .expect("Expect copying files to disk image to succeed");
320             });
321 
322         cloudinit_file_path
323     }
324 
325     fn prepare_files(&mut self, tmp_dir: &TempDir, network: &GuestNetworkConfig) {
326         let mut workload_path = dirs::home_dir().unwrap();
327         workload_path.push("workloads");
328 
329         let mut osdisk_base_path = workload_path;
330         osdisk_base_path.push(&self.image_name);
331 
332         let osdisk_path = String::from(tmp_dir.as_path().join("osdisk.img").to_str().unwrap());
333         let cloudinit_path = self.prepare_cloudinit(tmp_dir, network);
334 
335         rate_limited_copy(osdisk_base_path, &osdisk_path)
336             .expect("copying of OS source disk image failed");
337 
338         self.cloudinit_path = cloudinit_path;
339         self.osdisk_path = osdisk_path;
340     }
341 
342     fn disk(&self, disk_type: DiskType) -> Option<String> {
343         match disk_type {
344             DiskType::OperatingSystem => Some(self.osdisk_path.clone()),
345             DiskType::CloudInit => Some(self.cloudinit_path.clone()),
346         }
347     }
348 }
349 
350 impl DiskConfig for WindowsDiskConfig {
351     fn prepare_cloudinit(&self, _tmp_dir: &TempDir, _network: &GuestNetworkConfig) -> String {
352         String::new()
353     }
354 
355     fn prepare_files(&mut self, tmp_dir: &TempDir, _network: &GuestNetworkConfig) {
356         let mut workload_path = dirs::home_dir().unwrap();
357         workload_path.push("workloads");
358 
359         let mut osdisk_path = workload_path;
360         osdisk_path.push(&self.image_name);
361 
362         let osdisk_blk_size = fs::metadata(osdisk_path)
363             .expect("Expect retrieving Windows image metadata")
364             .len()
365             >> 9;
366 
367         let snapshot_cow_path =
368             String::from(tmp_dir.as_path().join("snapshot_cow").to_str().unwrap());
369 
370         // Create and truncate CoW file for device mapper
371         let cow_file_size: u64 = 1 << 30;
372         let cow_file_blk_size = cow_file_size >> 9;
373         let cow_file = std::fs::File::create(snapshot_cow_path.as_str())
374             .expect("Expect creating CoW image to succeed");
375         cow_file
376             .set_len(cow_file_size)
377             .expect("Expect truncating CoW image to succeed");
378 
379         // losetup --find --show /tmp/snapshot_cow
380         let loopback_device = std::process::Command::new("losetup")
381             .arg("--find")
382             .arg("--show")
383             .arg(snapshot_cow_path.as_str())
384             .output()
385             .expect("Expect creating loopback device from snapshot CoW image to succeed");
386 
387         self.loopback_device = String::from_utf8_lossy(&loopback_device.stdout)
388             .trim()
389             .to_string();
390 
391         let random_extension = tmp_dir.as_path().file_name().unwrap();
392         let windows_snapshot_cow = format!(
393             "windows-snapshot-cow-{}",
394             random_extension.to_str().unwrap()
395         );
396 
397         // dmsetup create windows-snapshot-cow-1 --table '0 2097152 linear /dev/loop1 0'
398         std::process::Command::new("dmsetup")
399             .arg("create")
400             .arg(windows_snapshot_cow.as_str())
401             .args([
402                 "--table",
403                 format!("0 {} linear {} 0", cow_file_blk_size, self.loopback_device).as_str(),
404             ])
405             .output()
406             .expect("Expect creating Windows snapshot CoW with 'dmsetup' to succeed");
407 
408         let windows_snapshot = format!("windows-snapshot-{}", random_extension.to_str().unwrap());
409 
410         // dmsetup mknodes
411         std::process::Command::new("dmsetup")
412             .arg("mknodes")
413             .output()
414             .expect("Expect device mapper nodes to be ready");
415 
416         // dmsetup create windows-snapshot-1 --table '0 41943040 snapshot /dev/mapper/windows-base /dev/mapper/windows-snapshot-cow-1 P 8'
417         std::process::Command::new("dmsetup")
418             .arg("create")
419             .arg(windows_snapshot.as_str())
420             .args([
421                 "--table",
422                 format!(
423                     "0 {} snapshot /dev/mapper/windows-base /dev/mapper/{} P 8",
424                     osdisk_blk_size,
425                     windows_snapshot_cow.as_str()
426                 )
427                 .as_str(),
428             ])
429             .output()
430             .expect("Expect creating Windows snapshot with 'dmsetup' to succeed");
431 
432         // dmsetup mknodes
433         std::process::Command::new("dmsetup")
434             .arg("mknodes")
435             .output()
436             .expect("Expect device mapper nodes to be ready");
437 
438         self.osdisk_path = format!("/dev/mapper/{windows_snapshot}");
439         self.windows_snapshot_cow = windows_snapshot_cow;
440         self.windows_snapshot = windows_snapshot;
441     }
442 
443     fn disk(&self, disk_type: DiskType) -> Option<String> {
444         match disk_type {
445             DiskType::OperatingSystem => Some(self.osdisk_path.clone()),
446             DiskType::CloudInit => None,
447         }
448     }
449 }
450 
451 pub fn rate_limited_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
452     for i in 0..10 {
453         let free_bytes = unsafe {
454             let mut stats = std::mem::MaybeUninit::zeroed();
455             let fs_name = std::ffi::CString::new("/tmp").unwrap();
456             libc::statvfs(fs_name.as_ptr(), stats.as_mut_ptr());
457 
458             let free_blocks = stats.assume_init().f_bfree;
459             let block_size = stats.assume_init().f_bsize;
460 
461             free_blocks * block_size
462         };
463 
464         // Make sure there is at least 6 GiB of space
465         if free_bytes < 6 << 30 {
466             eprintln!("Not enough space on disk ({free_bytes}). Attempt {i} of 10. Sleeping.");
467             thread::sleep(std::time::Duration::new(60, 0));
468             continue;
469         }
470 
471         match fs::copy(&from, &to) {
472             Err(e) => {
473                 if let Some(errno) = e.raw_os_error() {
474                     if errno == libc::ENOSPC {
475                         eprintln!("Copy returned ENOSPC. Attempt {i} of 10. Sleeping.");
476                         thread::sleep(std::time::Duration::new(60, 0));
477                         continue;
478                     }
479                 }
480                 return Err(e);
481             }
482             Ok(i) => return Ok(i),
483         }
484     }
485     Err(io::Error::last_os_error())
486 }
487 
488 pub fn handle_child_output(
489     r: Result<(), std::boxed::Box<dyn std::any::Any + std::marker::Send>>,
490     output: &std::process::Output,
491 ) {
492     use std::os::unix::process::ExitStatusExt;
493     if r.is_ok() && output.status.success() {
494         return;
495     }
496 
497     match output.status.code() {
498         None => {
499             // Don't treat child.kill() as a problem
500             if output.status.signal() == Some(9) && r.is_ok() {
501                 return;
502             }
503 
504             eprintln!(
505                 "==== child killed by signal: {} ====",
506                 output.status.signal().unwrap()
507             );
508         }
509         Some(code) => {
510             eprintln!("\n\n==== child exit code: {code} ====");
511         }
512     }
513 
514     eprintln!(
515         "\n\n==== Start child stdout ====\n\n{}\n\n==== End child stdout ====",
516         String::from_utf8_lossy(&output.stdout)
517     );
518     eprintln!(
519         "\n\n==== Start child stderr ====\n\n{}\n\n==== End child stderr ====",
520         String::from_utf8_lossy(&output.stderr)
521     );
522 
523     panic!("Test failed")
524 }
525 
526 #[derive(Debug)]
527 pub struct PasswordAuth {
528     pub username: String,
529     pub password: String,
530 }
531 
532 pub const DEFAULT_SSH_RETRIES: u8 = 6;
533 pub const DEFAULT_SSH_TIMEOUT: u8 = 10;
534 
535 #[derive(Debug)]
536 pub enum SshCommandError {
537     Connection(std::io::Error),
538     Handshake(ssh2::Error),
539     Authentication(ssh2::Error),
540     ChannelSession(ssh2::Error),
541     Command(ssh2::Error),
542     ExitStatus(ssh2::Error),
543     NonZeroExitStatus(i32),
544     FileRead(std::io::Error),
545     FileMetadata(std::io::Error),
546     ScpSend(ssh2::Error),
547     WriteAll(std::io::Error),
548     SendEof(ssh2::Error),
549     WaitEof(ssh2::Error),
550 }
551 
552 fn scp_to_guest_with_auth(
553     path: &Path,
554     remote_path: &Path,
555     auth: &PasswordAuth,
556     ip: &str,
557     retries: u8,
558     timeout: u8,
559 ) -> Result<(), SshCommandError> {
560     let mut counter = 0;
561     loop {
562         match (|| -> Result<(), SshCommandError> {
563             let tcp =
564                 TcpStream::connect(format!("{ip}:22")).map_err(SshCommandError::Connection)?;
565             let mut sess = Session::new().unwrap();
566             sess.set_tcp_stream(tcp);
567             sess.handshake().map_err(SshCommandError::Handshake)?;
568 
569             sess.userauth_password(&auth.username, &auth.password)
570                 .map_err(SshCommandError::Authentication)?;
571             assert!(sess.authenticated());
572 
573             let content = fs::read(path).map_err(SshCommandError::FileRead)?;
574             let mode = fs::metadata(path)
575                 .map_err(SshCommandError::FileMetadata)?
576                 .permissions()
577                 .mode()
578                 & 0o777;
579 
580             let mut channel = sess
581                 .scp_send(remote_path, mode as i32, content.len() as u64, None)
582                 .map_err(SshCommandError::ScpSend)?;
583             channel
584                 .write_all(&content)
585                 .map_err(SshCommandError::WriteAll)?;
586             channel.send_eof().map_err(SshCommandError::SendEof)?;
587             channel.wait_eof().map_err(SshCommandError::WaitEof)?;
588 
589             // Intentionally ignore these results here as their failure
590             // does not precipitate a repeat
591             let _ = channel.close();
592             let _ = channel.wait_close();
593 
594             Ok(())
595         })() {
596             Ok(_) => break,
597             Err(e) => {
598                 counter += 1;
599                 if counter >= retries {
600                     eprintln!(
601                         "\n\n==== Start scp command output (FAILED) ====\n\n\
602                          path =\"{path:?}\"\n\
603                          remote_path =\"{remote_path:?}\"\n\
604                          auth=\"{auth:#?}\"\n\
605                          ip=\"{ip}\"\n\
606                          error=\"{e:?}\"\n\
607                          \n==== End scp command outout ====\n\n"
608                     );
609 
610                     return Err(e);
611                 }
612             }
613         };
614         thread::sleep(std::time::Duration::new((timeout * counter).into(), 0));
615     }
616     Ok(())
617 }
618 
619 pub fn scp_to_guest(
620     path: &Path,
621     remote_path: &Path,
622     ip: &str,
623     retries: u8,
624     timeout: u8,
625 ) -> Result<(), SshCommandError> {
626     scp_to_guest_with_auth(
627         path,
628         remote_path,
629         &PasswordAuth {
630             username: String::from("cloud"),
631             password: String::from("cloud123"),
632         },
633         ip,
634         retries,
635         timeout,
636     )
637 }
638 
639 pub fn ssh_command_ip_with_auth(
640     command: &str,
641     auth: &PasswordAuth,
642     ip: &str,
643     retries: u8,
644     timeout: u8,
645 ) -> Result<String, SshCommandError> {
646     let mut s = String::new();
647 
648     let mut counter = 0;
649     loop {
650         match (|| -> Result<(), SshCommandError> {
651             let tcp =
652                 TcpStream::connect(format!("{ip}:22")).map_err(SshCommandError::Connection)?;
653             let mut sess = Session::new().unwrap();
654             sess.set_tcp_stream(tcp);
655             sess.handshake().map_err(SshCommandError::Handshake)?;
656 
657             sess.userauth_password(&auth.username, &auth.password)
658                 .map_err(SshCommandError::Authentication)?;
659             assert!(sess.authenticated());
660 
661             let mut channel = sess
662                 .channel_session()
663                 .map_err(SshCommandError::ChannelSession)?;
664             channel.exec(command).map_err(SshCommandError::Command)?;
665 
666             // Intentionally ignore these results here as their failure
667             // does not precipitate a repeat
668             let _ = channel.read_to_string(&mut s);
669             let _ = channel.close();
670             let _ = channel.wait_close();
671 
672             let status = channel.exit_status().map_err(SshCommandError::ExitStatus)?;
673 
674             if status != 0 {
675                 Err(SshCommandError::NonZeroExitStatus(status))
676             } else {
677                 Ok(())
678             }
679         })() {
680             Ok(_) => break,
681             Err(e) => {
682                 counter += 1;
683                 if counter >= retries {
684                     eprintln!(
685                         "\n\n==== Start ssh command output (FAILED) ====\n\n\
686                          command=\"{command}\"\n\
687                          auth=\"{auth:#?}\"\n\
688                          ip=\"{ip}\"\n\
689                          output=\"{s}\"\n\
690                          error=\"{e:?}\"\n\
691                          \n==== End ssh command outout ====\n\n"
692                     );
693 
694                     return Err(e);
695                 }
696             }
697         };
698         thread::sleep(std::time::Duration::new((timeout * counter).into(), 0));
699     }
700     Ok(s)
701 }
702 
703 pub fn ssh_command_ip(
704     command: &str,
705     ip: &str,
706     retries: u8,
707     timeout: u8,
708 ) -> Result<String, SshCommandError> {
709     ssh_command_ip_with_auth(
710         command,
711         &PasswordAuth {
712             username: String::from("cloud"),
713             password: String::from("cloud123"),
714         },
715         ip,
716         retries,
717         timeout,
718     )
719 }
720 
721 pub fn exec_host_command_status(command: &str) -> ExitStatus {
722     exec_host_command_output(command).status
723 }
724 
725 pub fn exec_host_command_output(command: &str) -> Output {
726     let output = std::process::Command::new("bash")
727         .args(["-c", command])
728         .output()
729         .unwrap_or_else(|e| panic!("Expected '{command}' to run. Error: {:?}", e));
730 
731     if !output.status.success() {
732         let stdout = String::from_utf8_lossy(&output.stdout);
733         let stderr = String::from_utf8_lossy(&output.stderr);
734         eprintln!(
735             "\n\n==== Start 'exec_host_command' failed ==== \
736             \n\n---stdout---\n{stdout}\n---stderr---{stderr} \
737             \n\n==== End 'exec_host_command' failed ====",
738         );
739     }
740 
741     output
742 }
743 
744 pub fn check_lines_count(input: &str, line_count: usize) -> bool {
745     if input.lines().count() == line_count {
746         true
747     } else {
748         eprintln!(
749             "\n\n==== Start 'check_lines_count' failed ==== \
750             \n\ninput = {input}\nline_count = {line_count} \
751             \n\n==== End 'check_lines_count' failed ====",
752         );
753 
754         false
755     }
756 }
757 
758 pub fn check_matched_lines_count(input: &str, keywords: Vec<&str>, line_count: usize) -> bool {
759     let mut matches = String::new();
760     for line in input.lines() {
761         if keywords.iter().all(|k| line.contains(k)) {
762             matches += line;
763         }
764     }
765 
766     if matches.lines().count() == line_count {
767         true
768     } else {
769         eprintln!(
770             "\n\n==== Start 'check_matched_lines_count' failed ==== \
771             \nkeywords = {keywords:?}, line_count = {line_count} \
772             \n\ninput = {input} matches = {matches} \
773             \n\n==== End 'check_matched_lines_count' failed ====",
774         );
775 
776         false
777     }
778 }
779 
780 pub const PIPE_SIZE: i32 = 32 << 20;
781 
782 static NEXT_VM_ID: Lazy<Mutex<u8>> = Lazy::new(|| Mutex::new(1));
783 
784 pub struct Guest {
785     pub tmp_dir: TempDir,
786     pub disk_config: Box<dyn DiskConfig>,
787     pub network: GuestNetworkConfig,
788 }
789 
790 // Safe to implement as we know we have no interior mutability
791 impl std::panic::RefUnwindSafe for Guest {}
792 
793 impl Guest {
794     pub fn new_from_ip_range(mut disk_config: Box<dyn DiskConfig>, class: &str, id: u8) -> Self {
795         let tmp_dir = TempDir::new_with_prefix("/tmp/ch").unwrap();
796 
797         let network = GuestNetworkConfig {
798             guest_ip: format!("{class}.{id}.2"),
799             l2_guest_ip1: format!("{class}.{id}.3"),
800             l2_guest_ip2: format!("{class}.{id}.4"),
801             l2_guest_ip3: format!("{class}.{id}.5"),
802             host_ip: format!("{class}.{id}.1"),
803             guest_mac: format!("12:34:56:78:90:{id:02x}"),
804             l2_guest_mac1: format!("de:ad:be:ef:12:{id:02x}"),
805             l2_guest_mac2: format!("de:ad:be:ef:34:{id:02x}"),
806             l2_guest_mac3: format!("de:ad:be:ef:56:{id:02x}"),
807             tcp_listener_port: DEFAULT_TCP_LISTENER_PORT + id as u16,
808         };
809 
810         disk_config.prepare_files(&tmp_dir, &network);
811 
812         Guest {
813             tmp_dir,
814             disk_config,
815             network,
816         }
817     }
818 
819     pub fn new(disk_config: Box<dyn DiskConfig>) -> Self {
820         let mut guard = NEXT_VM_ID.lock().unwrap();
821         let id = *guard;
822         *guard = id + 1;
823 
824         Self::new_from_ip_range(disk_config, "192.168", id)
825     }
826 
827     pub fn default_net_string(&self) -> String {
828         format!(
829             "tap=,mac={},ip={},mask=255.255.255.0",
830             self.network.guest_mac, self.network.host_ip
831         )
832     }
833 
834     pub fn default_net_string_w_iommu(&self) -> String {
835         format!(
836             "tap=,mac={},ip={},mask=255.255.255.0,iommu=on",
837             self.network.guest_mac, self.network.host_ip
838         )
839     }
840 
841     pub fn default_net_string_w_mtu(&self, mtu: u16) -> String {
842         format!(
843             "tap=,mac={},ip={},mask=255.255.255.0,mtu={}",
844             self.network.guest_mac, self.network.host_ip, mtu
845         )
846     }
847 
848     pub fn ssh_command(&self, command: &str) -> Result<String, SshCommandError> {
849         ssh_command_ip(
850             command,
851             &self.network.guest_ip,
852             DEFAULT_SSH_RETRIES,
853             DEFAULT_SSH_TIMEOUT,
854         )
855     }
856 
857     #[cfg(target_arch = "x86_64")]
858     pub fn ssh_command_l1(&self, command: &str) -> Result<String, SshCommandError> {
859         ssh_command_ip(
860             command,
861             &self.network.guest_ip,
862             DEFAULT_SSH_RETRIES,
863             DEFAULT_SSH_TIMEOUT,
864         )
865     }
866 
867     #[cfg(target_arch = "x86_64")]
868     pub fn ssh_command_l2_1(&self, command: &str) -> Result<String, SshCommandError> {
869         ssh_command_ip(
870             command,
871             &self.network.l2_guest_ip1,
872             DEFAULT_SSH_RETRIES,
873             DEFAULT_SSH_TIMEOUT,
874         )
875     }
876 
877     #[cfg(target_arch = "x86_64")]
878     pub fn ssh_command_l2_2(&self, command: &str) -> Result<String, SshCommandError> {
879         ssh_command_ip(
880             command,
881             &self.network.l2_guest_ip2,
882             DEFAULT_SSH_RETRIES,
883             DEFAULT_SSH_TIMEOUT,
884         )
885     }
886 
887     #[cfg(target_arch = "x86_64")]
888     pub fn ssh_command_l2_3(&self, command: &str) -> Result<String, SshCommandError> {
889         ssh_command_ip(
890             command,
891             &self.network.l2_guest_ip3,
892             DEFAULT_SSH_RETRIES,
893             DEFAULT_SSH_TIMEOUT,
894         )
895     }
896 
897     pub fn api_create_body(&self, cpu_count: u8, kernel_path: &str, kernel_cmd: &str) -> String {
898         format! {"{{\"cpus\":{{\"boot_vcpus\":{},\"max_vcpus\":{}}},\"payload\":{{\"kernel\":\"{}\",\"cmdline\": \"{}\"}},\"net\":[{{\"ip\":\"{}\", \"mask\":\"255.255.255.0\", \"mac\":\"{}\"}}], \"disks\":[{{\"path\":\"{}\"}}, {{\"path\":\"{}\"}}]}}",
899                  cpu_count,
900                  cpu_count,
901                  kernel_path,
902                  kernel_cmd,
903                  self.network.host_ip,
904                  self.network.guest_mac,
905                  self.disk_config.disk(DiskType::OperatingSystem).unwrap().as_str(),
906                  self.disk_config.disk(DiskType::CloudInit).unwrap().as_str(),
907         }
908     }
909 
910     pub fn get_cpu_count(&self) -> Result<u32, Error> {
911         self.ssh_command("grep -c processor /proc/cpuinfo")?
912             .trim()
913             .parse()
914             .map_err(Error::Parsing)
915     }
916 
917     pub fn get_total_memory(&self) -> Result<u32, Error> {
918         self.ssh_command("grep MemTotal /proc/meminfo | grep -o \"[0-9]*\"")?
919             .trim()
920             .parse()
921             .map_err(Error::Parsing)
922     }
923 
924     #[cfg(target_arch = "x86_64")]
925     pub fn get_total_memory_l2(&self) -> Result<u32, Error> {
926         self.ssh_command_l2_1("grep MemTotal /proc/meminfo | grep -o \"[0-9]*\"")?
927             .trim()
928             .parse()
929             .map_err(Error::Parsing)
930     }
931 
932     pub fn get_numa_node_memory(&self, node_id: usize) -> Result<u32, Error> {
933         self.ssh_command(
934             format!(
935                 "grep MemTotal /sys/devices/system/node/node{node_id}/meminfo \
936                         | cut -d \":\" -f 2 | grep -o \"[0-9]*\""
937             )
938             .as_str(),
939         )?
940         .trim()
941         .parse()
942         .map_err(Error::Parsing)
943     }
944 
945     pub fn wait_vm_boot(&self, custom_timeout: Option<i32>) -> Result<(), Error> {
946         self.network
947             .wait_vm_boot(custom_timeout)
948             .map_err(Error::WaitForBoot)
949     }
950 
951     pub fn check_numa_node_cpus(&self, node_id: usize, cpus: Vec<usize>) -> Result<(), Error> {
952         for cpu in cpus.iter() {
953             let cmd = format!("[ -d \"/sys/devices/system/node/node{node_id}/cpu{cpu}\" ]");
954             self.ssh_command(cmd.as_str())?;
955         }
956 
957         Ok(())
958     }
959 
960     pub fn check_numa_node_distances(
961         &self,
962         node_id: usize,
963         distances: &str,
964     ) -> Result<bool, Error> {
965         let cmd = format!("cat /sys/devices/system/node/node{node_id}/distance");
966         if self.ssh_command(cmd.as_str())?.trim() == distances {
967             Ok(true)
968         } else {
969             Ok(false)
970         }
971     }
972 
973     pub fn check_numa_common(
974         &self,
975         mem_ref: Option<&[u32]>,
976         node_ref: Option<&[Vec<usize>]>,
977         distance_ref: Option<&[&str]>,
978     ) {
979         if let Some(mem_ref) = mem_ref {
980             // Check each NUMA node has been assigned the right amount of
981             // memory.
982             for (i, &m) in mem_ref.iter().enumerate() {
983                 assert!(self.get_numa_node_memory(i).unwrap_or_default() > m);
984             }
985         }
986 
987         if let Some(node_ref) = node_ref {
988             // Check each NUMA node has been assigned the right CPUs set.
989             for (i, n) in node_ref.iter().enumerate() {
990                 self.check_numa_node_cpus(i, n.clone()).unwrap();
991             }
992         }
993 
994         if let Some(distance_ref) = distance_ref {
995             // Check each NUMA node has been assigned the right distances.
996             for (i, &d) in distance_ref.iter().enumerate() {
997                 assert!(self.check_numa_node_distances(i, d).unwrap());
998             }
999         }
1000     }
1001 
1002     #[cfg(target_arch = "x86_64")]
1003     pub fn check_sgx_support(&self) -> Result<(), Error> {
1004         self.ssh_command(
1005             "cpuid -l 0x7 -s 0 | tr -s [:space:] | grep -q 'SGX: \
1006                     Software Guard Extensions supported = true'",
1007         )?;
1008         self.ssh_command(
1009             "cpuid -l 0x7 -s 0 | tr -s [:space:] | grep -q 'SGX_LC: \
1010                     SGX launch config supported = true'",
1011         )?;
1012         self.ssh_command(
1013             "cpuid -l 0x12 -s 0 | tr -s [:space:] | grep -q 'SGX1 \
1014                     supported = true'",
1015         )?;
1016 
1017         Ok(())
1018     }
1019 
1020     pub fn get_pci_bridge_class(&self) -> Result<String, Error> {
1021         Ok(self
1022             .ssh_command("cat /sys/bus/pci/devices/0000:00:00.0/class")?
1023             .trim()
1024             .to_string())
1025     }
1026 
1027     pub fn get_pci_device_ids(&self) -> Result<String, Error> {
1028         Ok(self
1029             .ssh_command("cat /sys/bus/pci/devices/*/device")?
1030             .trim()
1031             .to_string())
1032     }
1033 
1034     pub fn get_pci_vendor_ids(&self) -> Result<String, Error> {
1035         Ok(self
1036             .ssh_command("cat /sys/bus/pci/devices/*/vendor")?
1037             .trim()
1038             .to_string())
1039     }
1040 
1041     pub fn does_device_vendor_pair_match(
1042         &self,
1043         device_id: &str,
1044         vendor_id: &str,
1045     ) -> Result<bool, Error> {
1046         // We are checking if console device's device id and vendor id pair matches
1047         let devices = self.get_pci_device_ids()?;
1048         let devices: Vec<&str> = devices.split('\n').collect();
1049         let vendors = self.get_pci_vendor_ids()?;
1050         let vendors: Vec<&str> = vendors.split('\n').collect();
1051 
1052         for (index, d_id) in devices.iter().enumerate() {
1053             if *d_id == device_id {
1054                 if let Some(v_id) = vendors.get(index) {
1055                     if *v_id == vendor_id {
1056                         return Ok(true);
1057                     }
1058                 }
1059             }
1060         }
1061 
1062         Ok(false)
1063     }
1064 
1065     pub fn check_vsock(&self, socket: &str) {
1066         // Listen from guest on vsock CID=3 PORT=16
1067         // SOCKET-LISTEN:<domain>:<protocol>:<local-address>
1068         let guest_ip = self.network.guest_ip.clone();
1069         let listen_socat = thread::spawn(move || {
1070             ssh_command_ip("sudo socat - SOCKET-LISTEN:40:0:x00x00x10x00x00x00x03x00x00x00x00x00x00x00 > vsock_log", &guest_ip, DEFAULT_SSH_RETRIES, DEFAULT_SSH_TIMEOUT).unwrap();
1071         });
1072 
1073         // Make sure socat is listening, which might take a few second on slow systems
1074         thread::sleep(std::time::Duration::new(10, 0));
1075 
1076         // Write something to vsock from the host
1077         assert!(exec_host_command_status(&format!(
1078             "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{socket}"
1079         ))
1080         .success());
1081 
1082         // Wait for the thread to terminate.
1083         listen_socat.join().unwrap();
1084 
1085         assert_eq!(
1086             self.ssh_command("cat vsock_log").unwrap().trim(),
1087             "HelloWorld!"
1088         );
1089     }
1090 
1091     #[cfg(target_arch = "x86_64")]
1092     pub fn check_nvidia_gpu(&self) {
1093         assert!(self.ssh_command("nvidia-smi").unwrap().contains("Tesla T4"));
1094     }
1095 
1096     pub fn reboot_linux(&self, current_reboot_count: u32, custom_timeout: Option<i32>) {
1097         let list_boots_cmd = "sudo last | grep -c reboot";
1098         let boot_count = self
1099             .ssh_command(list_boots_cmd)
1100             .unwrap()
1101             .trim()
1102             .parse::<u32>()
1103             .unwrap_or_default();
1104 
1105         assert_eq!(boot_count, current_reboot_count + 1);
1106         self.ssh_command("sudo reboot").unwrap();
1107 
1108         self.wait_vm_boot(custom_timeout).unwrap();
1109         let boot_count = self
1110             .ssh_command(list_boots_cmd)
1111             .unwrap()
1112             .trim()
1113             .parse::<u32>()
1114             .unwrap_or_default();
1115         assert_eq!(boot_count, current_reboot_count + 2);
1116     }
1117 
1118     pub fn enable_memory_hotplug(&self) {
1119         self.ssh_command("echo online | sudo tee /sys/devices/system/memory/auto_online_blocks")
1120             .unwrap();
1121     }
1122 
1123     pub fn check_devices_common(
1124         &self,
1125         socket: Option<&String>,
1126         console_text: Option<&String>,
1127         pmem_path: Option<&String>,
1128     ) {
1129         // Check block devices are readable
1130         self.ssh_command("sudo dd if=/dev/vda of=/dev/null bs=1M iflag=direct count=1024")
1131             .unwrap();
1132         self.ssh_command("sudo dd if=/dev/vdb of=/dev/null bs=1M iflag=direct count=8")
1133             .unwrap();
1134         // Check if the rng device is readable
1135         self.ssh_command("sudo head -c 1000 /dev/hwrng > /dev/null")
1136             .unwrap();
1137         // Check vsock
1138         if let Some(socket) = socket {
1139             self.check_vsock(socket.as_str());
1140         }
1141         // Check if the console is usable
1142         if let Some(console_text) = console_text {
1143             let console_cmd = format!("echo {console_text} | sudo tee /dev/hvc0");
1144             self.ssh_command(&console_cmd).unwrap();
1145         }
1146         // The net device is 'automatically' exercised through the above 'ssh' commands
1147 
1148         // Check if the pmem device is usable
1149         if let Some(pmem_path) = pmem_path {
1150             assert_eq!(
1151                 self.ssh_command(&format!("ls {pmem_path}")).unwrap().trim(),
1152                 pmem_path
1153             );
1154             assert_eq!(
1155                 self.ssh_command(&format!("sudo mount {pmem_path} /mnt"))
1156                     .unwrap(),
1157                 ""
1158             );
1159             assert_eq!(self.ssh_command("ls /mnt").unwrap(), "lost+found\n");
1160             self.ssh_command("echo test123 | sudo tee /mnt/test")
1161                 .unwrap();
1162             assert_eq!(self.ssh_command("sudo umount /mnt").unwrap(), "");
1163             assert_eq!(self.ssh_command("ls /mnt").unwrap(), "");
1164 
1165             assert_eq!(
1166                 self.ssh_command(&format!("sudo mount {pmem_path} /mnt"))
1167                     .unwrap(),
1168                 ""
1169             );
1170             assert_eq!(
1171                 self.ssh_command("sudo cat /mnt/test || true")
1172                     .unwrap()
1173                     .trim(),
1174                 "test123"
1175             );
1176             self.ssh_command("sudo rm /mnt/test").unwrap();
1177             assert_eq!(self.ssh_command("sudo umount /mnt").unwrap(), "");
1178         }
1179     }
1180 }
1181 
1182 pub enum VerbosityLevel {
1183     Warn,
1184     Info,
1185     Debug,
1186 }
1187 
1188 impl Default for VerbosityLevel {
1189     fn default() -> Self {
1190         Self::Warn
1191     }
1192 }
1193 
1194 impl ToString for VerbosityLevel {
1195     fn to_string(&self) -> String {
1196         use VerbosityLevel::*;
1197         match self {
1198             Warn => "".to_string(),
1199             Info => "-v".to_string(),
1200             Debug => "-vv".to_string(),
1201         }
1202     }
1203 }
1204 
1205 pub struct GuestCommand<'a> {
1206     command: Command,
1207     guest: &'a Guest,
1208     capture_output: bool,
1209     print_cmd: bool,
1210     verbosity: VerbosityLevel,
1211 }
1212 
1213 impl<'a> GuestCommand<'a> {
1214     pub fn new(guest: &'a Guest) -> Self {
1215         Self::new_with_binary_path(guest, &clh_command("cloud-hypervisor"))
1216     }
1217 
1218     pub fn new_with_binary_path(guest: &'a Guest, binary_path: &str) -> Self {
1219         Self {
1220             command: Command::new(binary_path),
1221             guest,
1222             capture_output: false,
1223             print_cmd: true,
1224             verbosity: VerbosityLevel::Info,
1225         }
1226     }
1227 
1228     pub fn verbosity(&mut self, verbosity: VerbosityLevel) -> &mut Self {
1229         self.verbosity = verbosity;
1230         self
1231     }
1232 
1233     pub fn capture_output(&mut self) -> &mut Self {
1234         self.capture_output = true;
1235         self
1236     }
1237 
1238     pub fn set_print_cmd(&mut self, print_cmd: bool) -> &mut Self {
1239         self.print_cmd = print_cmd;
1240         self
1241     }
1242 
1243     pub fn spawn(&mut self) -> io::Result<Child> {
1244         use VerbosityLevel::*;
1245         match &self.verbosity {
1246             Warn => {}
1247             Info => {
1248                 self.command.arg("-v");
1249             }
1250             Debug => {
1251                 self.command.args(["-vv"]);
1252             }
1253         };
1254 
1255         if self.print_cmd {
1256             println!(
1257                 "\n\n==== Start cloud-hypervisor command-line ====\n\n\
1258                      {:?}\n\
1259                      \n==== End cloud-hypervisor command-line ====\n\n",
1260                 self.command
1261             );
1262         }
1263 
1264         if self.capture_output {
1265             let child = self
1266                 .command
1267                 .stderr(Stdio::piped())
1268                 .stdout(Stdio::piped())
1269                 .spawn()
1270                 .unwrap();
1271 
1272             let fd = child.stdout.as_ref().unwrap().as_raw_fd();
1273             let pipesize = unsafe { libc::fcntl(fd, libc::F_SETPIPE_SZ, PIPE_SIZE) };
1274             if pipesize == -1 {
1275                 return Err(io::Error::last_os_error());
1276             }
1277             let fd = child.stderr.as_ref().unwrap().as_raw_fd();
1278             let pipesize1 = unsafe { libc::fcntl(fd, libc::F_SETPIPE_SZ, PIPE_SIZE) };
1279             if pipesize1 == -1 {
1280                 return Err(io::Error::last_os_error());
1281             }
1282 
1283             if pipesize >= PIPE_SIZE && pipesize1 >= PIPE_SIZE {
1284                 Ok(child)
1285             } else {
1286                 Err(std::io::Error::new(
1287                     std::io::ErrorKind::Other,
1288                     format!(
1289                         "resizing pipe w/ 'fnctl' failed: stdout pipesize {pipesize}, stderr pipesize {pipesize1}"
1290                     ),
1291                 ))
1292             }
1293         } else {
1294             self.command.spawn()
1295         }
1296     }
1297 
1298     pub fn args<I, S>(&mut self, args: I) -> &mut Self
1299     where
1300         I: IntoIterator<Item = S>,
1301         S: AsRef<OsStr>,
1302     {
1303         self.command.args(args);
1304         self
1305     }
1306 
1307     pub fn default_disks(&mut self) -> &mut Self {
1308         if self.guest.disk_config.disk(DiskType::CloudInit).is_some() {
1309             self.args([
1310                 "--disk",
1311                 format!(
1312                     "path={}",
1313                     self.guest
1314                         .disk_config
1315                         .disk(DiskType::OperatingSystem)
1316                         .unwrap()
1317                 )
1318                 .as_str(),
1319                 format!(
1320                     "path={}",
1321                     self.guest.disk_config.disk(DiskType::CloudInit).unwrap()
1322                 )
1323                 .as_str(),
1324             ])
1325         } else {
1326             self.args([
1327                 "--disk",
1328                 format!(
1329                     "path={}",
1330                     self.guest
1331                         .disk_config
1332                         .disk(DiskType::OperatingSystem)
1333                         .unwrap()
1334                 )
1335                 .as_str(),
1336             ])
1337         }
1338     }
1339 
1340     pub fn default_net(&mut self) -> &mut Self {
1341         self.args(["--net", self.guest.default_net_string().as_str()])
1342     }
1343 }
1344 
1345 pub fn clh_command(cmd: &str) -> String {
1346     env::var("BUILD_TARGET").map_or(
1347         format!("target/x86_64-unknown-linux-gnu/release/{cmd}"),
1348         |target| format!("target/{target}/release/{cmd}"),
1349     )
1350 }
1351 
1352 pub fn parse_iperf3_output(output: &[u8], sender: bool, bandwidth: bool) -> Result<f64, Error> {
1353     std::panic::catch_unwind(|| {
1354         let s = String::from_utf8_lossy(output);
1355         let v: Value = serde_json::from_str(&s).expect("'iperf3' parse error: invalid json output");
1356 
1357         if bandwidth {
1358             if sender {
1359                 v["end"]["sum_sent"]["bits_per_second"]
1360                     .as_f64()
1361                     .expect("'iperf3' parse error: missing entry 'end.sum_sent.bits_per_second'")
1362             } else {
1363                 v["end"]["sum_received"]["bits_per_second"].as_f64().expect(
1364                     "'iperf3' parse error: missing entry 'end.sum_received.bits_per_second'",
1365                 )
1366             }
1367         } else {
1368             // iperf does not distinguish sent vs received in this case.
1369 
1370             let lost_packets = v["end"]["sum"]["lost_packets"]
1371                 .as_f64()
1372                 .expect("'iperf3' parse error: missing entry 'end.sum.lost_packets'");
1373             let packets = v["end"]["sum"]["packets"]
1374                 .as_f64()
1375                 .expect("'iperf3' parse error: missing entry 'end.sum.packets'");
1376             let seconds = v["end"]["sum"]["seconds"]
1377                 .as_f64()
1378                 .expect("'iperf3' parse error: missing entry 'end.sum.seconds'");
1379 
1380             (packets - lost_packets) / seconds
1381         }
1382     })
1383     .map_err(|_| {
1384         eprintln!(
1385             "==== Start iperf3 output ===\n\n{}\n\n=== End iperf3 output ===\n\n",
1386             String::from_utf8_lossy(output)
1387         );
1388         Error::Iperf3Parse
1389     })
1390 }
1391 
1392 #[derive(Clone)]
1393 pub enum FioOps {
1394     Read,
1395     RandomRead,
1396     Write,
1397     RandomWrite,
1398     ReadWrite,
1399     RandRW,
1400 }
1401 
1402 impl fmt::Display for FioOps {
1403     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1404         match self {
1405             FioOps::Read => write!(f, "read"),
1406             FioOps::RandomRead => write!(f, "randread"),
1407             FioOps::Write => write!(f, "write"),
1408             FioOps::RandomWrite => write!(f, "randwrite"),
1409             FioOps::ReadWrite => write!(f, "rw"),
1410             FioOps::RandRW => write!(f, "randrw"),
1411         }
1412     }
1413 }
1414 
1415 pub fn parse_fio_output(output: &str, fio_ops: &FioOps, num_jobs: u32) -> Result<f64, Error> {
1416     std::panic::catch_unwind(|| {
1417         let v: Value =
1418             serde_json::from_str(output).expect("'fio' parse error: invalid json output");
1419         let jobs = v["jobs"]
1420             .as_array()
1421             .expect("'fio' parse error: missing entry 'jobs'");
1422         assert_eq!(
1423             jobs.len(),
1424             num_jobs as usize,
1425             "'fio' parse error: Unexpected number of 'fio' jobs."
1426         );
1427 
1428         let (read, write) = match fio_ops {
1429             FioOps::Read | FioOps::RandomRead => (true, false),
1430             FioOps::Write | FioOps::RandomWrite => (false, true),
1431             FioOps::ReadWrite | FioOps::RandRW => (true, true),
1432         };
1433 
1434         let mut total_bps = 0_f64;
1435         for j in jobs {
1436             if read {
1437                 let bytes = j["read"]["io_bytes"]
1438                     .as_u64()
1439                     .expect("'fio' parse error: missing entry 'read.io_bytes'");
1440                 let runtime = j["read"]["runtime"]
1441                     .as_u64()
1442                     .expect("'fio' parse error: missing entry 'read.runtime'")
1443                     as f64
1444                     / 1000_f64;
1445                 total_bps += bytes as f64 / runtime;
1446             }
1447             if write {
1448                 let bytes = j["write"]["io_bytes"]
1449                     .as_u64()
1450                     .expect("'fio' parse error: missing entry 'write.io_bytes'");
1451                 let runtime = j["write"]["runtime"]
1452                     .as_u64()
1453                     .expect("'fio' parse error: missing entry 'write.runtime'")
1454                     as f64
1455                     / 1000_f64;
1456                 total_bps += bytes as f64 / runtime;
1457             }
1458         }
1459 
1460         total_bps
1461     })
1462     .map_err(|_| {
1463         eprintln!("=== Start Fio output ===\n\n{output}\n\n=== End Fio output ===\n\n");
1464         Error::FioOutputParse
1465     })
1466 }
1467 
1468 pub fn parse_fio_output_iops(output: &str, fio_ops: &FioOps, num_jobs: u32) -> Result<f64, Error> {
1469     std::panic::catch_unwind(|| {
1470         let v: Value =
1471             serde_json::from_str(output).expect("'fio' parse error: invalid json output");
1472         let jobs = v["jobs"]
1473             .as_array()
1474             .expect("'fio' parse error: missing entry 'jobs'");
1475         assert_eq!(
1476             jobs.len(),
1477             num_jobs as usize,
1478             "'fio' parse error: Unexpected number of 'fio' jobs."
1479         );
1480 
1481         let (read, write) = match fio_ops {
1482             FioOps::Read | FioOps::RandomRead => (true, false),
1483             FioOps::Write | FioOps::RandomWrite => (false, true),
1484             FioOps::ReadWrite | FioOps::RandRW => (true, true),
1485         };
1486 
1487         let mut total_iops = 0_f64;
1488         for j in jobs {
1489             if read {
1490                 let ios = j["read"]["total_ios"]
1491                     .as_u64()
1492                     .expect("'fio' parse error: missing entry 'read.total_ios'");
1493                 let runtime = j["read"]["runtime"]
1494                     .as_u64()
1495                     .expect("'fio' parse error: missing entry 'read.runtime'")
1496                     as f64
1497                     / 1000_f64;
1498                 total_iops += ios as f64 / runtime;
1499             }
1500             if write {
1501                 let ios = j["write"]["total_ios"]
1502                     .as_u64()
1503                     .expect("'fio' parse error: missing entry 'write.total_ios'");
1504                 let runtime = j["write"]["runtime"]
1505                     .as_u64()
1506                     .expect("'fio' parse error: missing entry 'write.runtime'")
1507                     as f64
1508                     / 1000_f64;
1509                 total_iops += ios as f64 / runtime;
1510             }
1511         }
1512 
1513         total_iops
1514     })
1515     .map_err(|_| {
1516         eprintln!("=== Start Fio output ===\n\n{output}\n\n=== End Fio output ===\n\n");
1517         Error::FioOutputParse
1518     })
1519 }
1520 
1521 // Wait the child process for a given timeout
1522 fn child_wait_timeout(child: &mut Child, timeout: u64) -> Result<(), WaitTimeoutError> {
1523     match child.wait_timeout(Duration::from_secs(timeout)) {
1524         Err(e) => {
1525             return Err(WaitTimeoutError::General(e));
1526         }
1527         Ok(s) => match s {
1528             None => {
1529                 return Err(WaitTimeoutError::Timedout);
1530             }
1531             Some(s) => {
1532                 if !s.success() {
1533                     return Err(WaitTimeoutError::ExitStatus);
1534                 }
1535             }
1536         },
1537     }
1538 
1539     Ok(())
1540 }
1541 
1542 pub fn measure_virtio_net_throughput(
1543     test_timeout: u32,
1544     queue_pairs: u32,
1545     guest: &Guest,
1546     receive: bool,
1547     bandwidth: bool,
1548 ) -> Result<f64, Error> {
1549     let default_port = 5201;
1550 
1551     // 1. start the iperf3 server on the guest
1552     for n in 0..queue_pairs {
1553         guest.ssh_command(&format!("iperf3 -s -p {} -D", default_port + n))?;
1554     }
1555 
1556     thread::sleep(Duration::new(1, 0));
1557 
1558     // 2. start the iperf3 client on host to measure RX through-put
1559     let mut clients = Vec::new();
1560     for n in 0..queue_pairs {
1561         let mut cmd = Command::new("iperf3");
1562         cmd.args([
1563             "-J", // Output in JSON format
1564             "-c",
1565             &guest.network.guest_ip,
1566             "-p",
1567             &format!("{}", default_port + n),
1568             "-t",
1569             &format!("{test_timeout}"),
1570             "-i",
1571             "0",
1572         ]);
1573         // For measuring the guest transmit throughput (as a sender),
1574         // use reverse mode of the iperf3 client on the host
1575         if !receive {
1576             cmd.args(["-R"]);
1577         }
1578         // Use UDP stream to measure packets per second. The bitrate is set to
1579         // 1T to make sure it saturates the link.
1580         if !bandwidth {
1581             cmd.args(["-u", "-b", "1T"]);
1582         }
1583         let client = cmd
1584             .stderr(Stdio::piped())
1585             .stdout(Stdio::piped())
1586             .spawn()
1587             .map_err(Error::Spawn)?;
1588 
1589         clients.push(client);
1590     }
1591 
1592     let mut err: Option<Error> = None;
1593     let mut results = Vec::new();
1594     let mut failed = false;
1595     for c in clients {
1596         let mut c = c;
1597         if let Err(e) = child_wait_timeout(&mut c, test_timeout as u64 + 5) {
1598             err = Some(Error::WaitTimeout(e));
1599             failed = true;
1600         }
1601 
1602         if !failed {
1603             // Safe to unwrap as we know the child has terminated succesffully
1604             let output = c.wait_with_output().unwrap();
1605             results.push(parse_iperf3_output(&output.stdout, receive, bandwidth)?);
1606         } else {
1607             let _ = c.kill();
1608             let output = c.wait_with_output().unwrap();
1609             println!(
1610                 "=============== Client output [Error] ===============\n\n{}\n\n===========end============\n\n",
1611                 String::from_utf8_lossy(&output.stdout)
1612             );
1613         }
1614     }
1615 
1616     if let Some(e) = err {
1617         Err(e)
1618     } else {
1619         Ok(results.iter().sum())
1620     }
1621 }
1622 
1623 pub fn parse_ethr_latency_output(output: &[u8]) -> Result<Vec<f64>, Error> {
1624     std::panic::catch_unwind(|| {
1625         let s = String::from_utf8_lossy(output);
1626         let mut latency = Vec::new();
1627         for l in s.lines() {
1628             let v: Value = serde_json::from_str(l).expect("'ethr' parse error: invalid json line");
1629             // Skip header/summary lines
1630             if let Some(avg) = v["Avg"].as_str() {
1631                 // Assume the latency unit is always "us"
1632                 latency.push(
1633                     avg.split("us").collect::<Vec<&str>>()[0]
1634                         .parse::<f64>()
1635                         .expect("'ethr' parse error: invalid 'Avg' entry"),
1636                 );
1637             }
1638         }
1639 
1640         assert!(
1641             !latency.is_empty(),
1642             "'ethr' parse error: no valid latency data found"
1643         );
1644 
1645         latency
1646     })
1647     .map_err(|_| {
1648         eprintln!(
1649             "=== Start ethr output ===\n\n{}\n\n=== End ethr output ===\n\n",
1650             String::from_utf8_lossy(output)
1651         );
1652         Error::EthrLogParse
1653     })
1654 }
1655 
1656 pub fn measure_virtio_net_latency(guest: &Guest, test_timeout: u32) -> Result<Vec<f64>, Error> {
1657     // copy the 'ethr' tool to the guest image
1658     let ethr_path = "/usr/local/bin/ethr";
1659     let ethr_remote_path = "/tmp/ethr";
1660     scp_to_guest(
1661         Path::new(ethr_path),
1662         Path::new(ethr_remote_path),
1663         &guest.network.guest_ip,
1664         //DEFAULT_SSH_RETRIES,
1665         1,
1666         DEFAULT_SSH_TIMEOUT,
1667     )?;
1668 
1669     // Start the ethr server on the guest
1670     guest.ssh_command(&format!("{ethr_remote_path} -s &> /dev/null &"))?;
1671 
1672     thread::sleep(Duration::new(10, 0));
1673 
1674     // Start the ethr client on the host
1675     let log_file = guest
1676         .tmp_dir
1677         .as_path()
1678         .join("ethr.client.log")
1679         .to_str()
1680         .unwrap()
1681         .to_string();
1682     let mut c = Command::new(ethr_path)
1683         .args([
1684             "-c",
1685             &guest.network.guest_ip,
1686             "-t",
1687             "l",
1688             "-o",
1689             &log_file, // file output is JSON format
1690             "-d",
1691             &format!("{test_timeout}s"),
1692         ])
1693         .stderr(Stdio::piped())
1694         .stdout(Stdio::piped())
1695         .spawn()
1696         .map_err(Error::Spawn)?;
1697 
1698     if let Err(e) = child_wait_timeout(&mut c, test_timeout as u64 + 5).map_err(Error::WaitTimeout)
1699     {
1700         let _ = c.kill();
1701         return Err(e);
1702     }
1703 
1704     // Parse the ethr latency test output
1705     let content = fs::read(log_file).map_err(Error::EthrLogFile)?;
1706     parse_ethr_latency_output(&content)
1707 }
1708