blob: e06e5fe990ab49b3f086dfd9f8772b13b3f0eea6 [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::{
Alan Stokes81c96f32022-04-07 14:13:19 +010022 ICompilationTask::ICompilationTask,
23 ICompilationTaskCallback::{FailureReason::FailureReason, ICompilationTaskCallback},
Alan Stokes8c840442021-11-26 15:54:30 +000024};
25use android_system_composd::binder::{Interface, Result as BinderResult, Strong};
Alan Stokes126fd512021-12-16 15:00:01 +000026use anyhow::{Context, Result};
Alan Stokes2d2e4db2022-01-28 16:41:52 +000027use compos_aidl_interface::aidl::com::android::compos::ICompOsService::{
28 CompilationMode::CompilationMode, ICompOsService,
29};
Alan Stokes16fb8552022-02-10 15:07:27 +000030use compos_common::odrefresh::{ExitCode, ODREFRESH_OUTPUT_ROOT_DIR};
Alan Stokes454069c2022-02-03 11:21:19 +000031use log::{error, info, warn};
Alan Stokesda596932021-12-15 17:48:55 +000032use rustutils::system_properties;
Alan Stokes35bac3c2021-12-16 14:37:24 +000033use std::fs::{remove_dir_all, File, OpenOptions};
Alan Stokesda596932021-12-15 17:48:55 +000034use std::os::unix::fs::OpenOptionsExt;
35use std::os::unix::io::AsRawFd;
36use std::path::Path;
Alan Stokes8c840442021-11-26 15:54:30 +000037use std::sync::{Arc, Mutex};
38use std::thread;
39
40#[derive(Clone)]
41pub struct OdrefreshTask {
42 running_task: Arc<Mutex<Option<RunningTask>>>,
43}
44
45impl Interface for OdrefreshTask {}
46
47impl ICompilationTask for OdrefreshTask {
48 fn cancel(&self) -> BinderResult<()> {
49 let task = self.take();
50 // Drop the VM, which should end compilation - and cause our thread to exit
51 drop(task);
52 Ok(())
53 }
54}
55
Alan Stokesda596932021-12-15 17:48:55 +000056struct RunningTask {
57 callback: Strong<dyn ICompilationTaskCallback>,
58 #[allow(dead_code)] // Keeps the CompOS VM alive
59 comp_os: Arc<CompOsInstance>,
60}
61
Alan Stokes8c840442021-11-26 15:54:30 +000062impl OdrefreshTask {
63 /// Return the current running task, if any, removing it from this CompilationTask.
64 /// Once removed, meaning the task has ended or been canceled, further calls will always return
65 /// None.
66 fn take(&self) -> Option<RunningTask> {
67 self.running_task.lock().unwrap().take()
68 }
69
70 pub fn start(
71 comp_os: Arc<CompOsInstance>,
Alan Stokes2d2e4db2022-01-28 16:41:52 +000072 compilation_mode: CompilationMode,
Alan Stokesac9aa1a2021-12-14 11:32:13 +000073 target_dir_name: String,
Alan Stokes8c840442021-11-26 15:54:30 +000074 callback: &Strong<dyn ICompilationTaskCallback>,
75 ) -> Result<OdrefreshTask> {
76 let service = comp_os.get_service();
77 let task = RunningTask { comp_os, callback: callback.clone() };
78 let task = OdrefreshTask { running_task: Arc::new(Mutex::new(Some(task))) };
79
Alan Stokes2d2e4db2022-01-28 16:41:52 +000080 task.clone().start_thread(service, compilation_mode, target_dir_name);
Alan Stokes8c840442021-11-26 15:54:30 +000081
82 Ok(task)
83 }
84
Alan Stokes2d2e4db2022-01-28 16:41:52 +000085 fn start_thread(
86 self,
87 service: Strong<dyn ICompOsService>,
88 compilation_mode: CompilationMode,
89 target_dir_name: String,
90 ) {
Alan Stokes8c840442021-11-26 15:54:30 +000091 thread::spawn(move || {
Alan Stokes2d2e4db2022-01-28 16:41:52 +000092 let exit_code = run_in_vm(service, compilation_mode, &target_dir_name);
Alan Stokes8c840442021-11-26 15:54:30 +000093
94 let task = self.take();
95 // We don't do the callback if cancel has already happened.
96 if let Some(task) = task {
97 let result = match exit_code {
Alan Stokes454069c2022-02-03 11:21:19 +000098 Ok(ExitCode::CompilationSuccess) => {
99 info!("CompilationSuccess");
100 task.callback.onSuccess()
101 }
Alan Stokes8c840442021-11-26 15:54:30 +0000102 Ok(exit_code) => {
Alan Stokes81c96f32022-04-07 14:13:19 +0100103 let message = format!("Unexpected odrefresh result: {:?}", exit_code);
104 error!("{}", message);
105 task.callback
106 .onFailure(FailureReason::UnexpectedCompilationResult, &message)
Alan Stokes8c840442021-11-26 15:54:30 +0000107 }
108 Err(e) => {
Alan Stokes81c96f32022-04-07 14:13:19 +0100109 let message = format!("Running odrefresh failed: {:?}", e);
110 error!("{}", message);
111 task.callback.onFailure(FailureReason::CompilationFailed, &message)
Alan Stokes8c840442021-11-26 15:54:30 +0000112 }
113 };
114 if let Err(e) = result {
115 warn!("Failed to deliver callback: {:?}", e);
116 }
117 }
118 });
119 }
120}
121
Alan Stokes2d2e4db2022-01-28 16:41:52 +0000122fn run_in_vm(
123 service: Strong<dyn ICompOsService>,
124 compilation_mode: CompilationMode,
125 target_dir_name: &str,
126) -> Result<ExitCode> {
Alan Stokes16fb8552022-02-10 15:07:27 +0000127 let output_root = Path::new(ODREFRESH_OUTPUT_ROOT_DIR);
Alan Stokes35bac3c2021-12-16 14:37:24 +0000128
129 // We need to remove the target directory because odrefresh running in compos will create it
130 // (and can't see the existing one, since authfs doesn't show it existing files in an output
131 // directory).
132 let target_path = output_root.join(target_dir_name);
Alan Stokesa4542ec2021-12-20 09:39:33 +0000133 if target_path.exists() {
134 remove_dir_all(&target_path)
135 .with_context(|| format!("Failed to delete {}", target_path.display()))?;
136 }
Alan Stokes35bac3c2021-12-16 14:37:24 +0000137
Alan Stokesda596932021-12-15 17:48:55 +0000138 let staging_dir = open_dir(composd_native::palette_create_odrefresh_staging_directory()?)?;
139 let system_dir = open_dir(Path::new("/system"))?;
Alan Stokes35bac3c2021-12-16 14:37:24 +0000140 let output_dir = open_dir(output_root)?;
Alan Stokesda596932021-12-15 17:48:55 +0000141
142 // Spawn a fd_server to serve the FDs.
143 let fd_server_config = FdServerConfig {
144 ro_dir_fds: vec![system_dir.as_raw_fd()],
145 rw_dir_fds: vec![staging_dir.as_raw_fd(), output_dir.as_raw_fd()],
146 ..Default::default()
147 };
148 let fd_server_raii = fd_server_config.into_fd_server()?;
149
Andrew Walbran014efb52022-02-03 17:43:11 +0000150 let zygote_arch = system_properties::read("ro.zygote")?.context("ro.zygote not set")?;
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800151 let system_server_compiler_filter =
Andrew Walbran014efb52022-02-03 17:43:11 +0000152 system_properties::read("dalvik.vm.systemservercompilerfilter")?.unwrap_or_default();
Alan Stokesda596932021-12-15 17:48:55 +0000153 let exit_code = service.odrefresh(
Alan Stokes2d2e4db2022-01-28 16:41:52 +0000154 compilation_mode,
Alan Stokesda596932021-12-15 17:48:55 +0000155 system_dir.as_raw_fd(),
156 output_dir.as_raw_fd(),
157 staging_dir.as_raw_fd(),
158 target_dir_name,
159 &zygote_arch,
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800160 &system_server_compiler_filter,
Alan Stokesda596932021-12-15 17:48:55 +0000161 )?;
162
163 drop(fd_server_raii);
Alan Stokes126fd512021-12-16 15:00:01 +0000164 ExitCode::from_i32(exit_code.into())
Alan Stokesda596932021-12-15 17:48:55 +0000165}
166
167/// Returns an owned FD of the directory. It currently returns a `File` as a FD owner, but
168/// it's better to use `std::os::unix::io::OwnedFd` once/if it becomes standard.
169fn open_dir(path: &Path) -> Result<File> {
170 OpenOptions::new()
171 .custom_flags(libc::O_DIRECTORY)
172 .read(true) // O_DIRECTORY can only be opened with read
173 .open(path)
174 .with_context(|| format!("Failed to open {:?} directory as path fd", path))
Alan Stokes8c840442021-11-26 15:54:30 +0000175}