• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //! ProfCollect Binder service implementation.
18 
19 use anyhow::{anyhow, Context, Error, Result};
20 use binder::Result as BinderResult;
21 use binder::{SpIBinder, Status};
22 use profcollectd_aidl_interface::aidl::com::android::server::profcollect::IProfCollectd::IProfCollectd;
23 use profcollectd_aidl_interface::aidl::com::android::server::profcollect::IProviderStatusCallback::IProviderStatusCallback;
24 use std::ffi::CString;
25 use std::fs::{read_dir, read_to_string, remove_file, write};
26 use std::str::FromStr;
27 use std::sync::{Mutex, MutexGuard};
28 use std::time::Duration;
29 
30 use crate::config::{
31     clear_data, Config, CONFIG_FILE, PROFILE_OUTPUT_DIR, REPORT_OUTPUT_DIR, REPORT_RETENTION_SECS,
32 };
33 use crate::report::{get_report_ts, pack_report};
34 use crate::scheduler::Scheduler;
35 
err_to_binder_status(msg: Error) -> Status36 pub fn err_to_binder_status(msg: Error) -> Status {
37     let msg = format!("{:#?}", msg);
38     let msg = CString::new(msg).expect("Failed to convert to CString");
39     Status::new_service_specific_error(1, Some(&msg))
40 }
41 
42 pub struct ProfcollectdBinderService {
43     lock: Mutex<Lock>,
44 }
45 
46 struct Lock {
47     config: Config,
48     scheduler: Scheduler,
49 }
50 
51 impl binder::Interface for ProfcollectdBinderService {}
52 
53 impl IProfCollectd for ProfcollectdBinderService {
trace_system(&self, tag: &str) -> BinderResult<()>54     fn trace_system(&self, tag: &str) -> BinderResult<()> {
55         let lock = &mut *self.lock();
56         lock.scheduler
57             .trace_system(&lock.config, tag)
58             .context("Failed to perform system-wide trace.")
59             .map_err(err_to_binder_status)
60     }
trace_process(&self, tag: &str, process: &str, duration: f32) -> BinderResult<()>61     fn trace_process(&self, tag: &str, process: &str, duration: f32) -> BinderResult<()> {
62         let lock = &mut *self.lock();
63         lock.scheduler
64             .trace_process(&lock.config, tag, process, duration)
65             .context("Failed to perform process trace.")
66             .map_err(err_to_binder_status)
67     }
process(&self) -> BinderResult<()>68     fn process(&self) -> BinderResult<()> {
69         let lock = &mut *self.lock();
70         lock.scheduler
71             .process(&lock.config)
72             .context("Failed to process profiles.")
73             .map_err(err_to_binder_status)
74     }
report(&self, usage_setting: i32) -> BinderResult<String>75     fn report(&self, usage_setting: i32) -> BinderResult<String> {
76         self.process()?;
77 
78         let lock = &mut *self.lock();
79         pack_report(&PROFILE_OUTPUT_DIR, &REPORT_OUTPUT_DIR, &lock.config, usage_setting)
80             .context("Failed to create profile report.")
81             .map_err(err_to_binder_status)
82     }
get_supported_provider(&self) -> BinderResult<String>83     fn get_supported_provider(&self) -> BinderResult<String> {
84         Ok(self.lock().scheduler.get_trace_provider_name().to_string())
85     }
86 
registerProviderStatusCallback( &self, cb: &binder::Strong<(dyn IProviderStatusCallback)>, ) -> BinderResult<()>87     fn registerProviderStatusCallback(
88         &self,
89         cb: &binder::Strong<(dyn IProviderStatusCallback)>,
90     ) -> BinderResult<()> {
91         if self.lock().scheduler.is_provider_ready() {
92             if let Err(e) = cb.onProviderReady() {
93                 log::error!("Failed to call ProviderStatusCallback {:?}", e);
94             }
95             return Ok(());
96         }
97 
98         let cb_binder: SpIBinder = cb.as_binder();
99         self.lock().scheduler.register_provider_ready_callback(Box::new(move || {
100             if let Ok(cb) = cb_binder.into_interface::<dyn IProviderStatusCallback>() {
101                 if let Err(e) = cb.onProviderReady() {
102                     log::error!("Failed to call ProviderStatusCallback {:?}", e)
103                 }
104             } else {
105                 log::error!("SpIBinder is not a IProviderStatusCallback.");
106             }
107         }));
108         Ok(())
109     }
110 }
111 
112 impl ProfcollectdBinderService {
new() -> Result<Self>113     pub fn new() -> Result<Self> {
114         let new_scheduler = Scheduler::new()?;
115         let new_config = Config::from_env()?;
116 
117         let config_changed = read_to_string(*CONFIG_FILE)
118             .ok()
119             .and_then(|s| Config::from_str(&s).ok())
120             .filter(|c| new_config == *c)
121             .is_none();
122 
123         if config_changed {
124             log::info!("Config change detected, resetting profcollect.");
125             clear_data()?;
126 
127             write(*CONFIG_FILE, new_config.to_string())?;
128             new_scheduler.clear_trace_log()?;
129         }
130 
131         // Clear profile reports out of rentention period.
132         for report in read_dir(*REPORT_OUTPUT_DIR)? {
133             let report = report?.path();
134             let report_name = report
135                 .file_stem()
136                 .and_then(|f| f.to_str())
137                 .ok_or_else(|| anyhow!("Malformed path {}", report.display()))?;
138             let report_ts = get_report_ts(report_name);
139             if let Err(e) = report_ts {
140                 log::error!(
141                     "Cannot decode creation timestamp for report {}, caused by {}, deleting",
142                     report_name,
143                     e
144                 );
145                 remove_file(report)?;
146                 continue;
147             }
148             let report_age = report_ts.unwrap().elapsed()?;
149             if report_age > Duration::from_secs(REPORT_RETENTION_SECS) {
150                 log::info!("Report {} past rentention period, deleting", report_name);
151                 remove_file(report)?;
152             }
153         }
154 
155         Ok(ProfcollectdBinderService {
156             lock: Mutex::new(Lock { scheduler: new_scheduler, config: new_config }),
157         })
158     }
159 
lock(&self) -> MutexGuard<Lock>160     fn lock(&self) -> MutexGuard<Lock> {
161         self.lock.lock().unwrap()
162     }
163 }
164