1 /*
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
19 use android_system_composd::{
20 aidl::android::system::composd::{
21 ICompilationTask::ICompilationTask,
22 ICompilationTaskCallback::{
23 BnCompilationTaskCallback, FailureReason::FailureReason, ICompilationTaskCallback,
24 },
25 IIsolatedCompilationService::ApexSource::ApexSource,
26 IIsolatedCompilationService::IIsolatedCompilationService,
27 },
28 binder::{
29 wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ProcessState,
30 Result as BinderResult, Strong,
31 },
32 };
33 use anyhow::{bail, Context, Result};
34 use compos_common::timeouts::timeouts;
35 use std::sync::{Arc, Condvar, Mutex};
36 use std::time::Duration;
37
main() -> Result<()>38 fn main() -> Result<()> {
39 #[rustfmt::skip]
40 let app = clap::App::new("composd_cmd")
41 .subcommand(
42 clap::SubCommand::with_name("staged-apex-compile"))
43 .subcommand(
44 clap::SubCommand::with_name("test-compile")
45 .arg(clap::Arg::with_name("prefer-staged").long("prefer-staged")),
46 );
47 let args = app.get_matches();
48
49 ProcessState::start_thread_pool();
50
51 match args.subcommand() {
52 ("staged-apex-compile", _) => run_staged_apex_compile()?,
53 ("test-compile", Some(sub_matches)) => {
54 let prefer_staged = sub_matches.is_present("prefer-staged");
55 run_test_compile(prefer_staged)?;
56 }
57 _ => panic!("Unrecognized subcommand"),
58 }
59
60 println!("All Ok!");
61
62 Ok(())
63 }
64
65 struct Callback(Arc<State>);
66
67 #[derive(Default)]
68 struct State {
69 mutex: Mutex<Option<Outcome>>,
70 completed: Condvar,
71 }
72
73 enum Outcome {
74 Succeeded,
75 Failed(FailureReason, String),
76 TaskDied,
77 }
78
79 impl Interface for Callback {}
80
81 impl ICompilationTaskCallback for Callback {
onSuccess(&self) -> BinderResult<()>82 fn onSuccess(&self) -> BinderResult<()> {
83 self.0.set_outcome(Outcome::Succeeded);
84 Ok(())
85 }
86
onFailure(&self, reason: FailureReason, message: &str) -> BinderResult<()>87 fn onFailure(&self, reason: FailureReason, message: &str) -> BinderResult<()> {
88 self.0.set_outcome(Outcome::Failed(reason, message.to_owned()));
89 Ok(())
90 }
91 }
92
93 impl State {
set_outcome(&self, outcome: Outcome)94 fn set_outcome(&self, outcome: Outcome) {
95 let mut guard = self.mutex.lock().unwrap();
96 *guard = Some(outcome);
97 drop(guard);
98 self.completed.notify_all();
99 }
100
wait(&self, duration: Duration) -> Result<Outcome>101 fn wait(&self, duration: Duration) -> Result<Outcome> {
102 let (mut outcome, result) = self
103 .completed
104 .wait_timeout_while(self.mutex.lock().unwrap(), duration, |outcome| outcome.is_none())
105 .unwrap();
106 if result.timed_out() {
107 bail!("Timed out waiting for compilation")
108 }
109 Ok(outcome.take().unwrap())
110 }
111 }
112
run_staged_apex_compile() -> Result<()>113 fn run_staged_apex_compile() -> Result<()> {
114 run_async_compilation(|service, callback| service.startStagedApexCompile(callback))
115 }
116
run_test_compile(prefer_staged: bool) -> Result<()>117 fn run_test_compile(prefer_staged: bool) -> Result<()> {
118 let apex_source = if prefer_staged { ApexSource::PreferStaged } else { ApexSource::NoStaged };
119 run_async_compilation(|service, callback| service.startTestCompile(apex_source, callback))
120 }
121
run_async_compilation<F>(start_compile_fn: F) -> Result<()> where F: FnOnce( &dyn IIsolatedCompilationService, &Strong<dyn ICompilationTaskCallback>, ) -> BinderResult<Strong<dyn ICompilationTask>>,122 fn run_async_compilation<F>(start_compile_fn: F) -> Result<()>
123 where
124 F: FnOnce(
125 &dyn IIsolatedCompilationService,
126 &Strong<dyn ICompilationTaskCallback>,
127 ) -> BinderResult<Strong<dyn ICompilationTask>>,
128 {
129 let service = wait_for_interface::<dyn IIsolatedCompilationService>("android.system.composd")
130 .context("Failed to connect to composd service")?;
131
132 let state = Arc::new(State::default());
133 let callback = Callback(state.clone());
134 let callback = BnCompilationTaskCallback::new_binder(callback, BinderFeatures::default());
135 let task = start_compile_fn(&*service, &callback).context("Compilation failed")?;
136
137 // Make sure composd keeps going even if we don't hold a reference to its service.
138 drop(service);
139
140 let state_clone = state.clone();
141 let mut death_recipient = DeathRecipient::new(move || {
142 eprintln!("CompilationTask died");
143 state_clone.set_outcome(Outcome::TaskDied);
144 });
145 // Note that dropping death_recipient cancels this, so we can't use a temporary here.
146 task.as_binder().link_to_death(&mut death_recipient)?;
147
148 println!("Waiting");
149
150 match state.wait(timeouts()?.odrefresh_max_execution_time) {
151 Ok(Outcome::Succeeded) => Ok(()),
152 Ok(Outcome::TaskDied) => bail!("Compilation task died"),
153 Ok(Outcome::Failed(reason, message)) => {
154 bail!("Compilation failed: {:?}: {}", reason, message)
155 }
156 Err(e) => {
157 if let Err(e) = task.cancel() {
158 eprintln!("Failed to cancel compilation: {:?}", e);
159 }
160 Err(e)
161 }
162 }
163 }
164