blob: 4fc4ad102ae0ea7320a29b2c5af2703c7f9ebf82 [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;
Alan Stokesa2869d22021-09-22 09:06:41 +010022use anyhow::{bail, Context, Result};
23use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010024use compos_aidl_interface::binder::Strong;
Alan Stokesd21764c2021-10-25 15:33:40 +010025use compos_common::compos_client::VmParameters;
Jiyong Park165921b2022-01-14 00:49:33 +090026use compos_common::{
27 DEX2OAT_CPU_SET_PROP_NAME, DEX2OAT_THREADS_PROP_NAME, PENDING_INSTANCE_DIR,
28 PREFER_STAGED_VM_CONFIG_PATH, TEST_INSTANCE_DIR,
29};
30use rustutils::system_properties;
31use std::num::NonZeroU32;
32use std::str::FromStr;
Alan Stokesa2869d22021-09-22 09:06:41 +010033use std::sync::{Arc, Mutex, Weak};
Alan Stokes6b2d0a82021-09-29 11:30:39 +010034use virtualizationservice::IVirtualizationService::IVirtualizationService;
Alan Stokesa2869d22021-09-22 09:06:41 +010035
Alan Stokes69c610f2021-09-27 14:03:31 +010036pub struct InstanceManager {
37 service: Strong<dyn IVirtualizationService>,
38 state: Mutex<State>,
39}
Alan Stokesa2869d22021-09-22 09:06:41 +010040
41impl InstanceManager {
Alan Stokes69c610f2021-09-27 14:03:31 +010042 pub fn new(service: Strong<dyn IVirtualizationService>) -> Self {
43 Self { service, state: Default::default() }
44 }
45
Alan Stokesa2869d22021-09-22 09:06:41 +010046 pub fn get_running_service(&self) -> Result<Strong<dyn ICompOsService>> {
Alan Stokes69c610f2021-09-27 14:03:31 +010047 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010048 let instance = state.get_running_instance().context("No running instance")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010049 Ok(instance.get_service())
Alan Stokesa2869d22021-09-22 09:06:41 +010050 }
51
Alan Stokes6fc18372021-11-25 17:50:27 +000052 pub fn start_pending_instance(&self) -> Result<Arc<CompOsInstance>> {
Alan Stokesb4a0e912021-12-01 11:43:59 +000053 let config_path = Some(PREFER_STAGED_VM_CONFIG_PATH.to_owned());
Jiyong Park165921b2022-01-14 00:49:33 +090054 let mut vm_parameters = VmParameters { config_path, ..Default::default() };
55 vm_parameters.cpus = NonZeroU32::from_str(
56 &system_properties::read(DEX2OAT_THREADS_PROP_NAME).unwrap_or_default(),
57 )
58 .ok();
59 vm_parameters.cpu_set = system_properties::read(DEX2OAT_CPU_SET_PROP_NAME).ok();
Alan Stokesb4a0e912021-12-01 11:43:59 +000060 self.start_instance(PENDING_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010061 }
62
63 pub fn start_test_instance(&self) -> Result<Arc<CompOsInstance>> {
Alan Stokesb4a0e912021-12-01 11:43:59 +000064 let vm_parameters = VmParameters { debug_mode: true, ..Default::default() };
Alan Stokesd21764c2021-10-25 15:33:40 +010065 self.start_instance(TEST_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010066 }
67
Alan Stokesd21764c2021-10-25 15:33:40 +010068 fn start_instance(
69 &self,
70 instance_name: &str,
71 vm_parameters: VmParameters,
72 ) -> Result<Arc<CompOsInstance>> {
Alan Stokes69c610f2021-09-27 14:03:31 +010073 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010074 state.mark_starting()?;
75 // Don't hold the lock while we start the instance to avoid blocking other callers.
76 drop(state);
77
Alan Stokesd21764c2021-10-25 15:33:40 +010078 let instance_starter = InstanceStarter::new(instance_name, vm_parameters);
79 let instance = self.try_start_instance(instance_starter);
Alan Stokesa2869d22021-09-22 09:06:41 +010080
Alan Stokes69c610f2021-09-27 14:03:31 +010081 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010082 if let Ok(ref instance) = instance {
83 state.mark_started(instance)?;
84 } else {
85 state.mark_stopped();
86 }
87 instance
88 }
89
Alan Stokesd21764c2021-10-25 15:33:40 +010090 fn try_start_instance(&self, instance_starter: InstanceStarter) -> Result<Arc<CompOsInstance>> {
Alan Stokes6b2d0a82021-09-29 11:30:39 +010091 let compos_instance = instance_starter.create_or_start_instance(&*self.service)?;
Alan Stokes69c610f2021-09-27 14:03:31 +010092 Ok(Arc::new(compos_instance))
93 }
94}
95
Alan Stokesa2869d22021-09-22 09:06:41 +010096// Ensures we only run one instance at a time.
97// Valid states:
98// Starting: is_starting is true, running_instance is None.
99// Started: is_starting is false, running_instance is Some(x) and there is a strong ref to x.
100// 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 +0100101// The panic calls here should never happen, unless the code above in InstanceManager is buggy.
102// In particular nothing the client does should be able to trigger them.
Alan Stokesa2869d22021-09-22 09:06:41 +0100103#[derive(Default)]
104struct State {
105 running_instance: Option<Weak<CompOsInstance>>,
106 is_starting: bool,
107}
108
109impl State {
110 // Move to Starting iff we are Stopped.
111 fn mark_starting(&mut self) -> Result<()> {
112 if self.is_starting {
113 bail!("An instance is already starting");
114 }
115 if let Some(weak) = &self.running_instance {
116 if weak.strong_count() != 0 {
117 bail!("An instance is already running");
118 }
119 }
120 self.running_instance = None;
121 self.is_starting = true;
122 Ok(())
123 }
124
125 // Move from Starting to Stopped.
126 fn mark_stopped(&mut self) {
127 if !self.is_starting || self.running_instance.is_some() {
128 panic!("Tried to mark stopped when not starting");
129 }
130 self.is_starting = false;
131 }
132
133 // Move from Starting to Started.
134 fn mark_started(&mut self, instance: &Arc<CompOsInstance>) -> Result<()> {
135 if !self.is_starting {
136 panic!("Tried to mark started when not starting")
137 }
138 if self.running_instance.is_some() {
139 panic!("Attempted to mark started when already started");
140 }
141 self.is_starting = false;
142 self.running_instance = Some(Arc::downgrade(instance));
143 Ok(())
144 }
145
146 // Return the running instance if we are in the Started state.
147 fn get_running_instance(&mut self) -> Option<Arc<CompOsInstance>> {
148 if self.is_starting {
149 return None;
150 }
151 let instance = self.running_instance.as_ref()?.upgrade();
152 if instance.is_none() {
153 // No point keeping an orphaned weak reference
154 self.running_instance = None;
155 }
156 instance
157 }
158}