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    pub(crate) fn new(
100        root_dispatcher: DispatcherRef<'static>,
101        mut start_args: DriverStartArgs,
102    ) -> Result<Self, Status> {
103        let incoming_namespace: Namespace = start_args
104            .incoming
105            .take()
106            .unwrap_or_default()
107            .try_into()
108            .map_err(|_| Status::INVALID_ARGS)?;
109        let incoming = Incoming::from(incoming_namespace);
110        Ok(DriverContext { root_dispatcher, start_args, incoming })
111    }
112
113    pub(crate) fn start_logging(&self, driver_name: &str) -> Result<(), Status> {
114        let log_client = match self.incoming.connect_protocol() {
115            Ok(log_client) => log_client,
116            Err(err) => {
117                eprintln!(
118                    "Error connecting to log sink proxy at driver startup: {err}. Continuing without logging."
119                );
120                return Ok(());
121            }
122        };
123
124        if let Err(e) = diagnostics_log::initialize(
125            diagnostics_log::PublishOptions::default()
126                .use_log_sink(log_client)
127                .tags(&["driver", driver_name]),
128        ) {
129            eprintln!("Error initializing logging at driver startup: {e}");
130        }
131        Ok(())
132    }
133}