summaryrefslogtreecommitdiff
path: root/profcollectd/libprofcollectd
diff options
context:
space:
mode:
Diffstat (limited to 'profcollectd/libprofcollectd')
-rw-r--r--profcollectd/libprofcollectd/Android.bp3
-rw-r--r--profcollectd/libprofcollectd/config.rs25
-rw-r--r--profcollectd/libprofcollectd/lib.rs14
-rw-r--r--profcollectd/libprofcollectd/logging_trace_provider.rs56
-rw-r--r--profcollectd/libprofcollectd/scheduler.rs36
-rw-r--r--profcollectd/libprofcollectd/service.rs13
-rw-r--r--profcollectd/libprofcollectd/simpleperf_etm_trace_provider.rs6
-rw-r--r--profcollectd/libprofcollectd/trace_provider.rs19
8 files changed, 148 insertions, 24 deletions
diff --git a/profcollectd/libprofcollectd/Android.bp b/profcollectd/libprofcollectd/Android.bp
index 2e37af9e..7fb1b567 100644
--- a/profcollectd/libprofcollectd/Android.bp
+++ b/profcollectd/libprofcollectd/Android.bp
@@ -60,4 +60,7 @@ rust_library {
"libsimpleperf_profcollect_rust",
],
shared_libs: ["libsimpleperf_profcollect"],
+
+ // Enable 'test' feature for more verbose logging and the logging trace provider.
+ // features: ["test"],
}
diff --git a/profcollectd/libprofcollectd/config.rs b/profcollectd/libprofcollectd/config.rs
index e8afb37f..902b5b5e 100644
--- a/profcollectd/libprofcollectd/config.rs
+++ b/profcollectd/libprofcollectd/config.rs
@@ -22,6 +22,7 @@ use macaddr::MacAddr6;
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::error::Error;
+use std::fs::{read_dir, remove_file};
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
@@ -31,6 +32,7 @@ const PROFCOLLECT_NODE_ID_PROPERTY: &str = "persist.profcollectd.node_id";
pub const REPORT_RETENTION_SECS: u64 = 14 * 24 * 60 * 60; // 14 days.
+// Static configs that cannot be changed.
lazy_static! {
pub static ref TRACE_OUTPUT_DIR: &'static Path = Path::new("/data/misc/profcollectd/trace/");
pub static ref PROFILE_OUTPUT_DIR: &'static Path = Path::new("/data/misc/profcollectd/output/");
@@ -42,6 +44,7 @@ lazy_static! {
Path::new("/data/misc/profcollectd/output/config.json");
}
+/// Dynamic configs, stored in config.json.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct Config {
/// Version of config file scheme, always equals to 1.
@@ -56,6 +59,8 @@ pub struct Config {
pub sampling_period: Duration,
/// An optional filter to limit which binaries to or not to profile.
pub binary_filter: String,
+ /// Maximum size of the trace directory.
+ pub max_trace_limit: u64,
}
impl Config {
@@ -70,6 +75,10 @@ impl Config {
)?),
sampling_period: Duration::from_millis(get_device_config("sampling_period", 500)?),
binary_filter: get_device_config("binary_filter", "".to_string())?,
+ max_trace_limit: get_device_config(
+ "max_trace_limit",
+ /* 512MB */ 512 * 1024 * 1024,
+ )?,
})
}
}
@@ -138,3 +147,19 @@ fn generate_random_node_id() -> MacAddr6 {
node_id[0] |= 0x1;
MacAddr6::from(node_id)
}
+
+pub fn clear_data() -> Result<()> {
+ fn remove_files(path: &Path) -> Result<()> {
+ read_dir(path)?
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|e| e.is_file())
+ .try_for_each(remove_file)?;
+ Ok(())
+ }
+
+ remove_files(&TRACE_OUTPUT_DIR)?;
+ remove_files(&PROFILE_OUTPUT_DIR)?;
+ remove_files(&REPORT_OUTPUT_DIR)?;
+ Ok(())
+}
diff --git a/profcollectd/libprofcollectd/lib.rs b/profcollectd/libprofcollectd/lib.rs
index aacbf8e3..5892e259 100644
--- a/profcollectd/libprofcollectd/lib.rs
+++ b/profcollectd/libprofcollectd/lib.rs
@@ -23,6 +23,9 @@ mod service;
mod simpleperf_etm_trace_provider;
mod trace_provider;
+#[cfg(feature = "test")]
+mod logging_trace_provider;
+
use anyhow::{Context, Result};
use profcollectd_aidl_interface::aidl::com::android::server::profcollect::IProfCollectd::{
self, BnProfCollectd,
@@ -88,11 +91,16 @@ pub fn report() -> Result<String> {
Ok(get_profcollectd_service()?.report()?)
}
+/// Clear all local data.
+pub fn reset() -> Result<()> {
+ config::clear_data()?;
+ Ok(())
+}
+
/// Inits logging for Android
pub fn init_logging() {
+ let min_log_level = if cfg!(feature = "test") { log::Level::Info } else { log::Level::Error };
android_logger::init_once(
- android_logger::Config::default()
- .with_tag("profcollectd")
- .with_min_level(log::Level::Error),
+ android_logger::Config::default().with_tag("profcollectd").with_min_level(min_log_level),
);
}
diff --git a/profcollectd/libprofcollectd/logging_trace_provider.rs b/profcollectd/libprofcollectd/logging_trace_provider.rs
new file mode 100644
index 00000000..1325855d
--- /dev/null
+++ b/profcollectd/libprofcollectd/logging_trace_provider.rs
@@ -0,0 +1,56 @@
+//
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+//! Logging trace provider for development and testing purposes.
+
+use anyhow::Result;
+use std::path::Path;
+use std::time::Duration;
+use trace_provider::TraceProvider;
+
+use crate::trace_provider;
+
+static LOGGING_TRACEFILE_EXTENSION: &str = "loggingtrace";
+
+pub struct LoggingTraceProvider {}
+
+impl TraceProvider for LoggingTraceProvider {
+ fn get_name(&self) -> &'static str {
+ "logging"
+ }
+
+ fn trace(&self, trace_dir: &Path, tag: &str, sampling_period: &Duration) {
+ let trace_file = trace_provider::get_path(trace_dir, tag, LOGGING_TRACEFILE_EXTENSION);
+
+ log::info!(
+ "Trace event triggered, tag {}, sampling for {}ms, saving to {}",
+ tag,
+ sampling_period.as_millis(),
+ trace_file.display()
+ );
+ }
+
+ fn process(&self, _trace_dir: &Path, _profile_dir: &Path) -> Result<()> {
+ log::info!("Process event triggered");
+ Ok(())
+ }
+}
+
+impl LoggingTraceProvider {
+ pub fn supported() -> bool {
+ true
+ }
+}
diff --git a/profcollectd/libprofcollectd/scheduler.rs b/profcollectd/libprofcollectd/scheduler.rs
index cfd0381f..b83bc457 100644
--- a/profcollectd/libprofcollectd/scheduler.rs
+++ b/profcollectd/libprofcollectd/scheduler.rs
@@ -16,6 +16,8 @@
//! ProfCollect tracing scheduler.
+use std::fs;
+use std::path::Path;
use std::sync::mpsc::{sync_channel, SyncSender};
use std::sync::Arc;
use std::sync::Mutex;
@@ -59,11 +61,13 @@ impl Scheduler {
Ok(_) => break,
Err(_) => {
// Did not receive a termination signal, initiate trace event.
- trace_provider.lock().unwrap().trace(
- &TRACE_OUTPUT_DIR,
- "periodic",
- &config.sampling_period,
- );
+ if check_space_limit(*TRACE_OUTPUT_DIR, &config).unwrap() {
+ trace_provider.lock().unwrap().trace(
+ &TRACE_OUTPUT_DIR,
+ "periodic",
+ &config.sampling_period,
+ );
+ }
}
}
}
@@ -83,7 +87,9 @@ impl Scheduler {
pub fn one_shot(&self, config: &Config, tag: &str) -> Result<()> {
let trace_provider = self.trace_provider.clone();
- trace_provider.lock().unwrap().trace(&TRACE_OUTPUT_DIR, tag, &config.sampling_period);
+ if check_space_limit(*TRACE_OUTPUT_DIR, config)? {
+ trace_provider.lock().unwrap().trace(&TRACE_OUTPUT_DIR, tag, &config.sampling_period);
+ }
Ok(())
}
@@ -106,3 +112,21 @@ impl Scheduler {
self.trace_provider.lock().unwrap().get_name()
}
}
+
+/// Run if space usage is under limit.
+fn check_space_limit(path: &Path, config: &Config) -> Result<bool> {
+ let ret = dir_size(path)? <= config.max_trace_limit;
+ if !ret {
+ log::error!("trace storage exhausted.");
+ }
+ Ok(ret)
+}
+
+/// Returns the size of a directory, non-recursive.
+fn dir_size(path: &Path) -> Result<u64> {
+ fs::read_dir(path)?.try_fold(0, |acc, file| {
+ let metadata = file?.metadata()?;
+ let size = if metadata.is_file() { metadata.len() } else { 0 };
+ Ok(acc + size)
+ })
+}
diff --git a/profcollectd/libprofcollectd/service.rs b/profcollectd/libprofcollectd/service.rs
index 04f30f89..a7fdce73 100644
--- a/profcollectd/libprofcollectd/service.rs
+++ b/profcollectd/libprofcollectd/service.rs
@@ -21,15 +21,15 @@ use binder::public_api::Result as BinderResult;
use binder::Status;
use profcollectd_aidl_interface::aidl::com::android::server::profcollect::IProfCollectd::IProfCollectd;
use std::ffi::CString;
-use std::fs::{copy, create_dir, read_dir, read_to_string, remove_dir_all, remove_file, write};
+use std::fs::{copy, read_dir, read_to_string, remove_file, write};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
use crate::config::{
- Config, BETTERBUG_CACHE_DIR_PREFIX, BETTERBUG_CACHE_DIR_SUFFIX, CONFIG_FILE,
- PROFILE_OUTPUT_DIR, REPORT_OUTPUT_DIR, REPORT_RETENTION_SECS, TRACE_OUTPUT_DIR,
+ clear_data, Config, BETTERBUG_CACHE_DIR_PREFIX, BETTERBUG_CACHE_DIR_SUFFIX, CONFIG_FILE,
+ PROFILE_OUTPUT_DIR, REPORT_OUTPUT_DIR, REPORT_RETENTION_SECS,
};
use crate::report::{get_report_ts, pack_report};
use crate::scheduler::Scheduler;
@@ -147,11 +147,8 @@ impl ProfcollectdBinderService {
.is_none();
if config_changed {
- log::info!("Config change detected, clearing traces.");
- remove_dir_all(*PROFILE_OUTPUT_DIR)?;
- remove_dir_all(*TRACE_OUTPUT_DIR)?;
- create_dir(*PROFILE_OUTPUT_DIR)?;
- create_dir(*TRACE_OUTPUT_DIR)?;
+ log::info!("Config change detected, resetting profcollect.");
+ clear_data()?;
write(*CONFIG_FILE, &new_config.to_string())?;
}
diff --git a/profcollectd/libprofcollectd/simpleperf_etm_trace_provider.rs b/profcollectd/libprofcollectd/simpleperf_etm_trace_provider.rs
index 2038a5be..d3baaa36 100644
--- a/profcollectd/libprofcollectd/simpleperf_etm_trace_provider.rs
+++ b/profcollectd/libprofcollectd/simpleperf_etm_trace_provider.rs
@@ -35,12 +35,10 @@ impl TraceProvider for SimpleperfEtmTraceProvider {
}
fn trace(&self, trace_dir: &Path, tag: &str, sampling_period: &Duration) {
- let mut trace_file = PathBuf::from(trace_dir);
- trace_file.push(trace_provider::construct_file_name(tag));
- trace_file.set_extension(ETM_TRACEFILE_EXTENSION);
+ let trace_file = trace_provider::get_path(trace_dir, tag, ETM_TRACEFILE_EXTENSION);
simpleperf_profcollect::record(
- &trace_file,
+ &*trace_file,
sampling_period,
simpleperf_profcollect::RecordScope::BOTH,
);
diff --git a/profcollectd/libprofcollectd/trace_provider.rs b/profcollectd/libprofcollectd/trace_provider.rs
index ed0d56f5..44d4cee9 100644
--- a/profcollectd/libprofcollectd/trace_provider.rs
+++ b/profcollectd/libprofcollectd/trace_provider.rs
@@ -18,12 +18,15 @@
use anyhow::{anyhow, Result};
use chrono::Utc;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::simpleperf_etm_trace_provider::SimpleperfEtmTraceProvider;
+#[cfg(feature = "test")]
+use crate::logging_trace_provider::LoggingTraceProvider;
+
pub trait TraceProvider {
fn get_name(&self) -> &'static str;
fn trace(&self, trace_dir: &Path, tag: &str, sampling_period: &Duration);
@@ -36,9 +39,19 @@ pub fn get_trace_provider() -> Result<Arc<Mutex<dyn TraceProvider + Send>>> {
return Ok(Arc::new(Mutex::new(SimpleperfEtmTraceProvider {})));
}
+ #[cfg(feature = "test")]
+ if LoggingTraceProvider::supported() {
+ log::info!("logging trace provider registered.");
+ return Ok(Arc::new(Mutex::new(LoggingTraceProvider {})));
+ }
+
Err(anyhow!("No trace provider found for this device."))
}
-pub fn construct_file_name(tag: &str) -> String {
- format!("{}_{}", Utc::now().format("%Y%m%d-%H%M%S"), tag)
+pub fn get_path(dir: &Path, tag: &str, ext: &str) -> Box<Path> {
+ let filename = format!("{}_{}", Utc::now().format("%Y%m%d-%H%M%S"), tag);
+ let mut trace_file = PathBuf::from(dir);
+ trace_file.push(filename);
+ trace_file.set_extension(ext);
+ trace_file.into_boxed_path()
}