blob: e0fed85dbb48be2c7a52b59b0611fa59e311d923 [file] [log] [blame]
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Functions for creating and collecting atoms.
16
David Brazdilf50c7a62023-04-19 14:22:42 +000017use crate::aidl::{clone_file, GLOBAL_SERVICE};
Seungjae Yoo6d265d92022-11-15 10:51:33 +090018use crate::crosvm::VmMetric;
David Brazdil1f530702022-10-03 12:18:10 +010019use crate::get_calling_uid;
David Brazdil49f96f52022-12-16 21:29:13 +000020use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000021use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000022 CpuTopology::CpuTopology,
Alan Stokes0d1ef782022-09-27 13:46:35 +010023 IVirtualMachine::IVirtualMachine,
24 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
25 VirtualMachineConfig::VirtualMachineConfig,
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000026};
27use android_system_virtualizationservice::binder::{Status, Strong};
David Brazdil49f96f52022-12-16 21:29:13 +000028use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
29 AtomVmBooted::AtomVmBooted,
30 AtomVmCreationRequested::AtomVmCreationRequested,
31 AtomVmExited::AtomVmExited,
32};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000033use anyhow::{anyhow, Result};
David Brazdil1f530702022-10-03 12:18:10 +010034use binder::ParcelFileDescriptor;
Seungjae Yooeebe6442023-04-04 13:02:46 +090035use log::{info, warn};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000036use microdroid_payload_config::VmPayloadConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000037use statslog_virtualization_rust::vm_creation_requested;
Shikha Panwarc93a42b2022-11-09 14:12:25 +000038use std::thread;
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090039use std::time::{Duration, SystemTime};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000040use zip::ZipArchive;
41
David Brazdil7d1e5ec2023-02-06 17:56:29 +000042const INVALID_NUM_CPUS: i32 = -1;
43
Alan Stokes0d1ef782022-09-27 13:46:35 +010044fn get_apex_list(config: &VirtualMachineAppConfig) -> String {
45 match &config.payload {
46 Payload::PayloadConfig(_) => String::new(),
47 Payload::ConfigPath(config_path) => {
48 let vm_payload_config = get_vm_payload_config(&config.apk, config_path);
49 if let Ok(vm_payload_config) = vm_payload_config {
50 vm_payload_config
51 .apexes
52 .iter()
53 .map(|x| x.name.clone())
54 .collect::<Vec<String>>()
55 .join(":")
56 } else {
57 "INFO: Can't get VmPayloadConfig".to_owned()
58 }
59 }
60 }
61}
62
63fn get_vm_payload_config(
64 apk_fd: &Option<ParcelFileDescriptor>,
65 config_path: &str,
66) -> Result<VmPayloadConfig> {
67 let apk = apk_fd.as_ref().ok_or_else(|| anyhow!("APK is none"))?;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000068 let apk_file = clone_file(apk)?;
69 let mut apk_zip = ZipArchive::new(&apk_file)?;
Alan Stokes0d1ef782022-09-27 13:46:35 +010070 let config_file = apk_zip.by_name(config_path)?;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000071 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
72 Ok(vm_payload_config)
73}
74
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090075fn get_duration(vm_start_timestamp: Option<SystemTime>) -> Duration {
76 match vm_start_timestamp {
77 Some(vm_start_timestamp) => vm_start_timestamp.elapsed().unwrap_or_default(),
78 None => Duration::default(),
79 }
80}
81
David Brazdil7d1e5ec2023-02-06 17:56:29 +000082// Returns the number of CPUs configured in the host system.
83// This matches how crosvm determines the number of logical cores.
84// For telemetry purposes only.
David Brazdil25e8c052023-02-17 12:53:01 +000085pub(crate) fn get_num_cpus() -> Option<usize> {
Andrew Walbranb58d1b42023-07-07 13:54:49 +010086 // SAFETY: Only integer constants passed back and forth.
David Brazdil7d1e5ec2023-02-06 17:56:29 +000087 let ret = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_CONF) };
88 if ret > 0 {
89 ret.try_into().ok()
90 } else {
91 None
92 }
93}
94
Frederick Mayle681254c2024-12-11 19:20:06 -080095fn get_num_vcpus(cpu_topology: CpuTopology, custom_vcpu_count: Option<i32>) -> i32 {
96 match cpu_topology {
97 CpuTopology::ONE_CPU => 1,
98 CpuTopology::MATCH_HOST => {
99 get_num_cpus().and_then(|v| v.try_into().ok()).unwrap_or_else(|| {
100 warn!("Failed to determine the number of CPUs in the host");
101 INVALID_NUM_CPUS
102 })
103 }
104 CpuTopology::CUSTOM => custom_vcpu_count.unwrap_or_else(|| {
105 warn!("AppConfig doesn't support CpuTopology::CUSTOM");
106 INVALID_NUM_CPUS
107 }),
108 _ => {
109 warn!("invalid CpuTopology: {cpu_topology:?}");
110 INVALID_NUM_CPUS
111 }
112 }
113}
114
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000115/// Write the stats of VMCreation to statsd
Seungjae Yoob2db3d22023-04-06 18:05:43 +0900116/// The function creates a separate thread which waits for statsd to start to push atom
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000117pub fn write_vm_creation_stats(
118 config: &VirtualMachineConfig,
119 is_protected: bool,
120 ret: &binder::Result<Strong<dyn IVirtualMachine>>,
121) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900122 if cfg!(early) {
123 info!("Writing VmCreationRequested atom for early VMs is not implemented; skipping");
124 return;
125 }
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000126 let creation_succeeded;
127 let binder_exception_code;
128 match ret {
129 Ok(_) => {
130 creation_succeeded = true;
131 binder_exception_code = Status::ok().exception_code() as i32;
132 }
133 Err(ref e) => {
134 creation_succeeded = false;
135 binder_exception_code = e.exception_code() as i32;
136 }
137 }
Frederick Mayle681254c2024-12-11 19:20:06 -0800138
139 let (vm_identifier, config_type, num_cpus, memory_mib, apexes) = match config {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100140 VirtualMachineConfig::AppConfig(config) => (
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000141 config.name.clone(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100142 vm_creation_requested::ConfigType::VirtualMachineAppConfig,
Frederick Mayle681254c2024-12-11 19:20:06 -0800143 get_num_vcpus(config.cpuTopology, None),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100144 config.memoryMib,
145 get_apex_list(config),
146 ),
147 VirtualMachineConfig::RawConfig(config) => (
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000148 config.name.clone(),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100149 vm_creation_requested::ConfigType::VirtualMachineRawConfig,
Frederick Mayle681254c2024-12-11 19:20:06 -0800150 get_num_vcpus(config.cpuTopology, Some(config.customVcpuCount)),
Alan Stokes0d1ef782022-09-27 13:46:35 +0100151 config.memoryMib,
152 String::new(),
153 ),
154 };
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000155
David Brazdil49f96f52022-12-16 21:29:13 +0000156 let atom = AtomVmCreationRequested {
David Brazdil1f530702022-10-03 12:18:10 +0100157 uid: get_calling_uid() as i32,
David Brazdil49f96f52022-12-16 21:29:13 +0000158 vmIdentifier: vm_identifier,
159 isProtected: is_protected,
160 creationSucceeded: creation_succeeded,
161 binderExceptionCode: binder_exception_code,
162 configType: config_type as i32,
163 numCpus: num_cpus,
164 memoryMib: memory_mib,
165 apexes,
166 };
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000167
Seungjae Yooeebe6442023-04-04 13:02:46 +0900168 info!("Writing VmCreationRequested atom into statsd.");
David Brazdil49f96f52022-12-16 21:29:13 +0000169 thread::spawn(move || {
170 GLOBAL_SERVICE.atomVmCreationRequested(&atom).unwrap_or_else(|e| {
171 warn!("Failed to write VmCreationRequested atom: {e}");
172 });
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000173 });
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000174}
Seungjae Yooacf559a2022-08-12 04:44:51 +0000175
176/// Write the stats of VM boot to statsd
Seungjae Yoob2db3d22023-04-06 18:05:43 +0900177/// The function creates a separate thread which waits for statsd to start to push atom
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900178pub fn write_vm_booted_stats(
179 uid: i32,
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000180 vm_identifier: &str,
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900181 vm_start_timestamp: Option<SystemTime>,
182) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900183 if cfg!(early) {
184 info!("Writing VmCreationRequested atom for early VMs is not implemented; skipping");
185 return;
186 }
187
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000188 let vm_identifier = vm_identifier.to_owned();
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900189 let duration = get_duration(vm_start_timestamp);
David Brazdil49f96f52022-12-16 21:29:13 +0000190
191 let atom = AtomVmBooted {
192 uid,
193 vmIdentifier: vm_identifier,
194 elapsedTimeMillis: duration.as_millis() as i64,
195 };
196
Seungjae Yooeebe6442023-04-04 13:02:46 +0900197 info!("Writing VmBooted atom into statsd.");
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000198 thread::spawn(move || {
David Brazdil49f96f52022-12-16 21:29:13 +0000199 GLOBAL_SERVICE.atomVmBooted(&atom).unwrap_or_else(|e| {
Seungjae Yooeebe6442023-04-04 13:02:46 +0900200 warn!("Failed to write VmBooted atom: {e}");
David Brazdil49f96f52022-12-16 21:29:13 +0000201 });
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000202 });
Seungjae Yooacf559a2022-08-12 04:44:51 +0000203}
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000204
205/// Write the stats of VM exit to statsd
Seungjae Yoob2db3d22023-04-06 18:05:43 +0900206pub fn write_vm_exited_stats_sync(
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900207 uid: i32,
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000208 vm_identifier: &str,
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900209 reason: DeathReason,
Seungjae Yoo93430e82022-12-05 16:37:42 +0900210 exit_signal: Option<i32>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900211 vm_metric: &VmMetric,
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900212) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900213 if cfg!(early) {
214 info!("Writing VmExited atom for early VMs is not implemented; skipping");
215 return;
216 }
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000217 let vm_identifier = vm_identifier.to_owned();
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900218 let elapsed_time_millis = get_duration(vm_metric.start_timestamp).as_millis() as i64;
219 let guest_time_millis = vm_metric.cpu_guest_time.unwrap_or_default();
220 let rss = vm_metric.rss.unwrap_or_default();
221
David Brazdil49f96f52022-12-16 21:29:13 +0000222 let atom = AtomVmExited {
223 uid,
224 vmIdentifier: vm_identifier,
225 elapsedTimeMillis: elapsed_time_millis,
226 deathReason: reason,
227 guestTimeMillis: guest_time_millis,
228 rssVmKb: rss.vm,
229 rssCrosvmKb: rss.crosvm,
230 exitSignal: exit_signal.unwrap_or_default(),
231 };
232
Seungjae Yooeebe6442023-04-04 13:02:46 +0900233 info!("Writing VmExited atom into statsd.");
Seungjae Yoob2db3d22023-04-06 18:05:43 +0900234 GLOBAL_SERVICE.atomVmExited(&atom).unwrap_or_else(|e| {
235 warn!("Failed to write VmExited atom: {e}");
Shikha Panwarc93a42b2022-11-09 14:12:25 +0000236 });
237}