blob: 8f9fafc4742dcf0331cfd5424ab2e38a2066e3e3 [file] [log] [blame]
Andrew Walbran94bbf2f2022-05-12 18:35:42 +00001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Integration test for VM bootloader.
16
17use android_system_virtualizationservice::{
18 aidl::android::system::virtualizationservice::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000019 CpuTopology::CpuTopology, DiskImage::DiskImage, VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000020 VirtualMachineRawConfig::VirtualMachineRawConfig,
21 },
22 binder::{ParcelFileDescriptor, ProcessState},
23};
24use anyhow::{Context, Error};
25use log::info;
26use std::{
Jakob Vukalovicef996292023-04-13 14:28:34 +000027 collections::{HashSet, VecDeque},
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000028 fs::File,
Andrew Walbran8d05dae2023-03-22 16:42:55 +000029 io::{self, BufRead, BufReader, Read, Write},
Pierre-Clément Tosi0d1aed02022-11-17 17:06:28 +000030 panic, thread,
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000031};
32use vmclient::{DeathReason, VmInstance};
33
Nikita Putikhincf9c24e2024-07-16 12:42:14 +020034const VMBASE_EXAMPLE_PATH: &str = "vmbase_example.bin";
35const TEST_DISK_IMAGE_PATH: &str = "test_disk.img";
36const EMPTY_DISK_IMAGE_PATH: &str = "empty_disk.img";
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000037
38/// Runs the vmbase_example VM as an unprotected VM via VirtualizationService.
39#[test]
40fn test_run_example_vm() -> Result<(), Error> {
Pierre-Clément Tosi0d1aed02022-11-17 17:06:28 +000041 android_logger::init_once(
Jeff Vander Stoepd9dda0c2024-02-07 14:27:06 +010042 android_logger::Config::default()
43 .with_tag("vmbase")
44 .with_max_level(log::LevelFilter::Debug),
Pierre-Clément Tosi0d1aed02022-11-17 17:06:28 +000045 );
46
47 // Redirect panic messages to logcat.
48 panic::set_hook(Box::new(|panic_info| {
49 log::error!("{}", panic_info);
50 }));
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000051
52 // We need to start the thread pool for Binder to work properly, especially link_to_death.
53 ProcessState::start_thread_pool();
54
David Brazdil4b4c5102022-12-19 22:56:20 +000055 let virtmgr =
56 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
57 let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000058
59 // Start example VM.
60 let bootloader = ParcelFileDescriptor::new(
61 File::open(VMBASE_EXAMPLE_PATH)
62 .with_context(|| format!("Failed to open VM image {}", VMBASE_EXAMPLE_PATH))?,
63 );
Seungjae Yoo62085c02022-08-12 04:44:52 +000064
Andrew Walbranb713baa2022-12-07 14:34:49 +000065 // Make file for test disk image.
66 let mut test_image = File::options()
67 .create(true)
68 .read(true)
69 .write(true)
70 .truncate(true)
71 .open(TEST_DISK_IMAGE_PATH)
72 .with_context(|| format!("Failed to open test disk image {}", TEST_DISK_IMAGE_PATH))?;
73 // Write 4 sectors worth of 4-byte numbers counting up.
74 for i in 0u32..512 {
75 test_image.write_all(&i.to_le_bytes())?;
76 }
77 let test_image = ParcelFileDescriptor::new(test_image);
78 let disk_image = DiskImage { image: Some(test_image), writable: false, partitions: vec![] };
79
Andrew Walbran6ac174e2023-06-23 14:58:51 +000080 // Make file for empty test disk image.
81 let empty_image = File::options()
82 .create(true)
83 .read(true)
84 .write(true)
85 .truncate(true)
86 .open(EMPTY_DISK_IMAGE_PATH)
87 .with_context(|| format!("Failed to open empty disk image {}", EMPTY_DISK_IMAGE_PATH))?;
88 let empty_image = ParcelFileDescriptor::new(empty_image);
89 let empty_disk_image =
90 DiskImage { image: Some(empty_image), writable: false, partitions: vec![] };
91
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000092 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000093 name: String::from("VmBaseTest"),
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000094 kernel: None,
95 initrd: None,
96 params: None,
97 bootloader: Some(bootloader),
Andrew Walbran6ac174e2023-06-23 14:58:51 +000098 disks: vec![disk_image, empty_disk_image],
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000099 protectedVm: false,
100 memoryMib: 300,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000101 cpuTopology: CpuTopology::ONE_CPU,
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000102 platformVersion: "~1.0".to_string(),
Nikita Ioffe5776f082023-02-10 21:38:26 +0000103 gdbPort: 0, // no gdb
Inseob Kim6ef80972023-07-20 17:23:36 +0900104 ..Default::default()
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000105 });
Jakob Vukalovicef996292023-04-13 14:28:34 +0000106 let (handle, console) = android_log_fd()?;
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000107 let (mut log_reader, log_writer) = pipe()?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900108 let vm = VmInstance::create(
109 service.as_ref(),
110 &config,
111 Some(console),
112 /* consoleIn */ None,
113 Some(log_writer),
114 None,
115 )
116 .context("Failed to create VM")?;
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000117 vm.start().context("Failed to start VM")?;
118 info!("Started example VM.");
119
120 // Wait for VM to finish, and check that it shut down cleanly.
121 let death_reason = vm.wait_for_death();
122 assert_eq!(death_reason, DeathReason::Shutdown);
Jakob Vukalovicef996292023-04-13 14:28:34 +0000123 handle.join().unwrap();
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000124
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000125 // Check that the expected string was written to the log VirtIO console device.
126 let expected = "Hello VirtIO console\n";
127 let mut log_output = String::new();
128 assert_eq!(log_reader.read_to_string(&mut log_output)?, expected.len());
129 assert_eq!(log_output, expected);
130
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000131 Ok(())
132}
133
Jakob Vukalovicef996292023-04-13 14:28:34 +0000134fn android_log_fd() -> Result<(thread::JoinHandle<()>, File), io::Error> {
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000135 let (reader, writer) = pipe()?;
Jakob Vukalovicef996292023-04-13 14:28:34 +0000136 let handle = thread::spawn(|| VmLogProcessor::new(reader).run().unwrap());
137 Ok((handle, writer))
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000138}
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000139
140fn pipe() -> io::Result<(File, File)> {
141 let (reader_fd, writer_fd) = nix::unistd::pipe()?;
Frederick Maylefbbcfcd2024-04-08 16:31:54 -0700142 Ok((reader_fd.into(), writer_fd.into()))
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000143}
Jakob Vukalovicef996292023-04-13 14:28:34 +0000144
145struct VmLogProcessor {
146 reader: Option<File>,
147 expected: VecDeque<String>,
148 unexpected: HashSet<String>,
149 had_unexpected: bool,
150}
151
152impl VmLogProcessor {
153 fn messages() -> (VecDeque<String>, HashSet<String>) {
154 let mut expected = VecDeque::new();
155 let mut unexpected = HashSet::new();
156 for log_lvl in ["[ERROR]", "[WARN]", "[INFO]", "[DEBUG]"] {
157 expected.push_back(format!("{log_lvl} Unsuppressed message"));
158 unexpected.insert(format!("{log_lvl} Suppressed message"));
159 }
160 (expected, unexpected)
161 }
162
163 fn new(reader: File) -> Self {
164 let (expected, unexpected) = Self::messages();
165 Self { reader: Some(reader), expected, unexpected, had_unexpected: false }
166 }
167
168 fn verify(&mut self, msg: &str) {
169 if self.expected.front() == Some(&msg.to_owned()) {
170 self.expected.pop_front();
171 }
172 if !self.had_unexpected && self.unexpected.contains(msg) {
173 self.had_unexpected = true;
174 }
175 }
176
177 fn run(mut self) -> Result<(), &'static str> {
178 for line in BufReader::new(self.reader.take().unwrap()).lines() {
179 let msg = line.unwrap();
180 info!("{msg}");
181 self.verify(&msg);
182 }
183 if !self.expected.is_empty() {
184 Err("missing expected log message")
185 } else if self.had_unexpected {
186 Err("unexpected log message")
187 } else {
188 Ok(())
189 }
190 }
191}