blob: 2df5a803d1ec7c136846ee3e8d90b5a66bd95d54 [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 os::unix::io::FromRawFd,
31 panic, thread,
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000032};
33use vmclient::{DeathReason, VmInstance};
34
35const VMBASE_EXAMPLE_PATH: &str =
36 "/data/local/tmp/vmbase_example.integration_test/arm64/vmbase_example.bin";
Andrew Walbranb713baa2022-12-07 14:34:49 +000037const TEST_DISK_IMAGE_PATH: &str = "/data/local/tmp/vmbase_example.integration_test/test_disk.img";
Andrew Walbran6ac174e2023-06-23 14:58:51 +000038const EMPTY_DISK_IMAGE_PATH: &str =
39 "/data/local/tmp/vmbase_example.integration_test/empty_disk.img";
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000040
41/// Runs the vmbase_example VM as an unprotected VM via VirtualizationService.
42#[test]
43fn test_run_example_vm() -> Result<(), Error> {
Pierre-Clément Tosi0d1aed02022-11-17 17:06:28 +000044 android_logger::init_once(
Jeff Vander Stoepd9dda0c2024-02-07 14:27:06 +010045 android_logger::Config::default()
46 .with_tag("vmbase")
47 .with_max_level(log::LevelFilter::Debug),
Pierre-Clément Tosi0d1aed02022-11-17 17:06:28 +000048 );
49
50 // Redirect panic messages to logcat.
51 panic::set_hook(Box::new(|panic_info| {
52 log::error!("{}", panic_info);
53 }));
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000054
55 // We need to start the thread pool for Binder to work properly, especially link_to_death.
56 ProcessState::start_thread_pool();
57
David Brazdil4b4c5102022-12-19 22:56:20 +000058 let virtmgr =
59 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
60 let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000061
62 // Start example VM.
63 let bootloader = ParcelFileDescriptor::new(
64 File::open(VMBASE_EXAMPLE_PATH)
65 .with_context(|| format!("Failed to open VM image {}", VMBASE_EXAMPLE_PATH))?,
66 );
Seungjae Yoo62085c02022-08-12 04:44:52 +000067
Andrew Walbranb713baa2022-12-07 14:34:49 +000068 // Make file for test disk image.
69 let mut test_image = File::options()
70 .create(true)
71 .read(true)
72 .write(true)
73 .truncate(true)
74 .open(TEST_DISK_IMAGE_PATH)
75 .with_context(|| format!("Failed to open test disk image {}", TEST_DISK_IMAGE_PATH))?;
76 // Write 4 sectors worth of 4-byte numbers counting up.
77 for i in 0u32..512 {
78 test_image.write_all(&i.to_le_bytes())?;
79 }
80 let test_image = ParcelFileDescriptor::new(test_image);
81 let disk_image = DiskImage { image: Some(test_image), writable: false, partitions: vec![] };
82
Andrew Walbran6ac174e2023-06-23 14:58:51 +000083 // Make file for empty test disk image.
84 let empty_image = File::options()
85 .create(true)
86 .read(true)
87 .write(true)
88 .truncate(true)
89 .open(EMPTY_DISK_IMAGE_PATH)
90 .with_context(|| format!("Failed to open empty disk image {}", EMPTY_DISK_IMAGE_PATH))?;
91 let empty_image = ParcelFileDescriptor::new(empty_image);
92 let empty_disk_image =
93 DiskImage { image: Some(empty_image), writable: false, partitions: vec![] };
94
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000095 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000096 name: String::from("VmBaseTest"),
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000097 kernel: None,
98 initrd: None,
99 params: None,
100 bootloader: Some(bootloader),
Andrew Walbran6ac174e2023-06-23 14:58:51 +0000101 disks: vec![disk_image, empty_disk_image],
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000102 protectedVm: false,
103 memoryMib: 300,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000104 cpuTopology: CpuTopology::ONE_CPU,
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000105 platformVersion: "~1.0".to_string(),
Nikita Ioffe5776f082023-02-10 21:38:26 +0000106 gdbPort: 0, // no gdb
Inseob Kim6ef80972023-07-20 17:23:36 +0900107 ..Default::default()
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000108 });
Jakob Vukalovicef996292023-04-13 14:28:34 +0000109 let (handle, console) = android_log_fd()?;
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000110 let (mut log_reader, log_writer) = pipe()?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900111 let vm = VmInstance::create(
112 service.as_ref(),
113 &config,
114 Some(console),
115 /* consoleIn */ None,
116 Some(log_writer),
117 None,
118 )
119 .context("Failed to create VM")?;
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000120 vm.start().context("Failed to start VM")?;
121 info!("Started example VM.");
122
123 // Wait for VM to finish, and check that it shut down cleanly.
124 let death_reason = vm.wait_for_death();
125 assert_eq!(death_reason, DeathReason::Shutdown);
Jakob Vukalovicef996292023-04-13 14:28:34 +0000126 handle.join().unwrap();
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000127
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000128 // Check that the expected string was written to the log VirtIO console device.
129 let expected = "Hello VirtIO console\n";
130 let mut log_output = String::new();
131 assert_eq!(log_reader.read_to_string(&mut log_output)?, expected.len());
132 assert_eq!(log_output, expected);
133
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000134 Ok(())
135}
136
Jakob Vukalovicef996292023-04-13 14:28:34 +0000137fn android_log_fd() -> Result<(thread::JoinHandle<()>, File), io::Error> {
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000138 let (reader, writer) = pipe()?;
Jakob Vukalovicef996292023-04-13 14:28:34 +0000139 let handle = thread::spawn(|| VmLogProcessor::new(reader).run().unwrap());
140 Ok((handle, writer))
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000141}
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000142
143fn pipe() -> io::Result<(File, File)> {
144 let (reader_fd, writer_fd) = nix::unistd::pipe()?;
145
146 // SAFETY: These are new FDs with no previous owner.
147 let reader = unsafe { File::from_raw_fd(reader_fd) };
Andrew Walbranae3350d2023-07-21 19:01:18 +0100148 // SAFETY: These are new FDs with no previous owner.
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000149 let writer = unsafe { File::from_raw_fd(writer_fd) };
150
151 Ok((reader, writer))
152}
Jakob Vukalovicef996292023-04-13 14:28:34 +0000153
154struct VmLogProcessor {
155 reader: Option<File>,
156 expected: VecDeque<String>,
157 unexpected: HashSet<String>,
158 had_unexpected: bool,
159}
160
161impl VmLogProcessor {
162 fn messages() -> (VecDeque<String>, HashSet<String>) {
163 let mut expected = VecDeque::new();
164 let mut unexpected = HashSet::new();
165 for log_lvl in ["[ERROR]", "[WARN]", "[INFO]", "[DEBUG]"] {
166 expected.push_back(format!("{log_lvl} Unsuppressed message"));
167 unexpected.insert(format!("{log_lvl} Suppressed message"));
168 }
169 (expected, unexpected)
170 }
171
172 fn new(reader: File) -> Self {
173 let (expected, unexpected) = Self::messages();
174 Self { reader: Some(reader), expected, unexpected, had_unexpected: false }
175 }
176
177 fn verify(&mut self, msg: &str) {
178 if self.expected.front() == Some(&msg.to_owned()) {
179 self.expected.pop_front();
180 }
181 if !self.had_unexpected && self.unexpected.contains(msg) {
182 self.had_unexpected = true;
183 }
184 }
185
186 fn run(mut self) -> Result<(), &'static str> {
187 for line in BufReader::new(self.reader.take().unwrap()).lines() {
188 let msg = line.unwrap();
189 info!("{msg}");
190 self.verify(&msg);
191 }
192 if !self.expected.is_empty() {
193 Err("missing expected log message")
194 } else if self.had_unexpected {
195 Err("unexpected log message")
196 } else {
197 Ok(())
198 }
199 }
200}