blob: 2586737d6a9138f3e9f83b102a5a62cb3138b7af [file] [log] [blame]
Jooyung Han347d9f22021-05-28 00:05:14 +09001// Copyright 2021, 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//! Microdroid Manager
16
Jooyung Hanf48ceb42021-06-01 18:00:04 +090017mod ioutil;
Jooyung Han74573482021-06-08 17:10:21 +090018mod metadata;
Jooyung Han347d9f22021-05-28 00:05:14 +090019
Jooyung Han634e2d72021-06-10 16:27:38 +090020use anyhow::{anyhow, bail, Result};
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000021use log::{error, info, warn};
Jooyung Han634e2d72021-06-10 16:27:38 +090022use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Joel Galenson482704c2021-07-29 15:53:53 -070023use rustutils::system_properties::PropertyWatcher;
Jiyong Park8611a6c2021-07-09 18:17:44 +090024use std::fs::{self, File};
25use std::os::unix::io::{FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090026use std::path::Path;
Jiyong Park8611a6c2021-07-09 18:17:44 +090027use std::process::{Command, Stdio};
28use std::str;
Jooyung Han634e2d72021-06-10 16:27:38 +090029use std::time::Duration;
Jiyong Park8611a6c2021-07-09 18:17:44 +090030use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090031
32const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jooyung Han347d9f22021-05-28 00:05:14 +090033
Jooyung Han634e2d72021-06-10 16:27:38 +090034fn main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +090035 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +090036 info!("started.");
37
Jooyung Han74573482021-06-08 17:10:21 +090038 let metadata = metadata::load()?;
39 if !metadata.payload_config_path.is_empty() {
Jooyung Han634e2d72021-06-10 16:27:38 +090040 let config = load_config(Path::new(&metadata.payload_config_path))?;
41
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000042 let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
Joel Galenson482704c2021-07-29 15:53:53 -070043 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +000044 warn!("failed to set ro.vmsecret.keymint: {}", err);
45 }
46
Jooyung Han634e2d72021-06-10 16:27:38 +090047 // TODO(jooyung): wait until sys.boot_completed?
Jooyung Han347d9f22021-05-28 00:05:14 +090048 if let Some(main_task) = &config.task {
Jiyong Park8611a6c2021-07-09 18:17:44 +090049 exec_task(main_task).map_err(|e| {
50 error!("failed to execute task: {}", e);
51 e
52 })?;
Jooyung Han347d9f22021-05-28 00:05:14 +090053 }
54 }
55
56 Ok(())
57}
58
Jooyung Han634e2d72021-06-10 16:27:38 +090059fn load_config(path: &Path) -> Result<VmPayloadConfig> {
60 info!("loading config from {:?}...", path);
61 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
62 Ok(serde_json::from_reader(file)?)
63}
64
Jiyong Park8611a6c2021-07-09 18:17:44 +090065/// Executes the given task. Stdout of the task is piped into the vsock stream to the
66/// virtualizationservice in the host side.
Jooyung Han634e2d72021-06-10 16:27:38 +090067fn exec_task(task: &Task) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +090068 const VMADDR_CID_HOST: u32 = 2;
69 const PORT_VIRT_SVC: u32 = 3000;
70 let stdout = match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SVC) {
71 Ok(stream) => {
72 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
73 // to the file object, and then into the Command object. When the command is finished,
74 // the file descriptor is closed.
75 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
76 Stdio::from(f)
Jiyong Park038b73e2021-06-16 01:57:02 +090077 }
Jiyong Park8611a6c2021-07-09 18:17:44 +090078 Err(e) => {
79 error!("failed to connect to virtualization service: {}", e);
80 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
81 // we keep executing the task. This can happen if the owner of the VM doesn't register
82 // callback to accept the stream. Use /dev/null as the stdout so that the task can
83 // make progress without waiting for someone to consume the output.
84 Stdio::null()
85 }
86 };
87 info!("executing main task {:?}...", task);
88 // TODO(jiyong): consider piping the stream into stdio (and probably stderr) as well.
89 let mut child = build_command(task)?.stdout(stdout).spawn()?;
90 match child.wait()?.code() {
91 Some(0) => {
92 info!("task successfully finished");
93 Ok(())
94 }
95 Some(code) => bail!("task exited with exit code: {}", code),
96 None => bail!("task terminated by signal"),
Jiyong Park038b73e2021-06-16 01:57:02 +090097 }
Jooyung Han347d9f22021-05-28 00:05:14 +090098}
Jooyung Han634e2d72021-06-10 16:27:38 +090099
100fn build_command(task: &Task) -> Result<Command> {
101 Ok(match task.type_ {
102 TaskType::Executable => {
103 let mut command = Command::new(&task.command);
104 command.args(&task.args);
105 command
106 }
107 TaskType::MicrodroidLauncher => {
108 let mut command = Command::new("/system/bin/microdroid_launcher");
109 command.arg(find_library_path(&task.command)?).args(&task.args);
110 command
111 }
112 })
113}
114
115fn find_library_path(name: &str) -> Result<String> {
116 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
117 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
118 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
119 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
120
121 let metadata = fs::metadata(&path)?;
122 if !metadata.is_file() {
123 bail!("{} is not a file", &path);
124 }
125
126 Ok(path)
127}