blob: 8950f20df2daedf6810f44364ea43448b9a3724a [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::{
26 DEX2OAT_CPU_SET_PROP_NAME, DEX2OAT_THREADS_PROP_NAME, PENDING_INSTANCE_DIR,
27 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 Stokes6fc18372021-11-25 17:50:27 +000045 pub fn start_pending_instance(&self) -> Result<Arc<CompOsInstance>> {
Alan Stokesb4a0e912021-12-01 11:43:59 +000046 let config_path = Some(PREFER_STAGED_VM_CONFIG_PATH.to_owned());
Jiyong Park165921b2022-01-14 00:49:33 +090047 let mut vm_parameters = VmParameters { config_path, ..Default::default() };
48 vm_parameters.cpus = NonZeroU32::from_str(
49 &system_properties::read(DEX2OAT_THREADS_PROP_NAME).unwrap_or_default(),
50 )
51 .ok();
52 vm_parameters.cpu_set = system_properties::read(DEX2OAT_CPU_SET_PROP_NAME).ok();
Alan Stokesb4a0e912021-12-01 11:43:59 +000053 self.start_instance(PENDING_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010054 }
55
56 pub fn start_test_instance(&self) -> Result<Arc<CompOsInstance>> {
Alan Stokesb4a0e912021-12-01 11:43:59 +000057 let vm_parameters = VmParameters { debug_mode: true, ..Default::default() };
Alan Stokesd21764c2021-10-25 15:33:40 +010058 self.start_instance(TEST_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010059 }
60
Alan Stokesd21764c2021-10-25 15:33:40 +010061 fn start_instance(
62 &self,
63 instance_name: &str,
64 vm_parameters: VmParameters,
65 ) -> Result<Arc<CompOsInstance>> {
Alan Stokes69c610f2021-09-27 14:03:31 +010066 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010067 state.mark_starting()?;
68 // Don't hold the lock while we start the instance to avoid blocking other callers.
69 drop(state);
70
Alan Stokesd21764c2021-10-25 15:33:40 +010071 let instance_starter = InstanceStarter::new(instance_name, vm_parameters);
72 let instance = self.try_start_instance(instance_starter);
Alan Stokesa2869d22021-09-22 09:06:41 +010073
Alan Stokes69c610f2021-09-27 14:03:31 +010074 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010075 if let Ok(ref instance) = instance {
76 state.mark_started(instance)?;
77 } else {
78 state.mark_stopped();
79 }
80 instance
81 }
82
Alan Stokesd21764c2021-10-25 15:33:40 +010083 fn try_start_instance(&self, instance_starter: InstanceStarter) -> Result<Arc<CompOsInstance>> {
Alan Stokes6b2d0a82021-09-29 11:30:39 +010084 let compos_instance = instance_starter.create_or_start_instance(&*self.service)?;
Alan Stokes69c610f2021-09-27 14:03:31 +010085 Ok(Arc::new(compos_instance))
86 }
87}
88
Alan Stokesa2869d22021-09-22 09:06:41 +010089// Ensures we only run one instance at a time.
90// Valid states:
91// Starting: is_starting is true, running_instance is None.
92// Started: is_starting is false, running_instance is Some(x) and there is a strong ref to x.
93// 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 +010094// The panic calls here should never happen, unless the code above in InstanceManager is buggy.
95// In particular nothing the client does should be able to trigger them.
Alan Stokesa2869d22021-09-22 09:06:41 +010096#[derive(Default)]
97struct State {
98 running_instance: Option<Weak<CompOsInstance>>,
99 is_starting: bool,
100}
101
102impl State {
103 // Move to Starting iff we are Stopped.
104 fn mark_starting(&mut self) -> Result<()> {
105 if self.is_starting {
106 bail!("An instance is already starting");
107 }
108 if let Some(weak) = &self.running_instance {
109 if weak.strong_count() != 0 {
110 bail!("An instance is already running");
111 }
112 }
113 self.running_instance = None;
114 self.is_starting = true;
115 Ok(())
116 }
117
118 // Move from Starting to Stopped.
119 fn mark_stopped(&mut self) {
120 if !self.is_starting || self.running_instance.is_some() {
121 panic!("Tried to mark stopped when not starting");
122 }
123 self.is_starting = false;
124 }
125
126 // Move from Starting to Started.
127 fn mark_started(&mut self, instance: &Arc<CompOsInstance>) -> Result<()> {
128 if !self.is_starting {
129 panic!("Tried to mark started when not starting")
130 }
131 if self.running_instance.is_some() {
132 panic!("Attempted to mark started when already started");
133 }
134 self.is_starting = false;
135 self.running_instance = Some(Arc::downgrade(instance));
136 Ok(())
137 }
Alan Stokesa2869d22021-09-22 09:06:41 +0100138}