session_manager_lib/
startup.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::cobalt;
use anyhow::anyhow;
use fidl::endpoints::{create_proxy, ServerEnd};
use thiserror::Error;
use tracing::info;
use {
    fidl_fuchsia_component as fcomponent, fidl_fuchsia_component_decl as fdecl,
    fidl_fuchsia_component_sandbox as fsandbox, fidl_fuchsia_io as fio,
    fidl_fuchsia_session as fsession, fuchsia_async as fasync,
};

/// Errors returned by calls startup functions.
#[derive(Debug, Error, Clone, PartialEq)]
pub enum StartupError {
    #[error("Existing session not destroyed at \"{}/{}\": {:?}", collection, name, err)]
    NotDestroyed { name: String, collection: String, err: fcomponent::Error },

    #[error("Session {} not created at \"{}/{}\": Bedrock error {:?}", url, collection, name, err)]
    BedrockError { name: String, collection: String, url: String, err: String },

    #[error("Session {} not created at \"{}/{}\": {:?}", url, collection, name, err)]
    NotCreated { name: String, collection: String, url: String, err: fcomponent::Error },

    #[error(
        "Exposed directory of session {} at \"{}/{}\" not opened: {:?}",
        url,
        collection,
        name,
        err
    )]
    ExposedDirNotOpened { name: String, collection: String, url: String, err: fcomponent::Error },

    #[error("Session {} not launched at \"{}/{}\": {:?}", url, collection, name, err)]
    NotLaunched { name: String, collection: String, url: String, err: fcomponent::Error },

    #[error("Attempt to restart a not running session")]
    NotRunning,
}

impl From<StartupError> for fsession::LaunchError {
    fn from(e: StartupError) -> fsession::LaunchError {
        match e {
            StartupError::NotDestroyed { .. } => fsession::LaunchError::DestroyComponentFailed,
            StartupError::NotCreated { err, .. } => match err {
                fcomponent::Error::InstanceCannotResolve => fsession::LaunchError::NotFound,
                _ => fsession::LaunchError::CreateComponentFailed,
            },
            StartupError::ExposedDirNotOpened { .. }
            | StartupError::BedrockError { .. }
            | StartupError::NotLaunched { .. } => fsession::LaunchError::CreateComponentFailed,
            StartupError::NotRunning => fsession::LaunchError::NotFound,
        }
    }
}

impl From<StartupError> for fsession::RestartError {
    fn from(e: StartupError) -> fsession::RestartError {
        match e {
            StartupError::NotDestroyed { .. } => fsession::RestartError::DestroyComponentFailed,
            StartupError::NotCreated { err, .. } => match err {
                fcomponent::Error::InstanceCannotResolve => fsession::RestartError::NotFound,
                _ => fsession::RestartError::CreateComponentFailed,
            },
            StartupError::ExposedDirNotOpened { .. }
            | StartupError::BedrockError { .. }
            | StartupError::NotLaunched { .. } => fsession::RestartError::CreateComponentFailed,
            StartupError::NotRunning => fsession::RestartError::NotRunning,
        }
    }
}

impl From<StartupError> for fsession::LifecycleError {
    fn from(e: StartupError) -> fsession::LifecycleError {
        match e {
            StartupError::NotDestroyed { .. } => fsession::LifecycleError::DestroyComponentFailed,
            StartupError::NotCreated { err, .. } => match err {
                fcomponent::Error::InstanceCannotResolve => {
                    fsession::LifecycleError::ResolveComponentFailed
                }
                _ => fsession::LifecycleError::CreateComponentFailed,
            },
            StartupError::ExposedDirNotOpened { .. }
            | StartupError::BedrockError { .. }
            | StartupError::NotLaunched { .. } => fsession::LifecycleError::CreateComponentFailed,
            StartupError::NotRunning => fsession::LifecycleError::NotFound,
        }
    }
}

/// The name of the session child component.
const SESSION_NAME: &str = "session";

/// The name of the child collection the session is added to, must match the declaration in
/// `session_manager.cml`.
const SESSION_CHILD_COLLECTION: &str = "session";

/// Launches the specified session.
///
/// Any existing session child will be destroyed prior to launching the new session.
///
/// Returns a controller for the session component, or an error.
///
/// # Parameters
/// - `session_url`: The URL of the session to launch.
/// - `config_capabilities`: Configuration capabilities that will target the session.
/// - `exposed_dir`: The server end on which to serve the session's exposed directory.
/// - `realm`: The realm in which to launch the session.
///
/// # Errors
/// If there was a problem creating or binding to the session component instance.
pub async fn launch_session(
    session_url: &str,
    config_capabilities: Vec<fdecl::Configuration>,
    exposed_dir: ServerEnd<fio::DirectoryMarker>,
    realm: &fcomponent::RealmProxy,
) -> Result<fcomponent::ExecutionControllerProxy, StartupError> {
    info!(session_url, "Launching session");

    let start_time = zx::MonotonicInstant::get();
    let controller = set_session(session_url, config_capabilities, realm, exposed_dir).await?;
    let end_time = zx::MonotonicInstant::get();

    fasync::Task::local(async move {
        if let Ok(cobalt_logger) = cobalt::get_logger() {
            // The result is disregarded as there is not retry-logic if it fails, and the error is
            // not meant to be fatal.
            let _ = cobalt::log_session_launch_time(cobalt_logger, start_time, end_time).await;
        }
    })
    .detach();

    Ok(controller)
}

/// Stops the current session, if any.
///
/// # Parameters
/// - `realm`: The realm in which the session exists.
///
/// # Errors
/// `StartupError::NotDestroyed` if the session component could not be destroyed.
pub async fn stop_session(realm: &fcomponent::RealmProxy) -> Result<(), StartupError> {
    realm_management::destroy_child_component(SESSION_NAME, SESSION_CHILD_COLLECTION, realm)
        .await
        .map_err(|err| StartupError::NotDestroyed {
            name: SESSION_NAME.to_string(),
            collection: SESSION_CHILD_COLLECTION.to_string(),
            err,
        })
}

async fn create_config_dict(
    config_capabilities: Vec<fdecl::Configuration>,
) -> Result<Option<fsandbox::DictionaryRef>, anyhow::Error> {
    if config_capabilities.is_empty() {
        return Ok(None);
    }
    let dict_store =
        fuchsia_component::client::connect_to_protocol::<fsandbox::CapabilityStoreMarker>()?;
    let dict_id = 1;
    dict_store.dictionary_create(dict_id).await?.map_err(|e| anyhow!("{:#?}", e))?;
    let mut config_id = 2;
    for config in config_capabilities {
        let Some(value) = config.value else { continue };
        let Some(key) = config.name else { continue };

        dict_store
            .import(
                config_id,
                fsandbox::Capability::Data(fsandbox::Data::Bytes(fidl::persist(&value)?)),
            )
            .await?
            .map_err(|e| anyhow!("{:#?}", e))?;

        dict_store
            .dictionary_insert(dict_id, &fsandbox::DictionaryItem { key, value: config_id })
            .await?
            .map_err(|e| anyhow!("{:#?}", e))?;
        config_id += 1;
    }
    let dict = dict_store.export(dict_id).await?.map_err(|e| anyhow!("{:#?}", e))?;
    let fsandbox::Capability::Dictionary(dict) = dict else {
        return Err(anyhow!("Bad bedrock capability type"));
    };
    Ok(Some(dict))
}

/// Sets the currently active session.
///
/// If an existing session is running, the session's component instance will be destroyed prior to
/// creating the new session, effectively replacing the session.
///
/// # Parameters
/// - `session_url`: The URL of the session to instantiate.
/// - `config_capabilities`: Configuration capabilities that will target the session.
/// - `realm`: The realm in which to create the session.
/// - `exposed_dir`: The server end on which the session's exposed directory will be served.
///
/// # Errors
/// Returns an error if any of the realm operations fail, or the realm is unavailable.
async fn set_session(
    session_url: &str,
    config_capabilities: Vec<fdecl::Configuration>,
    realm: &fcomponent::RealmProxy,
    exposed_dir: ServerEnd<fio::DirectoryMarker>,
) -> Result<fcomponent::ExecutionControllerProxy, StartupError> {
    realm_management::destroy_child_component(SESSION_NAME, SESSION_CHILD_COLLECTION, realm)
        .await
        .or_else(|err: fcomponent::Error| match err {
            // Since the intent is simply to clear out the existing session child if it exists,
            // related errors are disregarded.
            fcomponent::Error::InvalidArguments
            | fcomponent::Error::InstanceNotFound
            | fcomponent::Error::CollectionNotFound => Ok(()),
            _ => Err(err),
        })
        .map_err(|err| StartupError::NotDestroyed {
            name: SESSION_NAME.to_string(),
            collection: SESSION_CHILD_COLLECTION.to_string(),
            err,
        })?;

    let (controller, controller_server_end) = create_proxy::<fcomponent::ControllerMarker>();
    let create_child_args = fcomponent::CreateChildArgs {
        controller: Some(controller_server_end),
        dictionary: create_config_dict(config_capabilities).await.map_err(|err| {
            StartupError::BedrockError {
                name: SESSION_NAME.to_string(),
                collection: SESSION_CHILD_COLLECTION.to_string(),
                url: session_url.to_string(),
                err: format!("{err:#?}"),
            }
        })?,
        ..Default::default()
    };
    realm_management::create_child_component(
        SESSION_NAME,
        session_url,
        SESSION_CHILD_COLLECTION,
        create_child_args,
        realm,
    )
    .await
    .map_err(|err| StartupError::NotCreated {
        name: SESSION_NAME.to_string(),
        collection: SESSION_CHILD_COLLECTION.to_string(),
        url: session_url.to_string(),
        err,
    })?;

    realm_management::open_child_component_exposed_dir(
        SESSION_NAME,
        SESSION_CHILD_COLLECTION,
        realm,
        exposed_dir,
    )
    .await
    .map_err(|err| StartupError::ExposedDirNotOpened {
        name: SESSION_NAME.to_string(),
        collection: SESSION_CHILD_COLLECTION.to_string(),
        url: session_url.to_string(),
        err,
    })?;

    // Start the component.
    let (execution_controller, execution_controller_server_end) =
        create_proxy::<fcomponent::ExecutionControllerMarker>();
    controller
        .start(fcomponent::StartChildArgs::default(), execution_controller_server_end)
        .await
        .map_err(|_| fcomponent::Error::Internal)
        .and_then(std::convert::identity)
        .map_err(|_err| StartupError::NotLaunched {
            name: SESSION_NAME.to_string(),
            collection: SESSION_CHILD_COLLECTION.to_string(),
            url: session_url.to_string(),
            err: fcomponent::Error::InstanceCannotStart,
        })?;

    Ok(execution_controller)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::{set_session, stop_session, SESSION_CHILD_COLLECTION, SESSION_NAME};
    use anyhow::Error;
    use fidl::endpoints::{create_endpoints, spawn_stream_handler};
    use lazy_static::lazy_static;
    use session_testing::{spawn_directory_server, spawn_server};
    use test_util::Counter;
    use {fidl_fuchsia_component as fcomponent, fidl_fuchsia_io as fio};

    #[fuchsia::test]
    async fn set_session_calls_realm_methods_in_appropriate_order() -> Result<(), Error> {
        lazy_static! {
            // The number of realm calls which have been made so far.
            static ref NUM_REALM_REQUESTS: Counter = Counter::new(0);
        }

        let session_url = "session";

        let directory_request_handler = move |directory_request| match directory_request {
            fio::DirectoryRequest::Open { path: _, .. } => {
                assert_eq!(NUM_REALM_REQUESTS.get(), 4);
            }
            _ => panic!("Directory handler received an unexpected request"),
        };

        let realm = spawn_stream_handler(move |realm_request| async move {
            match realm_request {
                fcomponent::RealmRequest::DestroyChild { child, responder } => {
                    assert_eq!(NUM_REALM_REQUESTS.get(), 0);
                    assert_eq!(child.collection, Some(SESSION_CHILD_COLLECTION.to_string()));
                    assert_eq!(child.name, SESSION_NAME);

                    let _ = responder.send(Ok(()));
                }
                fcomponent::RealmRequest::CreateChild { collection, decl, args, responder } => {
                    assert_eq!(NUM_REALM_REQUESTS.get(), 1);
                    assert_eq!(decl.url.unwrap(), session_url);
                    assert_eq!(decl.name.unwrap(), SESSION_NAME);
                    assert_eq!(&collection.name, SESSION_CHILD_COLLECTION);

                    spawn_server(args.controller.unwrap(), move |controller_request| {
                        match controller_request {
                            fcomponent::ControllerRequest::Start { responder, .. } => {
                                let _ = responder.send(Ok(()));
                            }
                            fcomponent::ControllerRequest::IsStarted { .. } => unimplemented!(),
                            fcomponent::ControllerRequest::GetExposedDictionary { .. } => {
                                unimplemented!()
                            }
                            fcomponent::ControllerRequest::Destroy { .. } => {
                                unimplemented!()
                            }
                            fcomponent::ControllerRequest::_UnknownMethod { .. } => {
                                unimplemented!()
                            }
                        }
                    });

                    let _ = responder.send(Ok(()));
                }
                fcomponent::RealmRequest::OpenExposedDir { child, exposed_dir, responder } => {
                    assert_eq!(NUM_REALM_REQUESTS.get(), 2);
                    assert_eq!(child.collection, Some(SESSION_CHILD_COLLECTION.to_string()));
                    assert_eq!(child.name, SESSION_NAME);

                    spawn_directory_server(exposed_dir, directory_request_handler);
                    let _ = responder.send(Ok(()));
                }
                _ => panic!("Realm handler received an unexpected request"),
            };
            NUM_REALM_REQUESTS.inc();
        });

        let (_exposed_dir, exposed_dir_server_end) = create_endpoints::<fio::DirectoryMarker>();
        let _controller = set_session(session_url, vec![], &realm, exposed_dir_server_end).await?;

        Ok(())
    }

    #[fuchsia::test]
    async fn set_session_starts_component() -> Result<(), Error> {
        lazy_static! {
            static ref NUM_START_CALLS: Counter = Counter::new(0);
        }

        let session_url = "session";

        let realm = spawn_stream_handler(move |realm_request| async move {
            match realm_request {
                fcomponent::RealmRequest::DestroyChild { responder, .. } => {
                    let _ = responder.send(Ok(()));
                }
                fcomponent::RealmRequest::CreateChild { args, responder, .. } => {
                    spawn_server(args.controller.unwrap(), move |controller_request| {
                        match controller_request {
                            fcomponent::ControllerRequest::Start { responder, .. } => {
                                NUM_START_CALLS.inc();
                                let _ = responder.send(Ok(()));
                            }
                            fcomponent::ControllerRequest::IsStarted { .. } => unimplemented!(),
                            fcomponent::ControllerRequest::GetExposedDictionary { .. } => {
                                unimplemented!()
                            }
                            fcomponent::ControllerRequest::Destroy { .. } => {
                                unimplemented!()
                            }
                            fcomponent::ControllerRequest::_UnknownMethod { .. } => {
                                unimplemented!()
                            }
                        }
                    });
                    let _ = responder.send(Ok(()));
                }
                fcomponent::RealmRequest::OpenExposedDir { responder, .. } => {
                    let _ = responder.send(Ok(()));
                }
                _ => panic!("Realm handler received an unexpected request"),
            };
        });

        let (_exposed_dir, exposed_dir_server_end) = create_endpoints::<fio::DirectoryMarker>();
        let _controller = set_session(session_url, vec![], &realm, exposed_dir_server_end).await?;
        assert_eq!(NUM_START_CALLS.get(), 1);

        Ok(())
    }

    #[fuchsia::test]
    async fn stop_session_calls_destroy_child() -> Result<(), Error> {
        lazy_static! {
            static ref NUM_DESTROY_CHILD_CALLS: Counter = Counter::new(0);
        }

        let realm = spawn_stream_handler(move |realm_request| async move {
            match realm_request {
                fcomponent::RealmRequest::DestroyChild { child, responder } => {
                    assert_eq!(NUM_DESTROY_CHILD_CALLS.get(), 0);
                    assert_eq!(child.collection, Some(SESSION_CHILD_COLLECTION.to_string()));
                    assert_eq!(child.name, SESSION_NAME);

                    let _ = responder.send(Ok(()));
                }
                _ => panic!("Realm handler received an unexpected request"),
            };
            NUM_DESTROY_CHILD_CALLS.inc();
        });

        stop_session(&realm).await?;
        assert_eq!(NUM_DESTROY_CHILD_CALLS.get(), 1);

        Ok(())
    }
}