blob: 6d096a11737c82f4665a226801a52dc98b98b4a5 [file] [log] [blame]
Alan Stokesb2cc79e2021-09-14 14:08:46 +01001/*
2 * Copyright (C) 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
17//! Simple command-line tool to drive composd for testing and debugging.
18
19use android_system_composd::{
Alan Stokes9ca14ca2021-10-20 14:25:57 +010020 aidl::android::system::composd::{
Alan Stokes6fc18372021-11-25 17:50:27 +000021 ICompilationTask::ICompilationTask,
Alan Stokes81c96f32022-04-07 14:13:19 +010022 ICompilationTaskCallback::{
23 BnCompilationTaskCallback, FailureReason::FailureReason, ICompilationTaskCallback,
24 },
Victor Hsiehbac923e2022-02-22 21:43:36 +000025 IIsolatedCompilationService::ApexSource::ApexSource,
Alan Stokes9ca14ca2021-10-20 14:25:57 +010026 IIsolatedCompilationService::IIsolatedCompilationService,
27 },
Alan Stokesdcb96022021-10-26 15:23:31 +010028 binder::{
29 wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ProcessState,
Alan Stokes6fc18372021-11-25 17:50:27 +000030 Result as BinderResult, Strong,
Alan Stokesdcb96022021-10-26 15:23:31 +010031 },
Alan Stokesb2cc79e2021-09-14 14:08:46 +010032};
Alan Stokes9ca14ca2021-10-20 14:25:57 +010033use anyhow::{bail, Context, Result};
Victor Hsieh1732c0d2022-09-12 14:36:03 -070034use clap::Parser;
Alan Stokes71403772022-06-21 14:56:28 +010035use compos_common::timeouts::TIMEOUTS;
Alan Stokes9ca14ca2021-10-20 14:25:57 +010036use std::sync::{Arc, Condvar, Mutex};
37use std::time::Duration;
Alan Stokesb2cc79e2021-09-14 14:08:46 +010038
Victor Hsieh1732c0d2022-09-12 14:36:03 -070039#[derive(Parser)]
40enum Actions {
41 /// Compile classpath for real. Output can be used after a reboot.
42 StagedApexCompile {},
43
44 /// Compile classpath in a debugging VM. Output is ignored.
45 TestCompile {
46 /// If any APEX is staged, prefer the staged version.
47 #[clap(long)]
48 prefer_staged: bool,
49 },
50}
51
Alan Stokesb2cc79e2021-09-14 14:08:46 +010052fn main() -> Result<()> {
Victor Hsieh1732c0d2022-09-12 14:36:03 -070053 let action = Actions::parse();
Alan Stokes388b88a2021-10-13 16:03:17 +010054
Alan Stokesb2cc79e2021-09-14 14:08:46 +010055 ProcessState::start_thread_pool();
56
Victor Hsieh1732c0d2022-09-12 14:36:03 -070057 match action {
58 Actions::StagedApexCompile {} => run_staged_apex_compile()?,
59 Actions::TestCompile { prefer_staged } => run_test_compile(prefer_staged)?,
Alan Stokes388b88a2021-10-13 16:03:17 +010060 }
Alan Stokesb2cc79e2021-09-14 14:08:46 +010061
62 println!("All Ok!");
63
64 Ok(())
65}
Alan Stokes9ca14ca2021-10-20 14:25:57 +010066
67struct Callback(Arc<State>);
68
69#[derive(Default)]
70struct State {
71 mutex: Mutex<Option<Outcome>>,
72 completed: Condvar,
73}
74
Alan Stokes9ca14ca2021-10-20 14:25:57 +010075enum Outcome {
76 Succeeded,
Alan Stokes81c96f32022-04-07 14:13:19 +010077 Failed(FailureReason, String),
78 TaskDied,
Alan Stokes9ca14ca2021-10-20 14:25:57 +010079}
80
81impl Interface for Callback {}
82
83impl ICompilationTaskCallback for Callback {
84 fn onSuccess(&self) -> BinderResult<()> {
85 self.0.set_outcome(Outcome::Succeeded);
86 Ok(())
87 }
88
Alan Stokes81c96f32022-04-07 14:13:19 +010089 fn onFailure(&self, reason: FailureReason, message: &str) -> BinderResult<()> {
90 self.0.set_outcome(Outcome::Failed(reason, message.to_owned()));
Alan Stokes9ca14ca2021-10-20 14:25:57 +010091 Ok(())
92 }
93}
94
95impl State {
96 fn set_outcome(&self, outcome: Outcome) {
97 let mut guard = self.mutex.lock().unwrap();
98 *guard = Some(outcome);
99 drop(guard);
100 self.completed.notify_all();
101 }
102
103 fn wait(&self, duration: Duration) -> Result<Outcome> {
Alan Stokes81c96f32022-04-07 14:13:19 +0100104 let (mut outcome, result) = self
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100105 .completed
106 .wait_timeout_while(self.mutex.lock().unwrap(), duration, |outcome| outcome.is_none())
107 .unwrap();
108 if result.timed_out() {
109 bail!("Timed out waiting for compilation")
110 }
Alan Stokes81c96f32022-04-07 14:13:19 +0100111 Ok(outcome.take().unwrap())
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100112 }
113}
114
Alan Stokes6fc18372021-11-25 17:50:27 +0000115fn run_staged_apex_compile() -> Result<()> {
116 run_async_compilation(|service, callback| service.startStagedApexCompile(callback))
117}
118
Victor Hsiehbac923e2022-02-22 21:43:36 +0000119fn run_test_compile(prefer_staged: bool) -> Result<()> {
120 let apex_source = if prefer_staged { ApexSource::PreferStaged } else { ApexSource::NoStaged };
121 run_async_compilation(|service, callback| service.startTestCompile(apex_source, callback))
Alan Stokes6fc18372021-11-25 17:50:27 +0000122}
123
124fn run_async_compilation<F>(start_compile_fn: F) -> Result<()>
125where
126 F: FnOnce(
127 &dyn IIsolatedCompilationService,
128 &Strong<dyn ICompilationTaskCallback>,
129 ) -> BinderResult<Strong<dyn ICompilationTask>>,
130{
Alan Stokesc4d5def2023-02-14 17:01:59 +0000131 if !hypervisor_props::is_any_vm_supported()? {
132 // Give up now, before trying to start composd, or we may end up waiting forever
133 // as it repeatedly starts and then aborts (b/254599807).
134 bail!("Device doesn't support protected or non-protected VMs")
135 }
136
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100137 let service = wait_for_interface::<dyn IIsolatedCompilationService>("android.system.composd")
138 .context("Failed to connect to composd service")?;
139
140 let state = Arc::new(State::default());
141 let callback = Callback(state.clone());
142 let callback = BnCompilationTaskCallback::new_binder(callback, BinderFeatures::default());
Alan Stokes6fc18372021-11-25 17:50:27 +0000143 let task = start_compile_fn(&*service, &callback).context("Compilation failed")?;
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100144
145 // Make sure composd keeps going even if we don't hold a reference to its service.
146 drop(service);
147
Alan Stokesdcb96022021-10-26 15:23:31 +0100148 let state_clone = state.clone();
149 let mut death_recipient = DeathRecipient::new(move || {
150 eprintln!("CompilationTask died");
Alan Stokes81c96f32022-04-07 14:13:19 +0100151 state_clone.set_outcome(Outcome::TaskDied);
Alan Stokesdcb96022021-10-26 15:23:31 +0100152 });
153 // Note that dropping death_recipient cancels this, so we can't use a temporary here.
154 task.as_binder().link_to_death(&mut death_recipient)?;
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100155
156 println!("Waiting");
157
Alan Stokes71403772022-06-21 14:56:28 +0100158 match state.wait(TIMEOUTS.odrefresh_max_execution_time) {
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100159 Ok(Outcome::Succeeded) => Ok(()),
Alan Stokes81c96f32022-04-07 14:13:19 +0100160 Ok(Outcome::TaskDied) => bail!("Compilation task died"),
161 Ok(Outcome::Failed(reason, message)) => {
162 bail!("Compilation failed: {:?}: {}", reason, message)
163 }
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100164 Err(e) => {
165 if let Err(e) = task.cancel() {
166 eprintln!("Failed to cancel compilation: {:?}", e);
167 }
168 Err(e)
169 }
170 }
171}
Andrew Walbranda8786d2022-12-01 14:54:27 +0000172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use clap::CommandFactory;
177
178 #[test]
179 fn verify_actions() {
180 // Check that the command parsing has been configured in a valid way.
181 Actions::command().debug_assert();
182 }
183}