Skip to main content

kernel_manager/
lib.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5pub mod kernels;
6pub mod pager;
7pub mod proxy;
8pub mod suspend;
9
10use crate::pager::{Pager, run_pager};
11use anyhow::{Error, anyhow};
12use fidl::Peered;
13use fidl::endpoints::{DiscoverableProtocolMarker, Proxy, ServerEnd};
14use fidl_fuchsia_component as fcomponent;
15use fidl_fuchsia_component_decl as fdecl;
16use fidl_fuchsia_component_runner as frunner;
17use fidl_fuchsia_io as fio;
18use fidl_fuchsia_starnix_container as fstarnix;
19use fidl_fuchsia_starnix_runner as fstarnixrunner;
20use fuchsia_async as fasync;
21use fuchsia_component::client as fclient;
22use fuchsia_inspect::{HistogramProperty, NumericProperty};
23use futures::TryStreamExt;
24use kernels::{KernelWakeLease, Kernels};
25use log::warn;
26use proxy::ChannelProxy;
27use rand::RngExt as _;
28use starnix_sync::{LockDepMutex, WakeSourcesLock};
29use std::future::Future;
30use std::sync::Arc;
31use suspend::{
32    ASLEEP_SIGNAL, AWAKE_SIGNAL, SuspendContext, WakeSource, WakeSources, suspend_container,
33};
34
35/// The name of the collection that the starnix_kernel is run in.
36const KERNEL_COLLECTION: &str = "kernels";
37
38/// The name of the protocol the kernel exposes for running containers.
39///
40/// This protocol is actually fuchsia.component.runner.ComponentRunner. We
41/// expose the implementation using this name to avoid confusion with copy
42/// of the fuchsia.component.runner.ComponentRunner protocol used for
43/// running component inside the container.
44const CONTAINER_RUNNER_PROTOCOL: &str = "fuchsia.starnix.container.Runner";
45
46#[allow(dead_code)]
47pub struct StarnixKernel {
48    /// The name of the kernel intsance in the kernels collection.
49    name: String,
50
51    /// The directory exposed by the Starnix kernel.
52    ///
53    /// This directory can be used to connect to services offered by the kernel.
54    exposed_dir: fio::DirectoryProxy,
55
56    /// An opaque token representing the container component.
57    component_instance: zx::Event,
58
59    /// The job the kernel lives under.
60    job: Arc<zx::Job>,
61
62    /// Tracks the active or in-flight wake lease for the container.
63    wake_lease: Arc<KernelWakeLease>,
64}
65
66impl StarnixKernel {
67    /// Creates a new instance of `starnix_kernel`.
68    ///
69    /// This is done by creating a new child in the `kernels` collection.
70    ///
71    /// Returns the kernel and a future that will resolve when the kernel has stopped.
72    pub async fn create(
73        realm: fcomponent::RealmProxy,
74        kernel_url: &str,
75        start_info: frunner::ComponentStartInfo,
76        controller: ServerEnd<frunner::ComponentControllerMarker>,
77    ) -> Result<(Self, impl Future<Output = ()>), Error> {
78        let kernel_name = generate_kernel_name(&start_info)?;
79        let component_instance = start_info
80            .component_instance
81            .as_ref()
82            .ok_or_else(|| {
83                anyhow::anyhow!("expected to find component_instance in ComponentStartInfo")
84            })?
85            .duplicate_handle(zx::Rights::SAME_RIGHTS)?;
86
87        // Create the `starnix_kernel`.
88        let (controller_proxy, controller_server_end) = fidl::endpoints::create_proxy();
89        realm
90            .create_child(
91                &fdecl::CollectionRef { name: KERNEL_COLLECTION.into() },
92                &fdecl::Child {
93                    name: Some(kernel_name.clone()),
94                    url: Some(kernel_url.to_string()),
95                    startup: Some(fdecl::StartupMode::Lazy),
96                    ..Default::default()
97                },
98                fcomponent::CreateChildArgs {
99                    controller: Some(controller_server_end),
100                    ..Default::default()
101                },
102            )
103            .await?
104            .map_err(|e| anyhow::anyhow!("failed to create kernel: {:?}", e))?;
105
106        let exposed_dir = open_exposed_directory(&realm, &kernel_name, KERNEL_COLLECTION).await?;
107        let container_runner = fclient::connect_to_named_protocol_at_dir_root::<
108            frunner::ComponentRunnerMarker,
109        >(&exposed_dir, CONTAINER_RUNNER_PROTOCOL)?;
110
111        // Actually start the container.
112        container_runner.start(start_info, controller)?;
113
114        // Ask the kernel for its job.
115        let container_controller =
116            fclient::connect_to_protocol_at_dir_root::<fstarnix::ControllerMarker>(&exposed_dir)?;
117        let fstarnix::ControllerGetJobHandleResponse { job, .. } =
118            container_controller.get_job_handle().await?;
119        let Some(job) = job else {
120            anyhow::bail!("expected to find job in ControllerGetJobHandleResponse");
121        };
122
123        let wake_lease = Arc::new(KernelWakeLease::new(&kernel_name));
124        let kernel = Self {
125            name: kernel_name,
126            exposed_dir,
127            component_instance,
128            job: Arc::new(job),
129            wake_lease,
130        };
131        let on_stop = async move {
132            _ = controller_proxy.into_channel().unwrap().on_closed().await;
133        };
134        Ok((kernel, on_stop))
135    }
136
137    /// Gets the opaque token representing the container component.
138    pub fn component_instance(&self) -> &zx::Event {
139        &self.component_instance
140    }
141
142    /// Gets the job the kernel lives under.
143    pub fn job(&self) -> &Arc<zx::Job> {
144        &self.job
145    }
146
147    /// Connect to the specified protocol exposed by the kernel.
148    pub fn connect_to_protocol<P: DiscoverableProtocolMarker>(&self) -> Result<P::Proxy, Error> {
149        fclient::connect_to_protocol_at_dir_root::<P>(&self.exposed_dir)
150    }
151}
152
153/// Generate a random name for the kernel.
154///
155/// We used to include some human-readable parts in the name, but people were
156/// tempted to make them load-bearing. We now just generate 7 random alphanumeric
157/// characters.
158fn generate_kernel_name(_start_info: &frunner::ComponentStartInfo) -> Result<String, Error> {
159    let random_id: String =
160        rand::rng().sample_iter(&rand::distr::Alphanumeric).take(7).map(char::from).collect();
161    Ok(random_id)
162}
163
164async fn open_exposed_directory(
165    realm: &fcomponent::RealmProxy,
166    child_name: &str,
167    collection_name: &str,
168) -> Result<fio::DirectoryProxy, Error> {
169    let (directory_proxy, server_end) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
170    realm
171        .open_exposed_dir(
172            &fdecl::ChildRef { name: child_name.into(), collection: Some(collection_name.into()) },
173            server_end,
174        )
175        .await?
176        .map_err(|e| {
177            anyhow!(
178                "failed to bind to child {} in collection {:?}: {:?}",
179                child_name,
180                collection_name,
181                e
182            )
183        })?;
184    Ok(directory_proxy)
185}
186
187pub struct SuspendMessage {
188    pub payload: fstarnixrunner::ManagerSuspendContainerRequest,
189    pub responder: fstarnixrunner::ManagerSuspendContainerResponder,
190}
191
192pub async fn run_suspend_worker(
193    receiver: async_channel::Receiver<SuspendMessage>,
194    suspend_context: Arc<SuspendContext>,
195    kernels: &Kernels,
196) {
197    while let Ok(msg) = receiver.recv().await {
198        suspend_context.suspend_attempts_count.add(1);
199        match suspend_container(msg.payload, &suspend_context, &kernels).await {
200            Ok(response) => {
201                if let Err(e) = match response {
202                    Ok(o) => {
203                        suspend_context.suspend_successes_count.add(1);
204                        if let Some(suspend_time) = o.suspend_time {
205                            suspend_context.suspend_duration_histogram.insert(suspend_time as u64);
206                        }
207                        msg.responder.send(Ok(&o))
208                    }
209                    Err(e) => {
210                        suspend_context.suspend_failures_count.add(1);
211                        msg.responder.send(Err(e))
212                    }
213                } {
214                    warn!("error replying to suspend request: {e}");
215                }
216            }
217            Err(e) => {
218                suspend_context.suspend_failures_count.add(1);
219                warn!("error executing suspend: {e}");
220                let _ = msg.responder.send(Err(fstarnixrunner::SuspendError::SuspendFailure));
221            }
222        }
223    }
224}
225
226pub async fn serve_starnix_manager(
227    mut stream: fstarnixrunner::ManagerRequestStream,
228    suspend_context: Arc<SuspendContext>,
229    sender: &async_channel::Sender<(ChannelProxy, Arc<LockDepMutex<WakeSources, WakeSourcesLock>>)>,
230    pager: Arc<Pager>,
231    suspend_sender: &async_channel::Sender<SuspendMessage>,
232) -> Result<(), Error> {
233    while let Some(event) = stream.try_next().await? {
234        match event {
235            fstarnixrunner::ManagerRequest::SuspendContainer { payload, responder, .. } => {
236                if let Err(e) = suspend_sender.try_send(SuspendMessage { payload, responder }) {
237                    warn!("failed to send suspend request to worker: {e}");
238                }
239            }
240            fstarnixrunner::ManagerRequest::ProxyWakeChannel { payload, .. } => {
241                let fstarnixrunner::ManagerProxyWakeChannelRequest {
242                    // TODO: Handle more than one container.
243                    container_job: Some(_container_job),
244                    remote_channel: Some(remote_channel),
245                    container_channel: Some(container_channel),
246                    name: Some(name),
247                    counter: Some(message_counter),
248                    ..
249                } = payload
250                else {
251                    continue;
252                };
253
254                suspend_context.wake_sources.lock().insert(
255                    message_counter.koid().unwrap(),
256                    WakeSource::from_counter(
257                        message_counter.duplicate_handle(zx::Rights::SAME_RIGHTS)?,
258                        name.clone(),
259                    ),
260                );
261
262                let proxy =
263                    ChannelProxy { container_channel, remote_channel, message_counter, name };
264
265                sender.try_send((proxy, suspend_context.wake_sources.clone())).unwrap();
266            }
267            fstarnixrunner::ManagerRequest::RegisterWakeWatcher { payload, responder } => {
268                if let Some(watcher) = payload.watcher {
269                    let (clear_mask, set_mask) = (ASLEEP_SIGNAL, AWAKE_SIGNAL);
270                    watcher.signal_peer(clear_mask, set_mask)?;
271
272                    suspend_context.wake_watchers.lock().push(watcher);
273                }
274                if let Err(e) = responder.send() {
275                    warn!("error registering power watcher: {e}");
276                }
277            }
278            fstarnixrunner::ManagerRequest::AddWakeSource { payload, .. } => {
279                let fstarnixrunner::ManagerAddWakeSourceRequest {
280                    // TODO: Handle more than one container.
281                    container_job: Some(_container_job),
282                    name: Some(name),
283                    handle: Some(handle),
284                    signals: Some(signals),
285                    ..
286                } = payload
287                else {
288                    continue;
289                };
290                suspend_context.wake_sources.lock().insert(
291                    handle.koid().unwrap(),
292                    WakeSource::from_handle(handle, name, zx::Signals::from_bits_truncate(signals)),
293                );
294            }
295            fstarnixrunner::ManagerRequest::RemoveWakeSource { payload, .. } => {
296                let fstarnixrunner::ManagerRemoveWakeSourceRequest {
297                    // TODO: Handle more than one container.
298                    container_job: Some(_container_job),
299                    handle: Some(handle),
300                    ..
301                } = payload
302                else {
303                    continue;
304                };
305
306                suspend_context.wake_sources.lock().remove(&handle.koid().unwrap());
307            }
308            fstarnixrunner::ManagerRequest::CreatePager { payload, .. } => {
309                fasync::Task::spawn(run_pager(payload, pager.clone())).detach();
310            }
311            _ => {}
312        }
313    }
314    Ok(())
315}