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