fdf_component/context.rs
1// Copyright 2024 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
5use crate::{Incoming, Node};
6use fuchsia_async::ScopeHandle;
7use fuchsia_component::server::{ServiceFs, ServiceObjTrait};
8use fuchsia_component_config::Config;
9use fuchsia_inspect::Inspector;
10use inspect_runtime::PublishOptions;
11use log::error;
12use namespace::Namespace;
13use zx::Status;
14
15use fdf::DispatcherRef;
16use fidl_fuchsia_driver_framework::DriverStartArgs;
17
18/// The context arguments passed to the driver in its start arguments.
19#[non_exhaustive]
20pub struct DriverContext {
21 /// A reference to the root [`fdf::Dispatcher`] for this driver.
22 pub root_dispatcher: DispatcherRef<'static>,
23 /// The original [`DriverStartArgs`] passed in as start arguments, minus any parts that were
24 /// used to construct other elements of [`Self`].
25 pub start_args: DriverStartArgs,
26 /// The incoming namespace constructed from [`DriverStartArgs::incoming`]. Since producing this
27 /// consumes the incoming namespace from [`Self::start_args`], that will always be [`None`].
28 pub incoming: Incoming,
29}
30
31impl DriverContext {
32 /// Binds the node proxy client end from the start args into a [`NodeProxy`] that can be used
33 /// to add child nodes. Dropping this proxy will result in the node being removed and the
34 /// driver starting shutdown, so it should be bound and stored in your driver object in its
35 /// [`crate::Driver::start`] method.
36 ///
37 /// After calling this, [`DriverStartArgs::node`] in [`Self::start_args`] will be `None`.
38 ///
39 /// Returns [`Status::INVALID_ARGS`] if the node client end is not present in the start
40 /// arguments.
41 pub fn take_node(&mut self) -> Result<Node, Status> {
42 let node_client = self.start_args.node.take().ok_or(Status::INVALID_ARGS)?;
43 Ok(Node::from(node_client.into_proxy()))
44 }
45
46 /// Returns the component config.
47 ///
48 /// After calling this, [`DriverStartArgs::config`] in [`Self::start_args`] will be `None`.
49 ///
50 /// Returns [`Status::INVALID_ARGS`] if the config is not present in the start arguments.
51 pub fn take_config<C: Config>(&mut self) -> Result<C, Status> {
52 let vmo = self.start_args.config.take().ok_or(Status::INVALID_ARGS)?;
53 Ok(Config::from_vmo(&vmo).expect("Config VMO handle must be valid."))
54 }
55
56 /// Serves the given [`ServiceFs`] on the node's outgoing directory. This can only be called
57 /// once, and after this the [`DriverStartArgs::outgoing_dir`] member will be [`None`].
58 ///
59 /// Logs an error and returns [`Status::INVALID_ARGS`] if the outgoing directory server end is
60 /// not present in the start arguments, or [`Status::INTERNAL`] if serving the connection
61 /// failed.
62 pub fn serve_outgoing<O: ServiceObjTrait>(
63 &mut self,
64 outgoing_fs: &mut ServiceFs<O>,
65 ) -> Result<(), Status> {
66 let Some(outgoing_dir) = self.start_args.outgoing_dir.take() else {
67 error!("Tried to serve on outgoing directory but it wasn't available");
68 return Err(Status::INVALID_ARGS);
69 };
70 outgoing_fs.serve_connection(outgoing_dir).map_err(|err| {
71 error!("Failed to serve outgoing directory: {err}");
72 Status::INTERNAL
73 })?;
74
75 Ok(())
76 }
77
78 /// Spawns a server handling `fuchsia.inspect.Tree` requests and a handle
79 /// to the `fuchsia.inspect.Tree` is published using `fuchsia.inspect.InspectSink`.
80 ///
81 /// Whenever the client wishes to stop publishing Inspect, the Controller may be dropped.
82 pub fn publish_inspect(&self, inspector: &Inspector, scope: ScopeHandle) -> Result<(), Status> {
83 let client = self.incoming.connect_protocol().map_err(|err| {
84 error!("Error connecting to inspect : {err}");
85 Status::INTERNAL
86 })?;
87
88 let task = inspect_runtime::publish(
89 inspector,
90 PublishOptions::default().on_inspect_sink_client(client),
91 )
92 .ok_or(Status::INTERNAL)?;
93
94 scope.spawn_local(task);
95
96 Ok(())
97 }
98
99 /// Returns the VMAR which the driver can use to map memory.
100 ///
101 /// If the driver was not provided with an explicit VMAR in its start arguments, the root VMAR
102 /// is returned.
103 pub fn vmar(&self) -> zx::Unowned<'_, zx::Vmar> {
104 // NB: We can't use `map_or_else` here, because the compiler gets confused about lifetimes
105 // when attempting to unify the types of the two function arguments.
106 if let Some(vmar) = self.start_args.vmar.as_ref().map(zx::Unowned::new) {
107 vmar
108 } else {
109 fuchsia_runtime::vmar_root_self()
110 }
111 }
112
113 pub(crate) fn new(
114 root_dispatcher: DispatcherRef<'static>,
115 mut start_args: DriverStartArgs,
116 ) -> Result<Self, Status> {
117 let incoming_namespace: Namespace = start_args
118 .incoming
119 .take()
120 .unwrap_or_default()
121 .try_into()
122 .map_err(|_| Status::INVALID_ARGS)?;
123 let incoming = Incoming::from(incoming_namespace);
124 Ok(DriverContext { root_dispatcher, start_args, incoming })
125 }
126
127 pub(crate) fn start_logging(&self, driver_name: &str) -> Result<(), Status> {
128 let log_client = match self.incoming.connect_protocol() {
129 Ok(log_client) => log_client,
130 Err(err) => {
131 eprintln!(
132 "Error connecting to log sink proxy at driver startup: {err}. Continuing without logging."
133 );
134 return Ok(());
135 }
136 };
137
138 if let Err(e) = driver_diagnostics_log::initialize(
139 driver_diagnostics_log::PublishOptions::default()
140 .use_log_sink(log_client)
141 .tags(&["driver", driver_name]),
142 ) {
143 eprintln!("Error initializing logging at driver startup: {e}");
144 }
145 Ok(())
146 }
147}