blob: 9088f1a6162672855bc73c7086ccc1498d6b3d30 [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 Walbran94bbf2f2022-05-12 18:35:42 +000038
39/// Runs the vmbase_example VM as an unprotected VM via VirtualizationService.
40#[test]
41fn test_run_example_vm() -> Result<(), Error> {
Pierre-Clément Tosi0d1aed02022-11-17 17:06:28 +000042 android_logger::init_once(
43 android_logger::Config::default().with_tag("vmbase").with_min_level(log::Level::Debug),
44 );
45
46 // Redirect panic messages to logcat.
47 panic::set_hook(Box::new(|panic_info| {
48 log::error!("{}", panic_info);
49 }));
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000050
51 // We need to start the thread pool for Binder to work properly, especially link_to_death.
52 ProcessState::start_thread_pool();
53
David Brazdil4b4c5102022-12-19 22:56:20 +000054 let virtmgr =
55 vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
56 let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000057
58 // Start example VM.
59 let bootloader = ParcelFileDescriptor::new(
60 File::open(VMBASE_EXAMPLE_PATH)
61 .with_context(|| format!("Failed to open VM image {}", VMBASE_EXAMPLE_PATH))?,
62 );
Seungjae Yoo62085c02022-08-12 04:44:52 +000063
Andrew Walbranb713baa2022-12-07 14:34:49 +000064 // Make file for test disk image.
65 let mut test_image = File::options()
66 .create(true)
67 .read(true)
68 .write(true)
69 .truncate(true)
70 .open(TEST_DISK_IMAGE_PATH)
71 .with_context(|| format!("Failed to open test disk image {}", TEST_DISK_IMAGE_PATH))?;
72 // Write 4 sectors worth of 4-byte numbers counting up.
73 for i in 0u32..512 {
74 test_image.write_all(&i.to_le_bytes())?;
75 }
76 let test_image = ParcelFileDescriptor::new(test_image);
77 let disk_image = DiskImage { image: Some(test_image), writable: false, partitions: vec![] };
78
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000079 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000080 name: String::from("VmBaseTest"),
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000081 kernel: None,
82 initrd: None,
83 params: None,
84 bootloader: Some(bootloader),
Andrew Walbranb713baa2022-12-07 14:34:49 +000085 disks: vec![disk_image],
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000086 protectedVm: false,
87 memoryMib: 300,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000088 cpuTopology: CpuTopology::ONE_CPU,
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000089 platformVersion: "~1.0".to_string(),
90 taskProfiles: vec![],
Nikita Ioffe5776f082023-02-10 21:38:26 +000091 gdbPort: 0, // no gdb
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000092 });
Jakob Vukalovicef996292023-04-13 14:28:34 +000093 let (handle, console) = android_log_fd()?;
Andrew Walbran8d05dae2023-03-22 16:42:55 +000094 let (mut log_reader, log_writer) = pipe()?;
95 let vm = VmInstance::create(service.as_ref(), &config, Some(console), Some(log_writer), None)
Andrew Walbran94bbf2f2022-05-12 18:35:42 +000096 .context("Failed to create VM")?;
97 vm.start().context("Failed to start VM")?;
98 info!("Started example VM.");
99
100 // Wait for VM to finish, and check that it shut down cleanly.
101 let death_reason = vm.wait_for_death();
102 assert_eq!(death_reason, DeathReason::Shutdown);
Jakob Vukalovicef996292023-04-13 14:28:34 +0000103 handle.join().unwrap();
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000104
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000105 // Check that the expected string was written to the log VirtIO console device.
106 let expected = "Hello VirtIO console\n";
107 let mut log_output = String::new();
108 assert_eq!(log_reader.read_to_string(&mut log_output)?, expected.len());
109 assert_eq!(log_output, expected);
110
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000111 Ok(())
112}
113
Jakob Vukalovicef996292023-04-13 14:28:34 +0000114fn android_log_fd() -> Result<(thread::JoinHandle<()>, File), io::Error> {
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000115 let (reader, writer) = pipe()?;
Jakob Vukalovicef996292023-04-13 14:28:34 +0000116 let handle = thread::spawn(|| VmLogProcessor::new(reader).run().unwrap());
117 Ok((handle, writer))
Andrew Walbran94bbf2f2022-05-12 18:35:42 +0000118}
Andrew Walbran8d05dae2023-03-22 16:42:55 +0000119
120fn pipe() -> io::Result<(File, File)> {
121 let (reader_fd, writer_fd) = nix::unistd::pipe()?;
122
123 // SAFETY: These are new FDs with no previous owner.
124 let reader = unsafe { File::from_raw_fd(reader_fd) };
125 let writer = unsafe { File::from_raw_fd(writer_fd) };
126
127 Ok((reader, writer))
128}
Jakob Vukalovicef996292023-04-13 14:28:34 +0000129
130struct VmLogProcessor {
131 reader: Option<File>,
132 expected: VecDeque<String>,
133 unexpected: HashSet<String>,
134 had_unexpected: bool,
135}
136
137impl VmLogProcessor {
138 fn messages() -> (VecDeque<String>, HashSet<String>) {
139 let mut expected = VecDeque::new();
140 let mut unexpected = HashSet::new();
141 for log_lvl in ["[ERROR]", "[WARN]", "[INFO]", "[DEBUG]"] {
142 expected.push_back(format!("{log_lvl} Unsuppressed message"));
143 unexpected.insert(format!("{log_lvl} Suppressed message"));
144 }
145 (expected, unexpected)
146 }
147
148 fn new(reader: File) -> Self {
149 let (expected, unexpected) = Self::messages();
150 Self { reader: Some(reader), expected, unexpected, had_unexpected: false }
151 }
152
153 fn verify(&mut self, msg: &str) {
154 if self.expected.front() == Some(&msg.to_owned()) {
155 self.expected.pop_front();
156 }
157 if !self.had_unexpected && self.unexpected.contains(msg) {
158 self.had_unexpected = true;
159 }
160 }
161
162 fn run(mut self) -> Result<(), &'static str> {
163 for line in BufReader::new(self.reader.take().unwrap()).lines() {
164 let msg = line.unwrap();
165 info!("{msg}");
166 self.verify(&msg);
167 }
168 if !self.expected.is_empty() {
169 Err("missing expected log message")
170 } else if self.had_unexpected {
171 Err("unexpected log message")
172 } else {
173 Ok(())
174 }
175 }
176}