blob: 24ae5767ba1584c0296f539e60e3fff29daf39a9 [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;
Alan Stokesb4a0e912021-12-01 11:43:59 +000026use compos_common::{PENDING_INSTANCE_DIR, PREFER_STAGED_VM_CONFIG_PATH, TEST_INSTANCE_DIR};
Alan Stokesa2869d22021-09-22 09:06:41 +010027use std::sync::{Arc, Mutex, Weak};
Alan Stokes6b2d0a82021-09-29 11:30:39 +010028use virtualizationservice::IVirtualizationService::IVirtualizationService;
Alan Stokesa2869d22021-09-22 09:06:41 +010029
Alan Stokes69c610f2021-09-27 14:03:31 +010030pub struct InstanceManager {
31 service: Strong<dyn IVirtualizationService>,
32 state: Mutex<State>,
33}
Alan Stokesa2869d22021-09-22 09:06:41 +010034
35impl InstanceManager {
Alan Stokes69c610f2021-09-27 14:03:31 +010036 pub fn new(service: Strong<dyn IVirtualizationService>) -> Self {
37 Self { service, state: Default::default() }
38 }
39
Alan Stokesa2869d22021-09-22 09:06:41 +010040 pub fn get_running_service(&self) -> Result<Strong<dyn ICompOsService>> {
Alan Stokes69c610f2021-09-27 14:03:31 +010041 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010042 let instance = state.get_running_instance().context("No running instance")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010043 Ok(instance.get_service())
Alan Stokesa2869d22021-09-22 09:06:41 +010044 }
45
Alan Stokes6fc18372021-11-25 17:50:27 +000046 pub fn start_pending_instance(&self) -> Result<Arc<CompOsInstance>> {
Alan Stokesb4a0e912021-12-01 11:43:59 +000047 let config_path = Some(PREFER_STAGED_VM_CONFIG_PATH.to_owned());
48 let vm_parameters = VmParameters { config_path, ..Default::default() };
49 self.start_instance(PENDING_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010050 }
51
52 pub fn start_test_instance(&self) -> Result<Arc<CompOsInstance>> {
Alan Stokesb4a0e912021-12-01 11:43:59 +000053 let vm_parameters = VmParameters { debug_mode: true, ..Default::default() };
Alan Stokesd21764c2021-10-25 15:33:40 +010054 self.start_instance(TEST_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010055 }
56
Alan Stokesd21764c2021-10-25 15:33:40 +010057 fn start_instance(
58 &self,
59 instance_name: &str,
60 vm_parameters: VmParameters,
61 ) -> Result<Arc<CompOsInstance>> {
Alan Stokes69c610f2021-09-27 14:03:31 +010062 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010063 state.mark_starting()?;
64 // Don't hold the lock while we start the instance to avoid blocking other callers.
65 drop(state);
66
Alan Stokesd21764c2021-10-25 15:33:40 +010067 let instance_starter = InstanceStarter::new(instance_name, vm_parameters);
68 let instance = self.try_start_instance(instance_starter);
Alan Stokesa2869d22021-09-22 09:06:41 +010069
Alan Stokes69c610f2021-09-27 14:03:31 +010070 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010071 if let Ok(ref instance) = instance {
72 state.mark_started(instance)?;
73 } else {
74 state.mark_stopped();
75 }
76 instance
77 }
78
Alan Stokesd21764c2021-10-25 15:33:40 +010079 fn try_start_instance(&self, instance_starter: InstanceStarter) -> Result<Arc<CompOsInstance>> {
Alan Stokes6b2d0a82021-09-29 11:30:39 +010080 let compos_instance = instance_starter.create_or_start_instance(&*self.service)?;
Alan Stokes69c610f2021-09-27 14:03:31 +010081 Ok(Arc::new(compos_instance))
82 }
83}
84
Alan Stokesa2869d22021-09-22 09:06:41 +010085// Ensures we only run one instance at a time.
86// Valid states:
87// Starting: is_starting is true, running_instance is None.
88// Started: is_starting is false, running_instance is Some(x) and there is a strong ref to x.
89// 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 +010090// The panic calls here should never happen, unless the code above in InstanceManager is buggy.
91// In particular nothing the client does should be able to trigger them.
Alan Stokesa2869d22021-09-22 09:06:41 +010092#[derive(Default)]
93struct State {
94 running_instance: Option<Weak<CompOsInstance>>,
95 is_starting: bool,
96}
97
98impl State {
99 // Move to Starting iff we are Stopped.
100 fn mark_starting(&mut self) -> Result<()> {
101 if self.is_starting {
102 bail!("An instance is already starting");
103 }
104 if let Some(weak) = &self.running_instance {
105 if weak.strong_count() != 0 {
106 bail!("An instance is already running");
107 }
108 }
109 self.running_instance = None;
110 self.is_starting = true;
111 Ok(())
112 }
113
114 // Move from Starting to Stopped.
115 fn mark_stopped(&mut self) {
116 if !self.is_starting || self.running_instance.is_some() {
117 panic!("Tried to mark stopped when not starting");
118 }
119 self.is_starting = false;
120 }
121
122 // Move from Starting to Started.
123 fn mark_started(&mut self, instance: &Arc<CompOsInstance>) -> Result<()> {
124 if !self.is_starting {
125 panic!("Tried to mark started when not starting")
126 }
127 if self.running_instance.is_some() {
128 panic!("Attempted to mark started when already started");
129 }
130 self.is_starting = false;
131 self.running_instance = Some(Arc::downgrade(instance));
132 Ok(())
133 }
134
135 // Return the running instance if we are in the Started state.
136 fn get_running_instance(&mut self) -> Option<Arc<CompOsInstance>> {
137 if self.is_starting {
138 return None;
139 }
140 let instance = self.running_instance.as_ref()?.upgrade();
141 if instance.is_none() {
142 // No point keeping an orphaned weak reference
143 self.running_instance = None;
144 }
145 instance
146 }
147}