xref: /cloud-hypervisor/test_infra/src/lib.rs (revision 5a9dd7489cdd27ad83b278ae94609214350b07b1)
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 = vec![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) ====\n\n\
151                  duration =\"{duration:?}, timeout = {timeout}s\"\n\
152                  listen_addr=\"{listen_addr}\"\n\
153                  expected_guest_addr=\"{expected_guest_addr}\"\n\
154                  message=\"{s}\"\n\
155                  error=\"{e:?}\"\n\
156                  \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         vec!["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         vec!["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     std::process::Command::new("bash")
723         .args(["-c", command])
724         .status()
725         .unwrap_or_else(|_| panic!("Expected '{command}' to run"))
726 }
727 
728 pub fn exec_host_command_output(command: &str) -> Output {
729     std::process::Command::new("bash")
730         .args(["-c", command])
731         .output()
732         .unwrap_or_else(|_| panic!("Expected '{command}' to run"))
733 }
734 
735 pub const PIPE_SIZE: i32 = 32 << 20;
736 
737 static NEXT_VM_ID: Lazy<Mutex<u8>> = Lazy::new(|| Mutex::new(1));
738 
739 pub struct Guest {
740     pub tmp_dir: TempDir,
741     pub disk_config: Box<dyn DiskConfig>,
742     pub network: GuestNetworkConfig,
743 }
744 
745 // Safe to implement as we know we have no interior mutability
746 impl std::panic::RefUnwindSafe for Guest {}
747 
748 impl Guest {
749     pub fn new_from_ip_range(mut disk_config: Box<dyn DiskConfig>, class: &str, id: u8) -> Self {
750         let tmp_dir = TempDir::new_with_prefix("/tmp/ch").unwrap();
751 
752         let network = GuestNetworkConfig {
753             guest_ip: format!("{class}.{id}.2"),
754             l2_guest_ip1: format!("{class}.{id}.3"),
755             l2_guest_ip2: format!("{class}.{id}.4"),
756             l2_guest_ip3: format!("{class}.{id}.5"),
757             host_ip: format!("{class}.{id}.1"),
758             guest_mac: format!("12:34:56:78:90:{id:02x}"),
759             l2_guest_mac1: format!("de:ad:be:ef:12:{id:02x}"),
760             l2_guest_mac2: format!("de:ad:be:ef:34:{id:02x}"),
761             l2_guest_mac3: format!("de:ad:be:ef:56:{id:02x}"),
762             tcp_listener_port: DEFAULT_TCP_LISTENER_PORT + id as u16,
763         };
764 
765         disk_config.prepare_files(&tmp_dir, &network);
766 
767         Guest {
768             tmp_dir,
769             disk_config,
770             network,
771         }
772     }
773 
774     pub fn new(disk_config: Box<dyn DiskConfig>) -> Self {
775         let mut guard = NEXT_VM_ID.lock().unwrap();
776         let id = *guard;
777         *guard = id + 1;
778 
779         Self::new_from_ip_range(disk_config, "192.168", id)
780     }
781 
782     pub fn default_net_string(&self) -> String {
783         format!(
784             "tap=,mac={},ip={},mask=255.255.255.0",
785             self.network.guest_mac, self.network.host_ip
786         )
787     }
788 
789     pub fn default_net_string_w_iommu(&self) -> String {
790         format!(
791             "tap=,mac={},ip={},mask=255.255.255.0,iommu=on",
792             self.network.guest_mac, self.network.host_ip
793         )
794     }
795 
796     pub fn default_net_string_w_mtu(&self, mtu: u16) -> String {
797         format!(
798             "tap=,mac={},ip={},mask=255.255.255.0,mtu={}",
799             self.network.guest_mac, self.network.host_ip, mtu
800         )
801     }
802 
803     pub fn ssh_command(&self, command: &str) -> Result<String, SshCommandError> {
804         ssh_command_ip(
805             command,
806             &self.network.guest_ip,
807             DEFAULT_SSH_RETRIES,
808             DEFAULT_SSH_TIMEOUT,
809         )
810     }
811 
812     #[cfg(target_arch = "x86_64")]
813     pub fn ssh_command_l1(&self, command: &str) -> Result<String, SshCommandError> {
814         ssh_command_ip(
815             command,
816             &self.network.guest_ip,
817             DEFAULT_SSH_RETRIES,
818             DEFAULT_SSH_TIMEOUT,
819         )
820     }
821 
822     #[cfg(target_arch = "x86_64")]
823     pub fn ssh_command_l2_1(&self, command: &str) -> Result<String, SshCommandError> {
824         ssh_command_ip(
825             command,
826             &self.network.l2_guest_ip1,
827             DEFAULT_SSH_RETRIES,
828             DEFAULT_SSH_TIMEOUT,
829         )
830     }
831 
832     #[cfg(target_arch = "x86_64")]
833     pub fn ssh_command_l2_2(&self, command: &str) -> Result<String, SshCommandError> {
834         ssh_command_ip(
835             command,
836             &self.network.l2_guest_ip2,
837             DEFAULT_SSH_RETRIES,
838             DEFAULT_SSH_TIMEOUT,
839         )
840     }
841 
842     #[cfg(target_arch = "x86_64")]
843     pub fn ssh_command_l2_3(&self, command: &str) -> Result<String, SshCommandError> {
844         ssh_command_ip(
845             command,
846             &self.network.l2_guest_ip3,
847             DEFAULT_SSH_RETRIES,
848             DEFAULT_SSH_TIMEOUT,
849         )
850     }
851 
852     pub fn api_create_body(&self, cpu_count: u8, kernel_path: &str, kernel_cmd: &str) -> String {
853         format! {"{{\"cpus\":{{\"boot_vcpus\":{},\"max_vcpus\":{}}},\"payload\":{{\"kernel\":\"{}\",\"cmdline\": \"{}\"}},\"net\":[{{\"ip\":\"{}\", \"mask\":\"255.255.255.0\", \"mac\":\"{}\"}}], \"disks\":[{{\"path\":\"{}\"}}, {{\"path\":\"{}\"}}]}}",
854                  cpu_count,
855                  cpu_count,
856                  kernel_path,
857                  kernel_cmd,
858                  self.network.host_ip,
859                  self.network.guest_mac,
860                  self.disk_config.disk(DiskType::OperatingSystem).unwrap().as_str(),
861                  self.disk_config.disk(DiskType::CloudInit).unwrap().as_str(),
862         }
863     }
864 
865     pub fn get_cpu_count(&self) -> Result<u32, Error> {
866         self.ssh_command("grep -c processor /proc/cpuinfo")?
867             .trim()
868             .parse()
869             .map_err(Error::Parsing)
870     }
871 
872     pub fn get_total_memory(&self) -> Result<u32, Error> {
873         self.ssh_command("grep MemTotal /proc/meminfo | grep -o \"[0-9]*\"")?
874             .trim()
875             .parse()
876             .map_err(Error::Parsing)
877     }
878 
879     #[cfg(target_arch = "x86_64")]
880     pub fn get_total_memory_l2(&self) -> Result<u32, Error> {
881         self.ssh_command_l2_1("grep MemTotal /proc/meminfo | grep -o \"[0-9]*\"")?
882             .trim()
883             .parse()
884             .map_err(Error::Parsing)
885     }
886 
887     pub fn get_numa_node_memory(&self, node_id: usize) -> Result<u32, Error> {
888         self.ssh_command(
889             format!(
890                 "grep MemTotal /sys/devices/system/node/node{node_id}/meminfo \
891                         | cut -d \":\" -f 2 | grep -o \"[0-9]*\""
892             )
893             .as_str(),
894         )?
895         .trim()
896         .parse()
897         .map_err(Error::Parsing)
898     }
899 
900     pub fn wait_vm_boot(&self, custom_timeout: Option<i32>) -> Result<(), Error> {
901         self.network
902             .wait_vm_boot(custom_timeout)
903             .map_err(Error::WaitForBoot)
904     }
905 
906     pub fn check_numa_node_cpus(&self, node_id: usize, cpus: Vec<usize>) -> Result<(), Error> {
907         for cpu in cpus.iter() {
908             let cmd = format!("[ -d \"/sys/devices/system/node/node{node_id}/cpu{cpu}\" ]");
909             self.ssh_command(cmd.as_str())?;
910         }
911 
912         Ok(())
913     }
914 
915     pub fn check_numa_node_distances(
916         &self,
917         node_id: usize,
918         distances: &str,
919     ) -> Result<bool, Error> {
920         let cmd = format!("cat /sys/devices/system/node/node{node_id}/distance");
921         if self.ssh_command(cmd.as_str())?.trim() == distances {
922             Ok(true)
923         } else {
924             Ok(false)
925         }
926     }
927 
928     pub fn check_numa_common(
929         &self,
930         mem_ref: Option<&[u32]>,
931         node_ref: Option<&[Vec<usize>]>,
932         distance_ref: Option<&[&str]>,
933     ) {
934         if let Some(mem_ref) = mem_ref {
935             // Check each NUMA node has been assigned the right amount of
936             // memory.
937             for (i, &m) in mem_ref.iter().enumerate() {
938                 assert!(self.get_numa_node_memory(i).unwrap_or_default() > m);
939             }
940         }
941 
942         if let Some(node_ref) = node_ref {
943             // Check each NUMA node has been assigned the right CPUs set.
944             for (i, n) in node_ref.iter().enumerate() {
945                 self.check_numa_node_cpus(i, n.clone()).unwrap();
946             }
947         }
948 
949         if let Some(distance_ref) = distance_ref {
950             // Check each NUMA node has been assigned the right distances.
951             for (i, &d) in distance_ref.iter().enumerate() {
952                 assert!(self.check_numa_node_distances(i, d).unwrap());
953             }
954         }
955     }
956 
957     #[cfg(target_arch = "x86_64")]
958     pub fn check_sgx_support(&self) -> Result<(), Error> {
959         self.ssh_command(
960             "cpuid -l 0x7 -s 0 | tr -s [:space:] | grep -q 'SGX: \
961                     Software Guard Extensions supported = true'",
962         )?;
963         self.ssh_command(
964             "cpuid -l 0x7 -s 0 | tr -s [:space:] | grep -q 'SGX_LC: \
965                     SGX launch config supported = true'",
966         )?;
967         self.ssh_command(
968             "cpuid -l 0x12 -s 0 | tr -s [:space:] | grep -q 'SGX1 \
969                     supported = true'",
970         )?;
971 
972         Ok(())
973     }
974 
975     pub fn get_pci_bridge_class(&self) -> Result<String, Error> {
976         Ok(self
977             .ssh_command("cat /sys/bus/pci/devices/0000:00:00.0/class")?
978             .trim()
979             .to_string())
980     }
981 
982     pub fn get_pci_device_ids(&self) -> Result<String, Error> {
983         Ok(self
984             .ssh_command("cat /sys/bus/pci/devices/*/device")?
985             .trim()
986             .to_string())
987     }
988 
989     pub fn get_pci_vendor_ids(&self) -> Result<String, Error> {
990         Ok(self
991             .ssh_command("cat /sys/bus/pci/devices/*/vendor")?
992             .trim()
993             .to_string())
994     }
995 
996     pub fn does_device_vendor_pair_match(
997         &self,
998         device_id: &str,
999         vendor_id: &str,
1000     ) -> Result<bool, Error> {
1001         // We are checking if console device's device id and vendor id pair matches
1002         let devices = self.get_pci_device_ids()?;
1003         let devices: Vec<&str> = devices.split('\n').collect();
1004         let vendors = self.get_pci_vendor_ids()?;
1005         let vendors: Vec<&str> = vendors.split('\n').collect();
1006 
1007         for (index, d_id) in devices.iter().enumerate() {
1008             if *d_id == device_id {
1009                 if let Some(v_id) = vendors.get(index) {
1010                     if *v_id == vendor_id {
1011                         return Ok(true);
1012                     }
1013                 }
1014             }
1015         }
1016 
1017         Ok(false)
1018     }
1019 
1020     pub fn check_vsock(&self, socket: &str) {
1021         // Listen from guest on vsock CID=3 PORT=16
1022         // SOCKET-LISTEN:<domain>:<protocol>:<local-address>
1023         let guest_ip = self.network.guest_ip.clone();
1024         let listen_socat = thread::spawn(move || {
1025             ssh_command_ip("sudo socat - SOCKET-LISTEN:40:0:x00x00x10x00x00x00x03x00x00x00x00x00x00x00 > vsock_log", &guest_ip, DEFAULT_SSH_RETRIES, DEFAULT_SSH_TIMEOUT).unwrap();
1026         });
1027 
1028         // Make sure socat is listening, which might take a few second on slow systems
1029         thread::sleep(std::time::Duration::new(10, 0));
1030 
1031         // Write something to vsock from the host
1032         assert!(exec_host_command_status(&format!(
1033             "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{socket}"
1034         ))
1035         .success());
1036 
1037         // Wait for the thread to terminate.
1038         listen_socat.join().unwrap();
1039 
1040         assert_eq!(
1041             self.ssh_command("cat vsock_log").unwrap().trim(),
1042             "HelloWorld!"
1043         );
1044     }
1045 
1046     #[cfg(target_arch = "x86_64")]
1047     pub fn check_nvidia_gpu(&self) {
1048         assert!(self.ssh_command("nvidia-smi").unwrap().contains("Tesla T4"));
1049     }
1050 
1051     pub fn reboot_linux(&self, current_reboot_count: u32, custom_timeout: Option<i32>) {
1052         let list_boots_cmd = "sudo last | grep -c reboot";
1053         let boot_count = self
1054             .ssh_command(list_boots_cmd)
1055             .unwrap()
1056             .trim()
1057             .parse::<u32>()
1058             .unwrap_or_default();
1059 
1060         assert_eq!(boot_count, current_reboot_count + 1);
1061         self.ssh_command("sudo reboot").unwrap();
1062 
1063         self.wait_vm_boot(custom_timeout).unwrap();
1064         let boot_count = self
1065             .ssh_command(list_boots_cmd)
1066             .unwrap()
1067             .trim()
1068             .parse::<u32>()
1069             .unwrap_or_default();
1070         assert_eq!(boot_count, current_reboot_count + 2);
1071     }
1072 
1073     pub fn enable_memory_hotplug(&self) {
1074         self.ssh_command("echo online | sudo tee /sys/devices/system/memory/auto_online_blocks")
1075             .unwrap();
1076     }
1077 
1078     pub fn check_devices_common(
1079         &self,
1080         socket: Option<&String>,
1081         console_text: Option<&String>,
1082         pmem_path: Option<&String>,
1083     ) {
1084         // Check block devices are readable
1085         self.ssh_command("sudo dd if=/dev/vda of=/dev/null bs=1M iflag=direct count=1024")
1086             .unwrap();
1087         self.ssh_command("sudo dd if=/dev/vdb of=/dev/null bs=1M iflag=direct count=8")
1088             .unwrap();
1089         // Check if the rng device is readable
1090         self.ssh_command("sudo head -c 1000 /dev/hwrng > /dev/null")
1091             .unwrap();
1092         // Check vsock
1093         if let Some(socket) = socket {
1094             self.check_vsock(socket.as_str());
1095         }
1096         // Check if the console is usable
1097         if let Some(console_text) = console_text {
1098             let console_cmd = format!("echo {console_text} | sudo tee /dev/hvc0");
1099             self.ssh_command(&console_cmd).unwrap();
1100         }
1101         // The net device is 'automatically' exercised through the above 'ssh' commands
1102 
1103         // Check if the pmem device is usable
1104         if let Some(pmem_path) = pmem_path {
1105             assert_eq!(
1106                 self.ssh_command(&format!("ls {pmem_path}")).unwrap().trim(),
1107                 pmem_path
1108             );
1109             assert_eq!(
1110                 self.ssh_command(&format!("sudo mount {pmem_path} /mnt"))
1111                     .unwrap(),
1112                 ""
1113             );
1114             assert_eq!(self.ssh_command("ls /mnt").unwrap(), "lost+found\n");
1115             self.ssh_command("echo test123 | sudo tee /mnt/test")
1116                 .unwrap();
1117             assert_eq!(self.ssh_command("sudo umount /mnt").unwrap(), "");
1118             assert_eq!(self.ssh_command("ls /mnt").unwrap(), "");
1119 
1120             assert_eq!(
1121                 self.ssh_command(&format!("sudo mount {pmem_path} /mnt"))
1122                     .unwrap(),
1123                 ""
1124             );
1125             assert_eq!(
1126                 self.ssh_command("sudo cat /mnt/test || true")
1127                     .unwrap()
1128                     .trim(),
1129                 "test123"
1130             );
1131             self.ssh_command("sudo rm /mnt/test").unwrap();
1132             assert_eq!(self.ssh_command("sudo umount /mnt").unwrap(), "");
1133         }
1134     }
1135 }
1136 
1137 pub enum VerbosityLevel {
1138     Warn,
1139     Info,
1140     Debug,
1141 }
1142 
1143 impl Default for VerbosityLevel {
1144     fn default() -> Self {
1145         Self::Warn
1146     }
1147 }
1148 
1149 impl ToString for VerbosityLevel {
1150     fn to_string(&self) -> String {
1151         use VerbosityLevel::*;
1152         match self {
1153             Warn => "".to_string(),
1154             Info => "-v".to_string(),
1155             Debug => "-v -v".to_string(),
1156         }
1157     }
1158 }
1159 
1160 pub struct GuestCommand<'a> {
1161     command: Command,
1162     guest: &'a Guest,
1163     capture_output: bool,
1164     print_cmd: bool,
1165     verbosity: VerbosityLevel,
1166 }
1167 
1168 impl<'a> GuestCommand<'a> {
1169     pub fn new(guest: &'a Guest) -> Self {
1170         Self::new_with_binary_path(guest, &clh_command("cloud-hypervisor"))
1171     }
1172 
1173     pub fn new_with_binary_path(guest: &'a Guest, binary_path: &str) -> Self {
1174         Self {
1175             command: Command::new(binary_path),
1176             guest,
1177             capture_output: false,
1178             print_cmd: true,
1179             verbosity: VerbosityLevel::Info,
1180         }
1181     }
1182 
1183     pub fn verbosity(&mut self, verbosity: VerbosityLevel) -> &mut Self {
1184         self.verbosity = verbosity;
1185         self
1186     }
1187 
1188     pub fn capture_output(&mut self) -> &mut Self {
1189         self.capture_output = true;
1190         self
1191     }
1192 
1193     pub fn set_print_cmd(&mut self, print_cmd: bool) -> &mut Self {
1194         self.print_cmd = print_cmd;
1195         self
1196     }
1197 
1198     pub fn spawn(&mut self) -> io::Result<Child> {
1199         use VerbosityLevel::*;
1200         match &self.verbosity {
1201             Warn => {}
1202             Info => {
1203                 self.command.arg("-v");
1204             }
1205             Debug => {
1206                 self.command.args(["-v", "-v"]);
1207             }
1208         };
1209 
1210         if self.print_cmd {
1211             println!(
1212                 "\n\n==== Start cloud-hypervisor command-line ====\n\n\
1213                      {:?}\n\
1214                      \n==== End cloud-hypervisor command-line ====\n\n",
1215                 self.command
1216             );
1217         }
1218 
1219         if self.capture_output {
1220             let child = self
1221                 .command
1222                 .stderr(Stdio::piped())
1223                 .stdout(Stdio::piped())
1224                 .spawn()
1225                 .unwrap();
1226 
1227             let fd = child.stdout.as_ref().unwrap().as_raw_fd();
1228             let pipesize = unsafe { libc::fcntl(fd, libc::F_SETPIPE_SZ, PIPE_SIZE) };
1229             if pipesize == -1 {
1230                 return Err(io::Error::last_os_error());
1231             }
1232             let fd = child.stderr.as_ref().unwrap().as_raw_fd();
1233             let pipesize1 = unsafe { libc::fcntl(fd, libc::F_SETPIPE_SZ, PIPE_SIZE) };
1234             if pipesize1 == -1 {
1235                 return Err(io::Error::last_os_error());
1236             }
1237 
1238             if pipesize >= PIPE_SIZE && pipesize1 >= PIPE_SIZE {
1239                 Ok(child)
1240             } else {
1241                 Err(std::io::Error::new(
1242                     std::io::ErrorKind::Other,
1243                     format!(
1244                         "resizing pipe w/ 'fnctl' failed: stdout pipesize {pipesize}, stderr pipesize {pipesize1}"
1245                     ),
1246                 ))
1247             }
1248         } else {
1249             self.command.spawn()
1250         }
1251     }
1252 
1253     pub fn args<I, S>(&mut self, args: I) -> &mut Self
1254     where
1255         I: IntoIterator<Item = S>,
1256         S: AsRef<OsStr>,
1257     {
1258         self.command.args(args);
1259         self
1260     }
1261 
1262     pub fn default_disks(&mut self) -> &mut Self {
1263         if self.guest.disk_config.disk(DiskType::CloudInit).is_some() {
1264             self.args([
1265                 "--disk",
1266                 format!(
1267                     "path={}",
1268                     self.guest
1269                         .disk_config
1270                         .disk(DiskType::OperatingSystem)
1271                         .unwrap()
1272                 )
1273                 .as_str(),
1274                 "--disk",
1275                 format!(
1276                     "path={}",
1277                     self.guest.disk_config.disk(DiskType::CloudInit).unwrap()
1278                 )
1279                 .as_str(),
1280             ])
1281         } else {
1282             self.args([
1283                 "--disk",
1284                 format!(
1285                     "path={}",
1286                     self.guest
1287                         .disk_config
1288                         .disk(DiskType::OperatingSystem)
1289                         .unwrap()
1290                 )
1291                 .as_str(),
1292             ])
1293         }
1294     }
1295 
1296     pub fn default_net(&mut self) -> &mut Self {
1297         self.args(["--net", self.guest.default_net_string().as_str()])
1298     }
1299 }
1300 
1301 pub fn clh_command(cmd: &str) -> String {
1302     env::var("BUILD_TARGET").map_or(
1303         format!("target/x86_64-unknown-linux-gnu/release/{cmd}"),
1304         |target| format!("target/{target}/release/{cmd}"),
1305     )
1306 }
1307 
1308 pub fn parse_iperf3_output(output: &[u8], sender: bool, bandwidth: bool) -> Result<f64, Error> {
1309     std::panic::catch_unwind(|| {
1310         let s = String::from_utf8_lossy(output);
1311         let v: Value = serde_json::from_str(&s).expect("'iperf3' parse error: invalid json output");
1312 
1313         if bandwidth {
1314             if sender {
1315                 v["end"]["sum_sent"]["bits_per_second"]
1316                     .as_f64()
1317                     .expect("'iperf3' parse error: missing entry 'end.sum_sent.bits_per_second'")
1318             } else {
1319                 v["end"]["sum_received"]["bits_per_second"].as_f64().expect(
1320                     "'iperf3' parse error: missing entry 'end.sum_received.bits_per_second'",
1321                 )
1322             }
1323         } else {
1324             // iperf does not distinguish sent vs received in this case.
1325 
1326             let lost_packets = v["end"]["sum"]["lost_packets"]
1327                 .as_f64()
1328                 .expect("'iperf3' parse error: missing entry 'end.sum.lost_packets'");
1329             let packets = v["end"]["sum"]["packets"]
1330                 .as_f64()
1331                 .expect("'iperf3' parse error: missing entry 'end.sum.packets'");
1332             let seconds = v["end"]["sum"]["seconds"]
1333                 .as_f64()
1334                 .expect("'iperf3' parse error: missing entry 'end.sum.seconds'");
1335 
1336             (packets - lost_packets) / seconds
1337         }
1338     })
1339     .map_err(|_| {
1340         eprintln!(
1341             "=============== iperf3 output ===============\n\n{}\n\n===========end============\n\n",
1342             String::from_utf8_lossy(output)
1343         );
1344         Error::Iperf3Parse
1345     })
1346 }
1347 
1348 #[derive(Clone)]
1349 pub enum FioOps {
1350     Read,
1351     RandomRead,
1352     Write,
1353     RandomWrite,
1354     ReadWrite,
1355     RandRW,
1356 }
1357 
1358 impl fmt::Display for FioOps {
1359     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1360         match self {
1361             FioOps::Read => write!(f, "read"),
1362             FioOps::RandomRead => write!(f, "randread"),
1363             FioOps::Write => write!(f, "write"),
1364             FioOps::RandomWrite => write!(f, "randwrite"),
1365             FioOps::ReadWrite => write!(f, "rw"),
1366             FioOps::RandRW => write!(f, "randrw"),
1367         }
1368     }
1369 }
1370 
1371 pub fn parse_fio_output(output: &str, fio_ops: &FioOps, num_jobs: u32) -> Result<f64, Error> {
1372     std::panic::catch_unwind(|| {
1373         let v: Value =
1374             serde_json::from_str(output).expect("'fio' parse error: invalid json output");
1375         let jobs = v["jobs"]
1376             .as_array()
1377             .expect("'fio' parse error: missing entry 'jobs'");
1378         assert_eq!(
1379             jobs.len(),
1380             num_jobs as usize,
1381             "'fio' parse error: Unexpected number of 'fio' jobs."
1382         );
1383 
1384         let (read, write) = match fio_ops {
1385             FioOps::Read | FioOps::RandomRead => (true, false),
1386             FioOps::Write | FioOps::RandomWrite => (false, true),
1387             FioOps::ReadWrite | FioOps::RandRW => (true, true),
1388         };
1389 
1390         let mut total_bps = 0_f64;
1391         for j in jobs {
1392             if read {
1393                 let bytes = j["read"]["io_bytes"]
1394                     .as_u64()
1395                     .expect("'fio' parse error: missing entry 'read.io_bytes'");
1396                 let runtime = j["read"]["runtime"]
1397                     .as_u64()
1398                     .expect("'fio' parse error: missing entry 'read.runtime'")
1399                     as f64
1400                     / 1000_f64;
1401                 total_bps += bytes as f64 / runtime;
1402             }
1403             if write {
1404                 let bytes = j["write"]["io_bytes"]
1405                     .as_u64()
1406                     .expect("'fio' parse error: missing entry 'write.io_bytes'");
1407                 let runtime = j["write"]["runtime"]
1408                     .as_u64()
1409                     .expect("'fio' parse error: missing entry 'write.runtime'")
1410                     as f64
1411                     / 1000_f64;
1412                 total_bps += bytes as f64 / runtime;
1413             }
1414         }
1415 
1416         total_bps
1417     })
1418     .map_err(|_| {
1419         eprintln!(
1420             "=============== Fio output ===============\n\n{output}\n\n===========end============\n\n"
1421         );
1422         Error::FioOutputParse
1423     })
1424 }
1425 
1426 pub fn parse_fio_output_iops(output: &str, fio_ops: &FioOps, num_jobs: u32) -> Result<f64, Error> {
1427     std::panic::catch_unwind(|| {
1428         let v: Value =
1429             serde_json::from_str(output).expect("'fio' parse error: invalid json output");
1430         let jobs = v["jobs"]
1431             .as_array()
1432             .expect("'fio' parse error: missing entry 'jobs'");
1433         assert_eq!(
1434             jobs.len(),
1435             num_jobs as usize,
1436             "'fio' parse error: Unexpected number of 'fio' jobs."
1437         );
1438 
1439         let (read, write) = match fio_ops {
1440             FioOps::Read | FioOps::RandomRead => (true, false),
1441             FioOps::Write | FioOps::RandomWrite => (false, true),
1442             FioOps::ReadWrite | FioOps::RandRW => (true, true),
1443         };
1444 
1445         let mut total_iops = 0_f64;
1446         for j in jobs {
1447             if read {
1448                 let ios = j["read"]["total_ios"]
1449                     .as_u64()
1450                     .expect("'fio' parse error: missing entry 'read.total_ios'");
1451                 let runtime = j["read"]["runtime"]
1452                     .as_u64()
1453                     .expect("'fio' parse error: missing entry 'read.runtime'")
1454                     as f64
1455                     / 1000_f64;
1456                 total_iops += ios as f64 / runtime;
1457             }
1458             if write {
1459                 let ios = j["write"]["total_ios"]
1460                     .as_u64()
1461                     .expect("'fio' parse error: missing entry 'write.total_ios'");
1462                 let runtime = j["write"]["runtime"]
1463                     .as_u64()
1464                     .expect("'fio' parse error: missing entry 'write.runtime'")
1465                     as f64
1466                     / 1000_f64;
1467                 total_iops += ios as f64 / runtime;
1468             }
1469         }
1470 
1471         total_iops
1472     })
1473     .map_err(|_| {
1474         eprintln!(
1475             "=============== Fio output ===============\n\n{output}\n\n===========end============\n\n"
1476         );
1477         Error::FioOutputParse
1478     })
1479 }
1480 
1481 // Wait the child process for a given timeout
1482 fn child_wait_timeout(child: &mut Child, timeout: u64) -> Result<(), WaitTimeoutError> {
1483     match child.wait_timeout(Duration::from_secs(timeout)) {
1484         Err(e) => {
1485             return Err(WaitTimeoutError::General(e));
1486         }
1487         Ok(s) => match s {
1488             None => {
1489                 return Err(WaitTimeoutError::Timedout);
1490             }
1491             Some(s) => {
1492                 if !s.success() {
1493                     return Err(WaitTimeoutError::ExitStatus);
1494                 }
1495             }
1496         },
1497     }
1498 
1499     Ok(())
1500 }
1501 
1502 pub fn measure_virtio_net_throughput(
1503     test_timeout: u32,
1504     queue_pairs: u32,
1505     guest: &Guest,
1506     receive: bool,
1507     bandwidth: bool,
1508 ) -> Result<f64, Error> {
1509     let default_port = 5201;
1510 
1511     // 1. start the iperf3 server on the guest
1512     for n in 0..queue_pairs {
1513         guest.ssh_command(&format!("iperf3 -s -p {} -D", default_port + n))?;
1514     }
1515 
1516     thread::sleep(Duration::new(1, 0));
1517 
1518     // 2. start the iperf3 client on host to measure RX through-put
1519     let mut clients = Vec::new();
1520     for n in 0..queue_pairs {
1521         let mut cmd = Command::new("iperf3");
1522         cmd.args([
1523             "-J", // Output in JSON format
1524             "-c",
1525             &guest.network.guest_ip,
1526             "-p",
1527             &format!("{}", default_port + n),
1528             "-t",
1529             &format!("{test_timeout}"),
1530             "-i",
1531             "0",
1532         ]);
1533         // For measuring the guest transmit throughput (as a sender),
1534         // use reverse mode of the iperf3 client on the host
1535         if !receive {
1536             cmd.args(["-R"]);
1537         }
1538         // Use UDP stream to measure packets per second. The bitrate is set to
1539         // 1T to make sure it saturates the link.
1540         if !bandwidth {
1541             cmd.args(["-u", "-b", "1T"]);
1542         }
1543         let client = cmd
1544             .stderr(Stdio::piped())
1545             .stdout(Stdio::piped())
1546             .spawn()
1547             .map_err(Error::Spawn)?;
1548 
1549         clients.push(client);
1550     }
1551 
1552     let mut err: Option<Error> = None;
1553     let mut results = Vec::new();
1554     let mut failed = false;
1555     for c in clients {
1556         let mut c = c;
1557         if let Err(e) = child_wait_timeout(&mut c, test_timeout as u64 + 5) {
1558             err = Some(Error::WaitTimeout(e));
1559             failed = true;
1560         }
1561 
1562         if !failed {
1563             // Safe to unwrap as we know the child has terminated succesffully
1564             let output = c.wait_with_output().unwrap();
1565             results.push(parse_iperf3_output(&output.stdout, receive, bandwidth)?);
1566         } else {
1567             let _ = c.kill();
1568             let output = c.wait_with_output().unwrap();
1569             println!(
1570                 "=============== Client output [Error] ===============\n\n{}\n\n===========end============\n\n",
1571                 String::from_utf8_lossy(&output.stdout)
1572             );
1573         }
1574     }
1575 
1576     if let Some(e) = err {
1577         Err(e)
1578     } else {
1579         Ok(results.iter().sum())
1580     }
1581 }
1582 
1583 pub fn parse_ethr_latency_output(output: &[u8]) -> Result<Vec<f64>, Error> {
1584     std::panic::catch_unwind(|| {
1585         let s = String::from_utf8_lossy(output);
1586         let mut latency = Vec::new();
1587         for l in s.lines() {
1588             let v: Value = serde_json::from_str(l).expect("'ethr' parse error: invalid json line");
1589             // Skip header/summary lines
1590             if let Some(avg) = v["Avg"].as_str() {
1591                 // Assume the latency unit is always "us"
1592                 latency.push(
1593                     avg.split("us").collect::<Vec<&str>>()[0]
1594                         .parse::<f64>()
1595                         .expect("'ethr' parse error: invalid 'Avg' entry"),
1596                 );
1597             }
1598         }
1599 
1600         assert!(
1601             !latency.is_empty(),
1602             "'ethr' parse error: no valid latency data found"
1603         );
1604 
1605         latency
1606     })
1607     .map_err(|_| {
1608         eprintln!(
1609             "=============== ethr output ===============\n\n{}\n\n===========end============\n\n",
1610             String::from_utf8_lossy(output)
1611         );
1612         Error::EthrLogParse
1613     })
1614 }
1615 
1616 pub fn measure_virtio_net_latency(guest: &Guest, test_timeout: u32) -> Result<Vec<f64>, Error> {
1617     // copy the 'ethr' tool to the guest image
1618     let ethr_path = "/usr/local/bin/ethr";
1619     let ethr_remote_path = "/tmp/ethr";
1620     scp_to_guest(
1621         Path::new(ethr_path),
1622         Path::new(ethr_remote_path),
1623         &guest.network.guest_ip,
1624         //DEFAULT_SSH_RETRIES,
1625         1,
1626         DEFAULT_SSH_TIMEOUT,
1627     )?;
1628 
1629     // Start the ethr server on the guest
1630     guest.ssh_command(&format!("{ethr_remote_path} -s &> /dev/null &"))?;
1631 
1632     thread::sleep(Duration::new(10, 0));
1633 
1634     // Start the ethr client on the host
1635     let log_file = guest
1636         .tmp_dir
1637         .as_path()
1638         .join("ethr.client.log")
1639         .to_str()
1640         .unwrap()
1641         .to_string();
1642     let mut c = Command::new(ethr_path)
1643         .args([
1644             "-c",
1645             &guest.network.guest_ip,
1646             "-t",
1647             "l",
1648             "-o",
1649             &log_file, // file output is JSON format
1650             "-d",
1651             &format!("{test_timeout}s"),
1652         ])
1653         .stderr(Stdio::piped())
1654         .stdout(Stdio::piped())
1655         .spawn()
1656         .map_err(Error::Spawn)?;
1657 
1658     if let Err(e) = child_wait_timeout(&mut c, test_timeout as u64 + 5).map_err(Error::WaitTimeout)
1659     {
1660         let _ = c.kill();
1661         return Err(e);
1662     }
1663 
1664     // Parse the ethr latency test output
1665     let content = fs::read(log_file).map_err(Error::EthrLogFile)?;
1666     parse_ethr_latency_output(&content)
1667 }
1668