blob: 5558f581d564a114856acc68e297fa97071a7d11 [file] [log] [blame]
Yi Konge3aab142021-03-02 13:58:25 +08001//
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 tracing scheduler.
18
Yi Kong581aa3a2021-11-24 00:19:30 +080019use std::fs;
Yabin Cuif158a752022-01-10 15:35:59 -080020use std::mem;
Yi Kong581aa3a2021-11-24 00:19:30 +080021use std::path::Path;
Yi Konge3aab142021-03-02 13:58:25 +080022use std::sync::mpsc::{sync_channel, SyncSender};
23use std::sync::Arc;
24use std::sync::Mutex;
25use std::thread;
Yabin Cuif158a752022-01-10 15:35:59 -080026use std::time::{Duration, Instant};
Yi Konge3aab142021-03-02 13:58:25 +080027
Yabin Cuif1d91d22023-04-27 12:50:59 -070028use crate::config::{Config, LOG_FILE, PROFILE_OUTPUT_DIR, TRACE_OUTPUT_DIR};
Yi Konge3aab142021-03-02 13:58:25 +080029use crate::trace_provider::{self, TraceProvider};
30use anyhow::{anyhow, ensure, Context, Result};
31
32pub struct Scheduler {
33 /// Signal to terminate the periodic collection worker thread, None if periodic collection is
34 /// not scheduled.
35 termination_ch: Option<SyncSender<()>>,
36 /// The preferred trace provider for the system.
37 trace_provider: Arc<Mutex<dyn TraceProvider + Send>>,
Yabin Cuif158a752022-01-10 15:35:59 -080038 provider_ready_callbacks: Arc<Mutex<Vec<Box<dyn FnOnce() + Send>>>>,
Yi Konge3aab142021-03-02 13:58:25 +080039}
40
41impl Scheduler {
42 pub fn new() -> Result<Self> {
43 let p = trace_provider::get_trace_provider()?;
Yabin Cuif1d91d22023-04-27 12:50:59 -070044 p.lock().map_err(|e| anyhow!(e.to_string()))?.set_log_file(&LOG_FILE);
Yabin Cuif158a752022-01-10 15:35:59 -080045 Ok(Scheduler {
46 termination_ch: None,
47 trace_provider: p,
48 provider_ready_callbacks: Arc::new(Mutex::new(Vec::new())),
49 })
Yi Konge3aab142021-03-02 13:58:25 +080050 }
51
52 fn is_scheduled(&self) -> bool {
53 self.termination_ch.is_some()
54 }
55
56 pub fn schedule_periodic(&mut self, config: &Config) -> Result<()> {
57 ensure!(!self.is_scheduled(), "Already scheduled.");
58
59 let (sender, receiver) = sync_channel(1);
60 self.termination_ch = Some(sender);
61
62 // Clone config and trace_provider ARC for the worker thread.
63 let config = config.clone();
64 let trace_provider = self.trace_provider.clone();
65
66 thread::spawn(move || {
67 loop {
68 match receiver.recv_timeout(config.collection_interval) {
69 Ok(_) => break,
70 Err(_) => {
71 // Did not receive a termination signal, initiate trace event.
Chris Wailes56a7a422022-11-16 15:49:28 -080072 if check_space_limit(&TRACE_OUTPUT_DIR, &config).unwrap() {
Yi Kong581aa3a2021-11-24 00:19:30 +080073 trace_provider.lock().unwrap().trace(
74 &TRACE_OUTPUT_DIR,
75 "periodic",
76 &config.sampling_period,
Yabin Cuifc1f1782023-05-02 15:12:32 -070077 &config.binary_filter,
Yi Kong581aa3a2021-11-24 00:19:30 +080078 );
79 }
Yi Konge3aab142021-03-02 13:58:25 +080080 }
81 }
82 }
83 });
84 Ok(())
85 }
86
87 pub fn terminate_periodic(&mut self) -> Result<()> {
88 self.termination_ch
89 .as_ref()
90 .ok_or_else(|| anyhow!("Not scheduled"))?
91 .send(())
92 .context("Scheduler worker disappeared.")?;
93 self.termination_ch = None;
94 Ok(())
95 }
96
97 pub fn one_shot(&self, config: &Config, tag: &str) -> Result<()> {
98 let trace_provider = self.trace_provider.clone();
Chris Wailes56a7a422022-11-16 15:49:28 -080099 if check_space_limit(&TRACE_OUTPUT_DIR, config)? {
Yabin Cuifc1f1782023-05-02 15:12:32 -0700100 trace_provider.lock().unwrap().trace(
101 &TRACE_OUTPUT_DIR,
102 tag,
103 &config.sampling_period,
104 &config.binary_filter,
105 );
Yi Kong581aa3a2021-11-24 00:19:30 +0800106 }
Yi Konge3aab142021-03-02 13:58:25 +0800107 Ok(())
108 }
109
Yi Kong87d0a172021-12-09 01:37:57 +0800110 pub fn process(&self, config: &Config) -> Result<()> {
Yi Konge3aab142021-03-02 13:58:25 +0800111 let trace_provider = self.trace_provider.clone();
Yi Kongfd24c6e2021-12-05 13:17:39 +0800112 trace_provider
113 .lock()
114 .unwrap()
Yi Kong87d0a172021-12-09 01:37:57 +0800115 .process(&TRACE_OUTPUT_DIR, &PROFILE_OUTPUT_DIR, &config.binary_filter)
Yi Kongfd24c6e2021-12-05 13:17:39 +0800116 .context("Failed to process profiles.")?;
Yi Konge3aab142021-03-02 13:58:25 +0800117 Ok(())
118 }
119
120 pub fn get_trace_provider_name(&self) -> &'static str {
121 self.trace_provider.lock().unwrap().get_name()
122 }
Yabin Cuif158a752022-01-10 15:35:59 -0800123
124 pub fn is_provider_ready(&self) -> bool {
125 self.trace_provider.lock().unwrap().is_ready()
126 }
127
128 pub fn register_provider_ready_callback(&self, cb: Box<dyn FnOnce() + Send>) {
129 let mut locked_callbacks = self.provider_ready_callbacks.lock().unwrap();
130 locked_callbacks.push(cb);
131 if locked_callbacks.len() == 1 {
132 self.start_thread_waiting_for_provider_ready();
133 }
134 }
135
136 fn start_thread_waiting_for_provider_ready(&self) {
137 let provider = self.trace_provider.clone();
138 let callbacks = self.provider_ready_callbacks.clone();
139
140 thread::spawn(move || {
141 let start_time = Instant::now();
142 loop {
143 let elapsed = Instant::now().duration_since(start_time);
144 if provider.lock().unwrap().is_ready() {
145 break;
146 }
147 // Decide check period based on how long we have waited:
148 // For the first 10s waiting, check every 100ms (likely to work on EVT devices).
149 // For the first 10m waiting, check every 10s (likely to work on DVT devices).
150 // For others, check every 10m.
151 let sleep_duration = if elapsed < Duration::from_secs(10) {
152 Duration::from_millis(100)
153 } else if elapsed < Duration::from_secs(60 * 10) {
154 Duration::from_secs(10)
155 } else {
156 Duration::from_secs(60 * 10)
157 };
158 thread::sleep(sleep_duration);
159 }
160
161 let mut locked_callbacks = callbacks.lock().unwrap();
162 let v = mem::take(&mut *locked_callbacks);
163 for cb in v {
164 cb();
165 }
166 });
167 }
Yabin Cuif1d91d22023-04-27 12:50:59 -0700168
169 pub fn clear_trace_log(&self) -> Result<()> {
170 let provider = self.trace_provider.lock().map_err(|e| anyhow!(e.to_string()))?;
171 provider.reset_log_file();
172 let mut result = Ok(());
173 if LOG_FILE.exists() {
174 result = fs::remove_file(*LOG_FILE).map_err(|e| anyhow!(e));
175 }
176 provider.set_log_file(&LOG_FILE);
177 result
178 }
Yi Konge3aab142021-03-02 13:58:25 +0800179}
Yi Kong581aa3a2021-11-24 00:19:30 +0800180
181/// Run if space usage is under limit.
182fn check_space_limit(path: &Path, config: &Config) -> Result<bool> {
Yi Kongc0065852021-12-14 15:57:01 +0800183 // Returns the size of a directory, non-recursive.
184 let dir_size = |path| -> Result<u64> {
185 fs::read_dir(path)?.try_fold(0, |acc, file| {
186 let metadata = file?.metadata()?;
187 let size = if metadata.is_file() { metadata.len() } else { 0 };
188 Ok(acc + size)
189 })
190 };
Yi Kong581aa3a2021-11-24 00:19:30 +0800191
Yi Kongc0065852021-12-14 15:57:01 +0800192 if dir_size(path)? > config.max_trace_limit {
193 log::error!("trace storage exhausted.");
194 return Ok(false);
195 }
196 Ok(true)
Yi Kong581aa3a2021-11-24 00:19:30 +0800197}