blob: 9dec1c13ed722b36e3fe97792672a9a9901c3b6e [file] [log] [blame]
Alan Stokes8c840442021-11-26 15:54:30 +00001/*
2 * Copyright 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alan Stokesda596932021-12-15 17:48:55 +000017//! Handle running odrefresh in the VM, with an async interface to allow cancellation
18
19use crate::fd_server_helper::FdServerConfig;
Alan Stokes8c840442021-11-26 15:54:30 +000020use crate::instance_starter::CompOsInstance;
Alan Stokes8c840442021-11-26 15:54:30 +000021use android_system_composd::aidl::android::system::composd::{
22 ICompilationTask::ICompilationTask, ICompilationTaskCallback::ICompilationTaskCallback,
23};
24use android_system_composd::binder::{Interface, Result as BinderResult, Strong};
Alan Stokes126fd512021-12-16 15:00:01 +000025use anyhow::{Context, Result};
Alan Stokes2d2e4db2022-01-28 16:41:52 +000026use compos_aidl_interface::aidl::com::android::compos::ICompOsService::{
27 CompilationMode::CompilationMode, ICompOsService,
28};
Alan Stokes16fb8552022-02-10 15:07:27 +000029use compos_common::odrefresh::{ExitCode, ODREFRESH_OUTPUT_ROOT_DIR};
Alan Stokes454069c2022-02-03 11:21:19 +000030use log::{error, info, warn};
Alan Stokesda596932021-12-15 17:48:55 +000031use rustutils::system_properties;
Alan Stokes35bac3c2021-12-16 14:37:24 +000032use std::fs::{remove_dir_all, File, OpenOptions};
Alan Stokesda596932021-12-15 17:48:55 +000033use std::os::unix::fs::OpenOptionsExt;
34use std::os::unix::io::AsRawFd;
35use std::path::Path;
Alan Stokes8c840442021-11-26 15:54:30 +000036use std::sync::{Arc, Mutex};
37use std::thread;
38
39#[derive(Clone)]
40pub struct OdrefreshTask {
41 running_task: Arc<Mutex<Option<RunningTask>>>,
42}
43
44impl Interface for OdrefreshTask {}
45
46impl ICompilationTask for OdrefreshTask {
47 fn cancel(&self) -> BinderResult<()> {
48 let task = self.take();
49 // Drop the VM, which should end compilation - and cause our thread to exit
50 drop(task);
51 Ok(())
52 }
53}
54
Alan Stokesda596932021-12-15 17:48:55 +000055struct RunningTask {
56 callback: Strong<dyn ICompilationTaskCallback>,
57 #[allow(dead_code)] // Keeps the CompOS VM alive
58 comp_os: Arc<CompOsInstance>,
59}
60
Alan Stokes8c840442021-11-26 15:54:30 +000061impl OdrefreshTask {
62 /// Return the current running task, if any, removing it from this CompilationTask.
63 /// Once removed, meaning the task has ended or been canceled, further calls will always return
64 /// None.
65 fn take(&self) -> Option<RunningTask> {
66 self.running_task.lock().unwrap().take()
67 }
68
69 pub fn start(
70 comp_os: Arc<CompOsInstance>,
Alan Stokes2d2e4db2022-01-28 16:41:52 +000071 compilation_mode: CompilationMode,
Alan Stokesac9aa1a2021-12-14 11:32:13 +000072 target_dir_name: String,
Alan Stokes8c840442021-11-26 15:54:30 +000073 callback: &Strong<dyn ICompilationTaskCallback>,
74 ) -> Result<OdrefreshTask> {
75 let service = comp_os.get_service();
76 let task = RunningTask { comp_os, callback: callback.clone() };
77 let task = OdrefreshTask { running_task: Arc::new(Mutex::new(Some(task))) };
78
Alan Stokes2d2e4db2022-01-28 16:41:52 +000079 task.clone().start_thread(service, compilation_mode, target_dir_name);
Alan Stokes8c840442021-11-26 15:54:30 +000080
81 Ok(task)
82 }
83
Alan Stokes2d2e4db2022-01-28 16:41:52 +000084 fn start_thread(
85 self,
86 service: Strong<dyn ICompOsService>,
87 compilation_mode: CompilationMode,
88 target_dir_name: String,
89 ) {
Alan Stokes8c840442021-11-26 15:54:30 +000090 thread::spawn(move || {
Alan Stokes2d2e4db2022-01-28 16:41:52 +000091 let exit_code = run_in_vm(service, compilation_mode, &target_dir_name);
Alan Stokes8c840442021-11-26 15:54:30 +000092
93 let task = self.take();
94 // We don't do the callback if cancel has already happened.
95 if let Some(task) = task {
96 let result = match exit_code {
Alan Stokes454069c2022-02-03 11:21:19 +000097 Ok(ExitCode::CompilationSuccess) => {
98 info!("CompilationSuccess");
99 task.callback.onSuccess()
100 }
Alan Stokes8c840442021-11-26 15:54:30 +0000101 Ok(exit_code) => {
102 error!("Unexpected odrefresh result: {:?}", exit_code);
103 task.callback.onFailure()
104 }
105 Err(e) => {
106 error!("Running odrefresh failed: {:?}", e);
107 task.callback.onFailure()
108 }
109 };
110 if let Err(e) = result {
111 warn!("Failed to deliver callback: {:?}", e);
112 }
113 }
114 });
115 }
116}
117
Alan Stokes2d2e4db2022-01-28 16:41:52 +0000118fn run_in_vm(
119 service: Strong<dyn ICompOsService>,
120 compilation_mode: CompilationMode,
121 target_dir_name: &str,
122) -> Result<ExitCode> {
Alan Stokes16fb8552022-02-10 15:07:27 +0000123 let output_root = Path::new(ODREFRESH_OUTPUT_ROOT_DIR);
Alan Stokes35bac3c2021-12-16 14:37:24 +0000124
125 // We need to remove the target directory because odrefresh running in compos will create it
126 // (and can't see the existing one, since authfs doesn't show it existing files in an output
127 // directory).
128 let target_path = output_root.join(target_dir_name);
Alan Stokesa4542ec2021-12-20 09:39:33 +0000129 if target_path.exists() {
130 remove_dir_all(&target_path)
131 .with_context(|| format!("Failed to delete {}", target_path.display()))?;
132 }
Alan Stokes35bac3c2021-12-16 14:37:24 +0000133
Alan Stokesda596932021-12-15 17:48:55 +0000134 let staging_dir = open_dir(composd_native::palette_create_odrefresh_staging_directory()?)?;
135 let system_dir = open_dir(Path::new("/system"))?;
Alan Stokes35bac3c2021-12-16 14:37:24 +0000136 let output_dir = open_dir(output_root)?;
Alan Stokesda596932021-12-15 17:48:55 +0000137
138 // Spawn a fd_server to serve the FDs.
139 let fd_server_config = FdServerConfig {
140 ro_dir_fds: vec![system_dir.as_raw_fd()],
141 rw_dir_fds: vec![staging_dir.as_raw_fd(), output_dir.as_raw_fd()],
142 ..Default::default()
143 };
144 let fd_server_raii = fd_server_config.into_fd_server()?;
145
Andrew Walbran014efb52022-02-03 17:43:11 +0000146 let zygote_arch = system_properties::read("ro.zygote")?.context("ro.zygote not set")?;
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800147 let system_server_compiler_filter =
Andrew Walbran014efb52022-02-03 17:43:11 +0000148 system_properties::read("dalvik.vm.systemservercompilerfilter")?.unwrap_or_default();
Alan Stokesda596932021-12-15 17:48:55 +0000149 let exit_code = service.odrefresh(
Alan Stokes2d2e4db2022-01-28 16:41:52 +0000150 compilation_mode,
Alan Stokesda596932021-12-15 17:48:55 +0000151 system_dir.as_raw_fd(),
152 output_dir.as_raw_fd(),
153 staging_dir.as_raw_fd(),
154 target_dir_name,
155 &zygote_arch,
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800156 &system_server_compiler_filter,
Alan Stokesda596932021-12-15 17:48:55 +0000157 )?;
158
159 drop(fd_server_raii);
Alan Stokes126fd512021-12-16 15:00:01 +0000160 ExitCode::from_i32(exit_code.into())
Alan Stokesda596932021-12-15 17:48:55 +0000161}
162
163/// Returns an owned FD of the directory. It currently returns a `File` as a FD owner, but
164/// it's better to use `std::os::unix::io::OwnedFd` once/if it becomes standard.
165fn open_dir(path: &Path) -> Result<File> {
166 OpenOptions::new()
167 .custom_flags(libc::O_DIRECTORY)
168 .read(true) // O_DIRECTORY can only be opened with read
169 .open(path)
170 .with_context(|| format!("Failed to open {:?} directory as path fd", path))
Alan Stokes8c840442021-11-26 15:54:30 +0000171}