blob: f1289e8d37a3668485f9a694aa2359ae822a38d1 [file] [log] [blame]
Alan Stokesa2869d22021-09-22 09:06:41 +01001/*
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
Alan Stokes6b2d0a82021-09-29 11:30:39 +010017//! Manages running instances of the CompOS VM. At most one instance should be running at
18//! a time, started on demand.
Alan Stokesa2869d22021-09-22 09:06:41 +010019
Alan Stokes6b2d0a82021-09-29 11:30:39 +010020use crate::instance_starter::{CompOsInstance, InstanceStarter};
21use android_system_virtualizationservice::aidl::android::system::virtualizationservice;
Victor Hsieh616f8222022-01-14 13:06:32 -080022use anyhow::{bail, Result};
Alan Stokes6b2d0a82021-09-29 11:30:39 +010023use compos_aidl_interface::binder::Strong;
Alan Stokesd21764c2021-10-25 15:33:40 +010024use compos_common::compos_client::VmParameters;
Jiyong Park165921b2022-01-14 00:49:33 +090025use compos_common::{
Alan Stokes6542fdd2022-02-17 15:21:46 +000026 CURRENT_INSTANCE_DIR, DEX2OAT_CPU_SET_PROP_NAME, DEX2OAT_THREADS_PROP_NAME,
Jiyong Park165921b2022-01-14 00:49:33 +090027 PREFER_STAGED_VM_CONFIG_PATH, TEST_INSTANCE_DIR,
28};
29use rustutils::system_properties;
30use std::num::NonZeroU32;
31use std::str::FromStr;
Alan Stokesa2869d22021-09-22 09:06:41 +010032use std::sync::{Arc, Mutex, Weak};
Alan Stokes6b2d0a82021-09-29 11:30:39 +010033use virtualizationservice::IVirtualizationService::IVirtualizationService;
Alan Stokesa2869d22021-09-22 09:06:41 +010034
Alan Stokes69c610f2021-09-27 14:03:31 +010035pub struct InstanceManager {
36 service: Strong<dyn IVirtualizationService>,
37 state: Mutex<State>,
38}
Alan Stokesa2869d22021-09-22 09:06:41 +010039
40impl InstanceManager {
Alan Stokes69c610f2021-09-27 14:03:31 +010041 pub fn new(service: Strong<dyn IVirtualizationService>) -> Self {
42 Self { service, state: Default::default() }
43 }
44
Alan Stokes6542fdd2022-02-17 15:21:46 +000045 pub fn start_current_instance(&self) -> Result<Arc<CompOsInstance>> {
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080046 let mut vm_parameters = new_vm_parameters()?;
47 vm_parameters.config_path = Some(PREFER_STAGED_VM_CONFIG_PATH.to_owned());
Alan Stokes6542fdd2022-02-17 15:21:46 +000048 self.start_instance(CURRENT_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010049 }
50
Victor Hsiehbac923e2022-02-22 21:43:36 +000051 pub fn start_test_instance(&self, prefer_staged: bool) -> Result<Arc<CompOsInstance>> {
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080052 let mut vm_parameters = new_vm_parameters()?;
53 vm_parameters.debug_mode = true;
Victor Hsiehbac923e2022-02-22 21:43:36 +000054 if prefer_staged {
55 vm_parameters.config_path = Some(PREFER_STAGED_VM_CONFIG_PATH.to_owned());
56 }
Alan Stokesd21764c2021-10-25 15:33:40 +010057 self.start_instance(TEST_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010058 }
59
Alan Stokesd21764c2021-10-25 15:33:40 +010060 fn start_instance(
61 &self,
62 instance_name: &str,
63 vm_parameters: VmParameters,
64 ) -> Result<Arc<CompOsInstance>> {
Alan Stokes69c610f2021-09-27 14:03:31 +010065 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010066 state.mark_starting()?;
67 // Don't hold the lock while we start the instance to avoid blocking other callers.
68 drop(state);
69
Alan Stokesd21764c2021-10-25 15:33:40 +010070 let instance_starter = InstanceStarter::new(instance_name, vm_parameters);
71 let instance = self.try_start_instance(instance_starter);
Alan Stokesa2869d22021-09-22 09:06:41 +010072
Alan Stokes69c610f2021-09-27 14:03:31 +010073 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010074 if let Ok(ref instance) = instance {
75 state.mark_started(instance)?;
76 } else {
77 state.mark_stopped();
78 }
79 instance
80 }
81
Alan Stokesd21764c2021-10-25 15:33:40 +010082 fn try_start_instance(&self, instance_starter: InstanceStarter) -> Result<Arc<CompOsInstance>> {
Alan Stokes6542fdd2022-02-17 15:21:46 +000083 let compos_instance = instance_starter.start_new_instance(&*self.service)?;
Alan Stokes69c610f2021-09-27 14:03:31 +010084 Ok(Arc::new(compos_instance))
85 }
86}
87
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080088fn new_vm_parameters() -> Result<VmParameters> {
Andrew Walbran014efb52022-02-03 17:43:11 +000089 let cpus = match system_properties::read(DEX2OAT_THREADS_PROP_NAME)? {
90 Some(s) => Some(NonZeroU32::from_str(&s)?),
91 None => {
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080092 // dex2oat uses all CPUs by default. To match the behavior, give the VM all CPUs by
93 // default.
94 NonZeroU32::new(num_cpus::get() as u32)
95 }
96 };
Andrew Walbran014efb52022-02-03 17:43:11 +000097 let cpu_set = system_properties::read(DEX2OAT_CPU_SET_PROP_NAME)?;
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080098 Ok(VmParameters { cpus, cpu_set, ..Default::default() })
99}
100
Alan Stokesa2869d22021-09-22 09:06:41 +0100101// Ensures we only run one instance at a time.
102// Valid states:
103// Starting: is_starting is true, running_instance is None.
104// Started: is_starting is false, running_instance is Some(x) and there is a strong ref to x.
105// Stopped: is_starting is false and running_instance is None or a weak ref to a dropped instance.
Alan Stokes69c610f2021-09-27 14:03:31 +0100106// The panic calls here should never happen, unless the code above in InstanceManager is buggy.
107// In particular nothing the client does should be able to trigger them.
Alan Stokesa2869d22021-09-22 09:06:41 +0100108#[derive(Default)]
109struct State {
110 running_instance: Option<Weak<CompOsInstance>>,
111 is_starting: bool,
112}
113
114impl State {
115 // Move to Starting iff we are Stopped.
116 fn mark_starting(&mut self) -> Result<()> {
117 if self.is_starting {
118 bail!("An instance is already starting");
119 }
120 if let Some(weak) = &self.running_instance {
121 if weak.strong_count() != 0 {
122 bail!("An instance is already running");
123 }
124 }
125 self.running_instance = None;
126 self.is_starting = true;
127 Ok(())
128 }
129
130 // Move from Starting to Stopped.
131 fn mark_stopped(&mut self) {
132 if !self.is_starting || self.running_instance.is_some() {
133 panic!("Tried to mark stopped when not starting");
134 }
135 self.is_starting = false;
136 }
137
138 // Move from Starting to Started.
139 fn mark_started(&mut self, instance: &Arc<CompOsInstance>) -> Result<()> {
140 if !self.is_starting {
141 panic!("Tried to mark started when not starting")
142 }
143 if self.running_instance.is_some() {
144 panic!("Attempted to mark started when already started");
145 }
146 self.is_starting = false;
147 self.running_instance = Some(Arc::downgrade(instance));
148 Ok(())
149 }
Alan Stokesa2869d22021-09-22 09:06:41 +0100150}