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