Skip to main content

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::{HealthAlertReporter, Incoming, Node, ParentProperty, PropertyValue};
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::AsyncDispatcher;
16use fidl_next_fuchsia_driver_framework::{DriverStartArgs, HealthAlert};
17
18pub use fuchsia_inspect_contrib::content_publisher as inspect_publisher;
19
20/// The context arguments passed to the driver in its start arguments.
21#[non_exhaustive]
22pub struct DriverContext {
23    /// A reference to the root [`fdf::Dispatcher`] for this driver.
24    pub root_dispatcher: AsyncDispatcher,
25    /// The original [`DriverStartArgs`] passed in as start arguments, minus any parts that were
26    /// used to construct other elements of [`Self`].
27    pub start_args: DriverStartArgs,
28    /// The incoming namespace constructed from [`DriverStartArgs::incoming`]. Since producing this
29    /// consumes the incoming namespace from [`Self::start_args`], that will always be [`None`].
30    pub incoming: Incoming,
31    health_alert_reporter: HealthAlertReporter,
32}
33
34impl DriverContext {
35    /// Returns a reporter through which the driver can proactively emit
36    /// `fuchsia.driver.framework/Driver.OnHealthAlert` events after [`crate::Driver::start`] has
37    /// consumed this context. The reporter is cheap to clone and may be used from any thread.
38    pub fn health_alert_reporter(&self) -> HealthAlertReporter {
39        self.health_alert_reporter.clone()
40    }
41
42    /// Reports `alert` to the driver framework. Equivalent to
43    /// `self.health_alert_reporter().report_health_alert(alert)`; see
44    /// [`HealthAlertReporter::report_health_alert`].
45    pub fn report_health_alert(&self, alert: HealthAlert) {
46        self.health_alert_reporter.report_health_alert(alert);
47    }
48
49    /// Binds the node proxy client end from the start args into a [`NodeProxy`] that can be used
50    /// to add child nodes. Dropping this proxy will result in the node being removed and the
51    /// driver starting shutdown, so it should be bound and stored in your driver object in its
52    /// [`crate::Driver::start`] method.
53    ///
54    /// After calling this, [`DriverStartArgs::node`] in [`Self::start_args`] will be `None`.
55    ///
56    /// Returns [`Status::INVALID_ARGS`] if the node client end is not present in the start
57    /// arguments.
58    pub fn take_node(&mut self) -> Result<Node, Status> {
59        let node_client = self.start_args.node.take().ok_or(Status::INVALID_ARGS)?;
60        let node_client =
61            fidl::endpoints::ClientEnd::<fidl_fuchsia_driver_framework::NodeMarker>::new(
62                node_client.into_untyped(),
63            );
64        Ok(Node::from(node_client.into_proxy()))
65    }
66
67    /// Returns the component config.
68    ///
69    /// After calling this, [`DriverStartArgs::config`] in [`Self::start_args`] will be `None`.
70    ///
71    /// Returns [`Status::INVALID_ARGS`] if the config is not present in the start arguments.
72    pub fn take_config<C: Config>(&mut self) -> Result<C, Status> {
73        let vmo = self.start_args.config.take().ok_or(Status::INVALID_ARGS)?;
74        Ok(Config::from_vmo(&vmo).expect("Config VMO handle must be valid."))
75    }
76
77    /// Serves the given [`ServiceFs`] on the node's outgoing directory. This can only be called
78    /// once, and after this the [`DriverStartArgs::outgoing_dir`] member will be [`None`].
79    ///
80    /// Logs an error and returns [`Status::INVALID_ARGS`] if the outgoing directory server end is
81    /// not present in the start arguments, or [`Status::INTERNAL`] if serving the connection
82    /// failed.
83    pub fn serve_outgoing<O: ServiceObjTrait>(
84        &mut self,
85        outgoing_fs: &mut ServiceFs<O>,
86    ) -> Result<(), Status> {
87        let Some(outgoing_dir) = self.start_args.outgoing_dir.take() else {
88            error!("Tried to serve on outgoing directory but it wasn't available");
89            return Err(Status::INVALID_ARGS);
90        };
91        let outgoing_dir = into_legacy_server_end(outgoing_dir);
92        outgoing_fs.serve_connection(outgoing_dir).map_err(|err| {
93            error!("Failed to serve outgoing directory: {err}");
94            Status::INTERNAL
95        })?;
96
97        Ok(())
98    }
99
100    /// Spawns a server handling `fuchsia.inspect.Tree` requests and a handle
101    /// to the `fuchsia.inspect.Tree` is published using `fuchsia.inspect.InspectSink`.
102    ///
103    /// Whenever the client wishes to stop publishing Inspect, the Controller may be dropped.
104    pub fn publish_inspect(&self, inspector: &Inspector, scope: ScopeHandle) -> Result<(), Status> {
105        let client = self.incoming.connect_protocol().map_err(|err| {
106            error!("Error connecting to inspect : {err}");
107            Status::INTERNAL
108        })?;
109
110        let task = inspect_runtime::publish(
111            inspector,
112            PublishOptions::default().on_inspect_sink_client(client),
113        )
114        .ok_or(Status::INTERNAL)?;
115
116        scope.spawn_local(task);
117
118        Ok(())
119    }
120
121    /// Returns an inspect content publisher that acts as a stream for requests for inspect data.
122    pub fn inspect_content_publisher(&self) -> Result<inspect_publisher::ContentPublisher, Status> {
123        let inspect_sink_client = self.incoming.connect_protocol().map_err(|err| {
124            error!("Error connecting to inspect : {err}");
125            Status::INTERNAL
126        })?;
127
128        let options = inspect_publisher::PublishOptions { inspect_sink_client };
129        inspect_publisher::content_publisher(options).map_err(|err| {
130            error!("Error creating inspect content publisher: {err}");
131            Status::INTERNAL
132        })
133    }
134
135    /// Returns the name of the node that the driver is bound to, if present in the start
136    /// arguments.
137    pub fn node_name(&self) -> Option<&str> {
138        self.start_args.node_name.as_deref()
139    }
140
141    /// Takes the node token from the start arguments, if the driver host provided one. The token
142    /// identifies the driver's node to other framework services, such as the power framework.
143    ///
144    /// After calling this, [`DriverStartArgs::node_token`] in [`Self::start_args`] will be `None`.
145    pub fn take_node_token(&mut self) -> Option<zx::Event> {
146        self.start_args.node_token.take()
147    }
148
149    /// Takes the power element dependency token from the start arguments. The driver host
150    /// provides it when the driver's manifest opts in to a framework-managed power element.
151    ///
152    /// After calling this, the `token` of [`DriverStartArgs::power_element_args`] in
153    /// [`Self::start_args`] will be `None`.
154    pub fn take_power_element_token(&mut self) -> Option<zx::Event> {
155        self.start_args.power_element_args.as_mut()?.token.take()
156    }
157
158    /// Returns the properties of the driver's parent node(s) from the start arguments, in the
159    /// order the driver host provided them. See [`ParentProperty::parent`] for how the properties
160    /// are grouped.
161    pub fn node_properties(&self) -> impl Iterator<Item = ParentProperty<'_>> + '_ {
162        self.start_args.node_properties_2.iter().flatten().flat_map(|entry| {
163            entry.properties.iter().map(move |property| ParentProperty {
164                parent: &entry.name,
165                key: &property.key,
166                value: PropertyValue::from(&property.value),
167            })
168        })
169    }
170
171    /// Returns the VMAR which the driver can use to map memory.
172    ///
173    /// If the driver was not provided with an explicit VMAR in its start arguments, the root VMAR
174    /// is returned.
175    pub fn vmar(&self) -> zx::Unowned<'_, zx::Vmar> {
176        // NB: We can't use `map_or_else` here, because the compiler gets confused about lifetimes
177        // when attempting to unify the types of the two function arguments.
178        if let Some(vmar) = self.start_args.vmar.as_ref().map(zx::Unowned::new) {
179            vmar
180        } else {
181            fuchsia_runtime::vmar_root_self()
182        }
183    }
184
185    pub(crate) fn new(
186        root_dispatcher: AsyncDispatcher,
187        mut start_args: DriverStartArgs,
188        health_alert_reporter: HealthAlertReporter,
189    ) -> Result<Self, Status> {
190        let mut incoming_namespace = Namespace::new();
191        for entry in start_args.incoming.take().unwrap_or_default() {
192            let path = entry
193                .path
194                .ok_or(Status::INVALID_ARGS)?
195                .parse()
196                .map_err(|_| Status::INVALID_ARGS)?;
197            let directory = into_legacy_client_end(entry.directory.ok_or(Status::INVALID_ARGS)?);
198            incoming_namespace.add(&path, directory).map_err(|_| Status::INVALID_ARGS)?;
199        }
200        let incoming = Incoming::from(incoming_namespace);
201        Ok(DriverContext { root_dispatcher, start_args, incoming, health_alert_reporter })
202    }
203
204    pub(crate) fn start_logging(&self, driver_name: &str) -> Result<(), Status> {
205        let log_client = match self.incoming.connect_protocol() {
206            Ok(log_client) => log_client,
207            Err(err) => {
208                eprintln!(
209                    "Error connecting to log sink proxy at driver startup: {err}. Continuing without logging."
210                );
211                return Ok(());
212            }
213        };
214
215        if let Err(e) = driver_diagnostics_log::initialize(
216            driver_diagnostics_log::PublishOptions::default()
217                .use_log_sink(log_client)
218                .tags(&["driver", driver_name]),
219        ) {
220            eprintln!("Error initializing logging at driver startup: {e}");
221        }
222        Ok(())
223    }
224}
225
226/// Converts a `fidl_next::ClientEnd` into a legacy `fidl::endpoints::ClientEnd` over a Zircon
227/// channel for APIs like `namespace::Namespace` that still accept `fidl_fuchsia_io` endpoints.
228fn into_legacy_client_end<P, M: fidl::endpoints::ProtocolMarker>(
229    client_end: fidl_next::ClientEnd<P, zx::Channel>,
230) -> fidl::endpoints::ClientEnd<M> {
231    fidl::endpoints::ClientEnd::new(client_end.into_untyped())
232}
233
234/// Converts a `fidl_next::ServerEnd` into a legacy `fidl::endpoints::ServerEnd` over a Zircon
235/// channel for APIs like `fuchsia_component::server::ServiceFs` that still accept
236/// `fidl_fuchsia_io` endpoints.
237fn into_legacy_server_end<P, M: fidl::endpoints::ProtocolMarker>(
238    server_end: fidl_next::ServerEnd<P, zx::Channel>,
239) -> fidl::endpoints::ServerEnd<M> {
240    fidl::endpoints::ServerEnd::new(server_end.into_untyped())
241}