blob: 14236ab9268ff144266907e2b64c4f44250130af [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 configurations.
18
19use anyhow::Result;
Yi Kong037bde82021-03-23 14:25:38 +080020use macaddr::MacAddr6;
Luca Stefanice7ab9a2024-01-22 19:07:38 +010021use once_cell::sync::Lazy;
Yi Kong037bde82021-03-23 14:25:38 +080022use rand::Rng;
Yi Konge3aab142021-03-02 13:58:25 +080023use serde::{Deserialize, Serialize};
24use std::error::Error;
Yi Kong34ebf872021-11-29 19:57:55 +080025use std::fs::{read_dir, remove_file};
Yi Konge3aab142021-03-02 13:58:25 +080026use std::path::Path;
27use std::str::FromStr;
28use std::time::Duration;
29
30const PROFCOLLECT_CONFIG_NAMESPACE: &str = "profcollect_native_boot";
Yi Kong037bde82021-03-23 14:25:38 +080031const PROFCOLLECT_NODE_ID_PROPERTY: &str = "persist.profcollectd.node_id";
Yi Konge3aab142021-03-02 13:58:25 +080032
Yi Kong87d0a172021-12-09 01:37:57 +080033const DEFAULT_BINARY_FILTER: &str = "^/(system|apex/.+)/(bin|lib|lib64)/.+";
Yi Kong8dffc122021-07-20 16:55:39 +080034pub const REPORT_RETENTION_SECS: u64 = 14 * 24 * 60 * 60; // 14 days.
35
Yi Kong34ebf872021-11-29 19:57:55 +080036// Static configs that cannot be changed.
Luca Stefanice7ab9a2024-01-22 19:07:38 +010037pub static TRACE_OUTPUT_DIR: Lazy<&'static Path> =
38 Lazy::new(|| Path::new("/data/misc/profcollectd/trace/"));
39pub static PROFILE_OUTPUT_DIR: Lazy<&'static Path> =
40 Lazy::new(|| Path::new("/data/misc/profcollectd/output/"));
41pub static REPORT_OUTPUT_DIR: Lazy<&'static Path> =
42 Lazy::new(|| Path::new("/data/misc/profcollectd/report/"));
43pub static CONFIG_FILE: Lazy<&'static Path> =
44 Lazy::new(|| Path::new("/data/misc/profcollectd/output/config.json"));
45pub static LOG_FILE: Lazy<&'static Path> =
46 Lazy::new(|| Path::new("/data/misc/profcollectd/output/trace.log"));
Yi Konge3aab142021-03-02 13:58:25 +080047
Yi Kong34ebf872021-11-29 19:57:55 +080048/// Dynamic configs, stored in config.json.
Yi Konge3aab142021-03-02 13:58:25 +080049#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
50pub struct Config {
51 /// Version of config file scheme, always equals to 1.
52 version: u32,
Yi Kong037bde82021-03-23 14:25:38 +080053 /// Application specific node ID.
54 pub node_id: MacAddr6,
Yi Konge3aab142021-03-02 13:58:25 +080055 /// Device build fingerprint.
56 pub build_fingerprint: String,
57 /// Interval between collections.
58 pub collection_interval: Duration,
59 /// Length of time each collection lasts for.
60 pub sampling_period: Duration,
61 /// An optional filter to limit which binaries to or not to profile.
62 pub binary_filter: String,
Yi Kong581aa3a2021-11-24 00:19:30 +080063 /// Maximum size of the trace directory.
64 pub max_trace_limit: u64,
Yi Konge3aab142021-03-02 13:58:25 +080065}
66
67impl Config {
68 pub fn from_env() -> Result<Self> {
69 Ok(Config {
70 version: 1,
Yi Kong037bde82021-03-23 14:25:38 +080071 node_id: get_or_initialise_node_id()?,
72 build_fingerprint: get_build_fingerprint()?,
Yi Konge3aab142021-03-02 13:58:25 +080073 collection_interval: Duration::from_secs(get_device_config(
74 "collection_interval",
75 600,
76 )?),
77 sampling_period: Duration::from_millis(get_device_config("sampling_period", 500)?),
Yi Kong87d0a172021-12-09 01:37:57 +080078 binary_filter: get_device_config("binary_filter", DEFAULT_BINARY_FILTER.to_string())?,
Yi Kong581aa3a2021-11-24 00:19:30 +080079 max_trace_limit: get_device_config(
80 "max_trace_limit",
81 /* 512MB */ 512 * 1024 * 1024,
82 )?,
Yi Konge3aab142021-03-02 13:58:25 +080083 })
84 }
85}
86
87impl ToString for Config {
88 fn to_string(&self) -> String {
89 serde_json::to_string(self).expect("Failed to deserialise configuration.")
90 }
91}
92
93impl FromStr for Config {
94 type Err = serde_json::Error;
95 fn from_str(s: &str) -> Result<Self, Self::Err> {
96 serde_json::from_str::<Config>(s)
97 }
98}
99
Yi Kong037bde82021-03-23 14:25:38 +0800100fn get_or_initialise_node_id() -> Result<MacAddr6> {
Chris Wailes8f571e12021-07-27 16:04:09 -0700101 let mut node_id = get_property(PROFCOLLECT_NODE_ID_PROPERTY, MacAddr6::nil())?;
Yi Kong037bde82021-03-23 14:25:38 +0800102 if node_id.is_nil() {
103 node_id = generate_random_node_id();
Chris Wailes8f571e12021-07-27 16:04:09 -0700104 set_property(PROFCOLLECT_NODE_ID_PROPERTY, node_id)?;
Yi Kong037bde82021-03-23 14:25:38 +0800105 }
106
107 Ok(node_id)
Yi Konge3aab142021-03-02 13:58:25 +0800108}
109
Yi Kong037bde82021-03-23 14:25:38 +0800110fn get_build_fingerprint() -> Result<String> {
111 get_property("ro.build.fingerprint", "unknown".to_string())
112}
113
114fn get_device_config<T>(key: &str, default_value: T) -> Result<T>
Yi Konge3aab142021-03-02 13:58:25 +0800115where
116 T: FromStr + ToString,
117 T::Err: Error + Send + Sync + 'static,
118{
Yi Kong037bde82021-03-23 14:25:38 +0800119 let default_value = default_value.to_string();
Luca Stefanice7ab9a2024-01-22 19:07:38 +0100120 let config =
121 flags_rust::GetServerConfigurableFlag(PROFCOLLECT_CONFIG_NAMESPACE, key, &default_value);
Yi Konge3aab142021-03-02 13:58:25 +0800122 Ok(T::from_str(&config)?)
123}
Yi Kong037bde82021-03-23 14:25:38 +0800124
125fn get_property<T>(key: &str, default_value: T) -> Result<T>
126where
127 T: FromStr + ToString,
128 T::Err: Error + Send + Sync + 'static,
129{
130 let default_value = default_value.to_string();
Andrew Walbran0aaa3a22022-02-07 12:36:22 +0000131 let value = rustutils::system_properties::read(key).unwrap_or(None).unwrap_or(default_value);
Yi Kong037bde82021-03-23 14:25:38 +0800132 Ok(T::from_str(&value)?)
133}
134
Joel Galenson0ab91112021-07-20 14:51:42 -0700135fn set_property<T>(key: &str, value: T) -> Result<()>
Yi Kong037bde82021-03-23 14:25:38 +0800136where
137 T: ToString,
138{
139 let value = value.to_string();
Andrew Walbran0aaa3a22022-02-07 12:36:22 +0000140 Ok(rustutils::system_properties::write(key, &value)?)
Yi Kong037bde82021-03-23 14:25:38 +0800141}
142
143fn generate_random_node_id() -> MacAddr6 {
144 let mut node_id = rand::thread_rng().gen::<[u8; 6]>();
145 node_id[0] |= 0x1;
146 MacAddr6::from(node_id)
147}
Yi Kong34ebf872021-11-29 19:57:55 +0800148
149pub fn clear_data() -> Result<()> {
150 fn remove_files(path: &Path) -> Result<()> {
151 read_dir(path)?
152 .filter_map(|e| e.ok())
153 .map(|e| e.path())
Yabin Cuif1d91d22023-04-27 12:50:59 -0700154 .filter(|e| e.is_file() && e != *LOG_FILE)
Yi Kong34ebf872021-11-29 19:57:55 +0800155 .try_for_each(remove_file)?;
156 Ok(())
157 }
158
159 remove_files(&TRACE_OUTPUT_DIR)?;
160 remove_files(&PROFILE_OUTPUT_DIR)?;
161 remove_files(&REPORT_OUTPUT_DIR)?;
162 Ok(())
163}