persistence/
lib.rs

1// Copyright 2020 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
5//! `diagnostics-persistence` component persists Inspect VMOs and serves them at the next boot.
6
7mod constants;
8mod fetcher;
9mod file_handler;
10mod inspect_server;
11mod persist_server;
12mod scheduler;
13
14use anyhow::{bail, format_err, Context, Error};
15use argh::FromArgs;
16use fetcher::Fetcher;
17use fidl::endpoints;
18use fuchsia_component::client;
19use fuchsia_component::server::ServiceFs;
20use fuchsia_inspect::component;
21use fuchsia_inspect::health::Reporter;
22use futures::{StreamExt, TryStreamExt};
23use log::*;
24use persist_server::PersistServer;
25use persistence_config::Config;
26use scheduler::Scheduler;
27use zx::BootInstant;
28use {
29    fidl_fuchsia_component_sandbox as fsandbox, fidl_fuchsia_update as fupdate,
30    fuchsia_async as fasync,
31};
32
33/// The name of the subcommand and the logs-tag.
34pub const PROGRAM_NAME: &str = "persistence";
35pub const PERSIST_NODE_NAME: &str = "persist";
36/// Added after persisted data is fully published
37pub const PUBLISHED_TIME_KEY: &str = "published";
38
39/// Command line args
40#[derive(FromArgs, Debug, PartialEq)]
41#[argh(subcommand, name = "persistence")]
42pub struct CommandLine {}
43
44// on_error logs any errors from `value` and then returns a Result.
45// value must return a Result; error_message must contain one {} to put the error in.
46macro_rules! on_error {
47    ($value:expr, $error_message:expr) => {
48        $value.or_else(|e| {
49            let message = format!($error_message, e);
50            warn!("{}", message);
51            bail!("{}", message)
52        })
53    };
54}
55
56pub async fn main(_args: CommandLine) -> Result<(), Error> {
57    info!("Starting Diagnostics Persistence Service service");
58    let mut health = component::health();
59    let config =
60        on_error!(persistence_config::load_configuration_files(), "Error loading configs: {}")?;
61    let inspector = component::inspector();
62    let _inspect_server_task =
63        inspect_runtime::publish(inspector, inspect_runtime::PublishOptions::default());
64
65    file_handler::forget_old_data(&config);
66
67    // Create the Inspect fetcher
68    let (fetch_requester, _fetcher_task) =
69        on_error!(Fetcher::new(&config), "Error initializing fetcher: {}")?;
70
71    let scheduler = Scheduler::new(fetch_requester, &config);
72
73    // Add a persistence fidl service for each service defined in the config files.
74    let scope = fasync::Scope::new();
75    let services_scope = scope.new_child_with_name("services");
76
77    let _service_scopes = spawn_persist_services(&config, scheduler, &services_scope)
78        .await
79        .expect("Error spawning persist services");
80
81    // Before serving previous data, wait until the post-boot system update check has finished.
82    // Note: We're already accepting persist requests. If we receive a request, store
83    // some data, and then cache is cleared after data is persisted, that data will be lost. This
84    // is correct behavior - we don't want to remember anything from before the cache was cleared.
85    scope.spawn(async move {
86        info!("Waiting for post-boot update check...");
87        let (notifier_client, mut notifier_request_stream) =
88            fidl::endpoints::create_request_stream::<fupdate::NotifierMarker>();
89        match fuchsia_component::client::connect_to_protocol::<fupdate::ListenerMarker>() {
90            Ok(proxy) => {
91                if let Err(e) = proxy.notify_on_first_update_check(
92                    fupdate::ListenerNotifyOnFirstUpdateCheckRequest {
93                        notifier: Some(notifier_client),
94                        ..Default::default()
95                    },
96                ) {
97                    error!(e:?; "Error subscribing to first update check; not publishing");
98                    return;
99                }
100            }
101            Err(e) => {
102                warn!(
103                    e:?;
104                    "Unable to connect to fuchsia.update.Listener; will publish immediately"
105                );
106            }
107        }
108
109        match notifier_request_stream.try_next().await {
110            Ok(Some(fupdate::NotifierRequest::Notify { control_handle: _ })) => {}
111            Ok(None) => {
112                warn!("Did not receive update notification; not publishing");
113                return;
114            }
115            Err(e) => {
116                error!("Error waiting for update notification; not publishing: {e}");
117                return;
118            }
119        }
120
121        // Start serving previous boot data
122        info!("...Update check has completed; publishing previous boot data");
123        inspector.root().record_child(PERSIST_NODE_NAME, |node| {
124            inspect_server::serve_persisted_data(node);
125            health.set_ok();
126            info!("Diagnostics Persistence Service ready");
127        });
128        inspector.root().record_int(PUBLISHED_TIME_KEY, BootInstant::get().into_nanos());
129    });
130
131    scope.await;
132
133    Ok(())
134}
135
136enum IncomingRequest {
137    Router(fsandbox::DictionaryRouterRequestStream),
138}
139
140// Serve a DataPersistence capability for each service defined in `config` using
141// a dynamic dictionary.
142async fn spawn_persist_services(
143    config: &Config,
144    scheduler: Scheduler,
145    scope: &fasync::Scope,
146) -> Result<Vec<fasync::Scope>, Error> {
147    let store = client::connect_to_protocol::<fsandbox::CapabilityStoreMarker>().unwrap();
148    let id_gen = sandbox::CapabilityIdGenerator::new();
149
150    let services_dict = id_gen.next();
151    store
152        .dictionary_create(services_dict)
153        .await
154        .context("Failed to send FIDL to create dictionary")?
155        .map_err(|e| format_err!("Failed to create dictionary: {e:?}"))?;
156
157    // Register each service with the exposed CFv2 dynamic dictionary.
158    let mut service_scopes = Vec::with_capacity(config.len());
159
160    for (service_name, tags) in config {
161        let connector_id = id_gen.next();
162        let (receiver, receiver_stream) =
163            endpoints::create_request_stream::<fsandbox::ReceiverMarker>();
164
165        store
166            .connector_create(connector_id, receiver)
167            .await
168            .context("Failed to send FIDL to create connector")?
169            .map_err(|e| format_err!("Failed to create connector: {e:?}"))?;
170
171        store
172            .dictionary_insert(
173                services_dict,
174                &fsandbox::DictionaryItem {
175                    key: format!("{}-{}", constants::PERSIST_SERVICE_NAME_PREFIX, service_name),
176                    value: connector_id,
177                },
178            )
179            .await
180            .context(
181                "Failed to send FIDL to insert into diagnostics-persist-capabilities dictionary",
182            )?
183            .map_err(|e| {
184                format_err!(
185                    "Failed to insert into diagnostics-persist-capabilities dictionary: {e:?}"
186                )
187            })?;
188
189        let service_scope = scope.new_child_with_name(service_name.clone());
190        PersistServer::spawn(
191            service_name.clone(),
192            tags.keys().cloned().collect(),
193            scheduler.clone(),
194            &service_scope,
195            receiver_stream,
196        );
197        service_scopes.push(service_scope);
198    }
199
200    // Expose the dynamic dictionary.
201    let mut fs = ServiceFs::new();
202    fs.dir("svc").add_fidl_service(IncomingRequest::Router);
203    fs.take_and_serve_directory_handle().expect("Failed to take service directory handle");
204    scope.spawn(fs.for_each_concurrent(None, move |IncomingRequest::Router(mut stream)| {
205        let store = store.clone();
206        let id_gen = id_gen.clone();
207        async move {
208            while let Ok(Some(request)) = stream.try_next().await {
209                match request {
210                    fsandbox::DictionaryRouterRequest::Route { payload: _, responder } => {
211                        let dup_dict_id = id_gen.next();
212                        store.duplicate(services_dict, dup_dict_id).await.unwrap().unwrap();
213                        let capability = store.export(dup_dict_id).await.unwrap().unwrap();
214                        let fsandbox::Capability::Dictionary(dict) = capability else {
215                            panic!("capability was not a dictionary? {capability:?}");
216                        };
217                        let _ = responder
218                            .send(Ok(fsandbox::DictionaryRouterRouteResponse::Dictionary(dict)));
219                    }
220                    fsandbox::DictionaryRouterRequest::_UnknownMethod { ordinal, .. } => {
221                        warn!(ordinal:%; "Unknown DictionaryRouter request");
222                    }
223                }
224            }
225        }
226    }));
227
228    Ok(service_scopes)
229}