component_debug/cli/
run.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// Copyright 2023 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::cli::format::{
    format_create_error, format_destroy_error, format_resolve_error, format_start_error,
};
use crate::lifecycle::{
    create_instance_in_collection, destroy_instance_in_collection, resolve_instance,
    start_instance, start_instance_with_args, ActionError, CreateError, DestroyError, StartError,
};
use anyhow::{bail, format_err, Result};
use fidl::HandleBased;
use fuchsia_url::AbsoluteComponentUrl;
use futures::future::BoxFuture;
use futures::AsyncReadExt;
use moniker::Moniker;
use std::io::Read;
use {
    fidl_fuchsia_component as fcomponent, fidl_fuchsia_component_decl as fdecl,
    fidl_fuchsia_process as fprocess, fidl_fuchsia_sys2 as fsys,
};

// This value is fairly arbitrary. The value matches `MAX_BUF` from `fuchsia.io`, but that
// constant is for `fuchsia.io.File` transfers, which are unrelated to these `zx::socket`
// transfers.
const TRANSFER_CHUNK_SIZE: usize = 8192;

async fn copy<W: std::io::Write>(source: fidl::Socket, mut sink: W) -> Result<()> {
    let mut source = fuchsia_async::Socket::from_socket(source);
    let mut buf = [0u8; TRANSFER_CHUNK_SIZE];
    loop {
        let bytes_read = source.read(&mut buf).await?;
        if bytes_read == 0 {
            return Ok(());
        }
        sink.write_all(&buf[..bytes_read])?;
        sink.flush()?;
    }
}

// The normal Rust representation of this constant is in fuchsia-runtime, which
// cannot be used on host. Maybe there's a way to move fruntime::HandleType and
// fruntime::HandleInfo to a place that can be used on host?
fn handle_id_for_fd(fd: u32) -> u32 {
    const PA_FD: u32 = 0x30;
    PA_FD | fd << 16
}

struct Stdio {
    local_in: fidl::Socket,
    local_out: fidl::Socket,
    local_err: fidl::Socket,
}

impl Stdio {
    fn new() -> (Self, Vec<fprocess::HandleInfo>) {
        let (local_in, remote_in) = fidl::Socket::create_stream();
        let (local_out, remote_out) = fidl::Socket::create_stream();
        let (local_err, remote_err) = fidl::Socket::create_stream();

        (
            Self { local_in, local_out, local_err },
            vec![
                fprocess::HandleInfo { handle: remote_in.into_handle(), id: handle_id_for_fd(0) },
                fprocess::HandleInfo { handle: remote_out.into_handle(), id: handle_id_for_fd(1) },
                fprocess::HandleInfo { handle: remote_err.into_handle(), id: handle_id_for_fd(2) },
            ],
        )
    }

    async fn forward(self) {
        let local_in = self.local_in;
        let local_out = self.local_out;
        let local_err = self.local_err;

        std::thread::spawn(move || {
            let mut term_in = std::io::stdin().lock();
            let mut buf = [0u8; TRANSFER_CHUNK_SIZE];
            loop {
                let bytes_read = term_in.read(&mut buf)?;
                if bytes_read == 0 {
                    return Ok::<(), anyhow::Error>(());
                }
                local_in.write(&buf[..bytes_read])?;
            }
        });

        std::thread::spawn(move || {
            let mut executor = fuchsia_async::LocalExecutor::new();
            let _result: Result<()> = executor
                .run_singlethreaded(async move { copy(local_err, std::io::stderr()).await });
        });

        std::thread::spawn(move || {
            let mut executor = fuchsia_async::LocalExecutor::new();
            let _result: Result<()> = executor
                .run_singlethreaded(async move { copy(local_out, std::io::stdout().lock()).await });
            std::process::exit(0);
        });

        // If we're following stdio, we just wait forever. When stdout is
        // closed, the whole process will exit.
        let () = futures::future::pending().await;
    }
}

pub async fn run_cmd<W: std::io::Write>(
    moniker: Moniker,
    url: AbsoluteComponentUrl,
    recreate: bool,
    connect_stdio: bool,
    config_overrides: Vec<fdecl::ConfigOverride>,
    lifecycle_controller_factory: impl Fn()
        -> BoxFuture<'static, Result<fsys::LifecycleControllerProxy>>,
    mut writer: W,
) -> Result<()> {
    let lifecycle_controller = lifecycle_controller_factory().await?;
    let parent = moniker
        .parent()
        .ok_or_else(|| format_err!("Error: {} does not reference a dynamic instance", moniker))?;
    let leaf = moniker
        .leaf()
        .ok_or_else(|| format_err!("Error: {} does not reference a dynamic instance", moniker))?;
    let child_name = leaf.name();
    let collection = leaf
        .collection()
        .ok_or_else(|| format_err!("Error: {} does not reference a dynamic instance", moniker))?;

    if recreate {
        // First try to destroy any existing instance at this monker.
        match destroy_instance_in_collection(&lifecycle_controller, &parent, collection, child_name)
            .await
        {
            Ok(()) => {
                writeln!(writer, "Destroyed existing component instance at {}...", moniker)?;
            }
            Err(DestroyError::ActionError(ActionError::InstanceNotFound))
            | Err(DestroyError::ActionError(ActionError::InstanceNotResolved)) => {
                // No resolved component exists at this moniker. Nothing to do.
            }
            Err(e) => return Err(format_destroy_error(&moniker, e)),
        }
    }

    writeln!(writer, "URL: {}", url)?;
    writeln!(writer, "Moniker: {}", moniker)?;
    writeln!(writer, "Creating component instance...")?;

    // First try to use StartWithArgs

    let (mut maybe_stdio, numbered_handles) = if connect_stdio {
        let (stdio, numbered_handles) = Stdio::new();
        (Some(stdio), Some(numbered_handles))
    } else {
        (None, Some(vec![]))
    };

    let create_result = create_instance_in_collection(
        &lifecycle_controller,
        &parent,
        collection,
        child_name,
        &url,
        config_overrides.clone(),
        None,
    )
    .await;

    match create_result {
        Err(CreateError::InstanceAlreadyExists) => {
            bail!("\nError: {} already exists.\nUse --recreate to destroy and create a new instance, or provide a different moniker.\n", moniker)
        }
        Err(e) => {
            return Err(format_create_error(&moniker, &parent, collection, e));
        }
        Ok(()) => {}
    }

    writeln!(writer, "Resolving component instance...")?;
    resolve_instance(&lifecycle_controller, &moniker)
        .await
        .map_err(|e| format_resolve_error(&moniker, e))?;

    writeln!(writer, "Starting component instance...")?;
    let start_args = fcomponent::StartChildArgs { numbered_handles, ..Default::default() };
    let res = start_instance_with_args(&lifecycle_controller, &moniker, start_args).await;
    if let Err(StartError::ActionError(ActionError::Fidl(_e))) = &res {
        // A FIDL error here could indicate that we're talking to a version of component manager
        // that does not support `fuchsia.sys2/LifecycleController.StartInstanceWithArgs`. Let's
        // try again with `fuchsia.sys2/LifecycleController.StartInstance`.

        // Component manager will close the lifecycle controller when it encounters a FIDL error,
        // so we need to create a new one.
        let lifecycle_controller = lifecycle_controller_factory().await?;

        if connect_stdio {
            // We want to provide stdio handles to the component, but this is only possible when
            // creating an instance when we have to use the legacy `StartInstance`. Delete and
            // recreate the component, providing the handles to the create call.

            let (stdio, numbered_handles) = Stdio::new();
            maybe_stdio = Some(stdio);
            let create_args = fcomponent::CreateChildArgs {
                numbered_handles: Some(numbered_handles),
                ..Default::default()
            };

            destroy_instance_in_collection(&lifecycle_controller, &parent, collection, child_name)
                .await?;
            create_instance_in_collection(
                &lifecycle_controller,
                &parent,
                collection,
                child_name,
                &url,
                config_overrides,
                Some(create_args),
            )
            .await?;
            resolve_instance(&lifecycle_controller, &moniker)
                .await
                .map_err(|e| format_resolve_error(&moniker, e))?;
        }

        let _stop_future = start_instance(&lifecycle_controller, &moniker)
            .await
            .map_err(|e| format_start_error(&moniker, e))?;
    } else {
        let _stop_future = res.map_err(|e| format_start_error(&moniker, e))?;
    }

    if let Some(stdio) = maybe_stdio {
        stdio.forward().await;
    }

    writeln!(writer, "Component instance is running!")?;

    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;
    use fidl::endpoints::create_proxy_and_stream;
    use fidl_fuchsia_sys2 as fsys;
    use futures::{FutureExt, TryStreamExt};

    fn setup_fake_lifecycle_controller_ok(
        expected_parent_moniker: &'static str,
        expected_collection: &'static str,
        expected_name: &'static str,
        expected_url: &'static str,
        expected_moniker: &'static str,
        expect_destroy: bool,
    ) -> fsys::LifecycleControllerProxy {
        let (lifecycle_controller, mut stream) =
            create_proxy_and_stream::<fsys::LifecycleControllerMarker>();
        fuchsia_async::Task::local(async move {
            if expect_destroy {
                let req = stream.try_next().await.unwrap().unwrap();
                match req {
                    fsys::LifecycleControllerRequest::DestroyInstance {
                        parent_moniker,
                        child,
                        responder,
                    } => {
                        assert_eq!(
                            Moniker::parse_str(expected_parent_moniker),
                            Moniker::parse_str(&parent_moniker)
                        );
                        assert_eq!(expected_name, child.name);
                        assert_eq!(expected_collection, child.collection.unwrap());
                        responder.send(Ok(())).unwrap();
                    }
                    _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
                }
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::CreateInstance {
                    parent_moniker,
                    collection,
                    decl,
                    responder,
                    args: _,
                } => {
                    assert_eq!(
                        Moniker::parse_str(expected_parent_moniker),
                        Moniker::parse_str(&parent_moniker)
                    );
                    assert_eq!(expected_collection, collection.name);
                    assert_eq!(expected_name, decl.name.unwrap());
                    assert_eq!(expected_url, decl.url.unwrap());
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::ResolveInstance { moniker, responder } => {
                    assert_eq!(Moniker::parse_str(expected_moniker), Moniker::parse_str(&moniker));
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::StartInstanceWithArgs {
                    moniker,
                    binder: _,
                    args: _,
                    responder,
                } => {
                    assert_eq!(Moniker::parse_str(expected_moniker), Moniker::parse_str(&moniker));
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }
        })
        .detach();
        lifecycle_controller
    }

    fn setup_fake_lifecycle_controller_fail(
        expected_parent_moniker: &'static str,
        expected_collection: &'static str,
        expected_name: &'static str,
        expected_url: &'static str,
    ) -> fsys::LifecycleControllerProxy {
        let (lifecycle_controller, mut stream) =
            create_proxy_and_stream::<fsys::LifecycleControllerMarker>();
        fuchsia_async::Task::local(async move {
            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::DestroyInstance {
                    parent_moniker,
                    child,
                    responder,
                } => {
                    assert_eq!(
                        Moniker::parse_str(expected_parent_moniker),
                        Moniker::parse_str(&parent_moniker)
                    );
                    assert_eq!(expected_name, child.name);
                    assert_eq!(expected_collection, child.collection.unwrap());
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::CreateInstance {
                    parent_moniker,
                    collection,
                    decl,
                    responder,
                    args: _,
                } => {
                    assert_eq!(
                        Moniker::parse_str(expected_parent_moniker),
                        Moniker::parse_str(&parent_moniker)
                    );
                    assert_eq!(expected_collection, collection.name);
                    assert_eq!(expected_name, decl.name.unwrap());
                    assert_eq!(expected_url, decl.url.unwrap());
                    responder.send(Err(fsys::CreateError::InstanceAlreadyExists)).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }
        })
        .detach();
        lifecycle_controller
    }

    fn setup_fake_lifecycle_controller_recreate(
        expected_parent_moniker: &'static str,
        expected_collection: &'static str,
        expected_name: &'static str,
        expected_url: &'static str,
        expected_moniker: &'static str,
    ) -> fsys::LifecycleControllerProxy {
        let (lifecycle_controller, mut stream) =
            create_proxy_and_stream::<fsys::LifecycleControllerMarker>();
        fuchsia_async::Task::local(async move {
            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::DestroyInstance {
                    parent_moniker,
                    child,
                    responder,
                } => {
                    assert_eq!(
                        Moniker::parse_str(expected_parent_moniker),
                        Moniker::parse_str(&parent_moniker)
                    );
                    assert_eq!(expected_name, child.name);
                    assert_eq!(expected_collection, child.collection.unwrap());
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::CreateInstance {
                    parent_moniker,
                    collection,
                    decl,
                    responder,
                    args: _,
                } => {
                    assert_eq!(
                        Moniker::parse_str(expected_parent_moniker),
                        Moniker::parse_str(&parent_moniker)
                    );
                    assert_eq!(expected_collection, collection.name);
                    assert_eq!(expected_name, decl.name.unwrap());
                    assert_eq!(expected_url, decl.url.unwrap());
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::ResolveInstance { moniker, responder } => {
                    assert_eq!(Moniker::parse_str(expected_moniker), Moniker::parse_str(&moniker));
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }

            let req = stream.try_next().await.unwrap().unwrap();
            match req {
                fsys::LifecycleControllerRequest::StartInstanceWithArgs {
                    moniker,
                    binder: _,
                    args: _,
                    responder,
                } => {
                    assert_eq!(Moniker::parse_str(expected_moniker), Moniker::parse_str(&moniker));
                    responder.send(Ok(())).unwrap();
                }
                _ => panic!("Unexpected Lifecycle Controller request: {:?}", req),
            }
        })
        .detach();
        lifecycle_controller
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_ok() -> Result<()> {
        let mut output = Vec::new();
        let lifecycle_controller = setup_fake_lifecycle_controller_ok(
            "/some",
            "collection",
            "name",
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm",
            "/some/collection:name",
            true,
        );
        let response = run_cmd(
            "/some/collection:name".try_into().unwrap(),
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm".try_into().unwrap(),
            true,
            false,
            vec![],
            move || {
                let lifecycle_controller = lifecycle_controller.clone();
                async move { Ok(lifecycle_controller) }.boxed()
            },
            &mut output,
        )
        .await;
        response.unwrap();
        Ok(())
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_name() -> Result<()> {
        let mut output = Vec::new();
        let lifecycle_controller = setup_fake_lifecycle_controller_ok(
            "/core",
            "ffx-laboratory",
            "foobar",
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm",
            "/core/ffx-laboratory:foobar",
            false,
        );
        let response = run_cmd(
            "/core/ffx-laboratory:foobar".try_into().unwrap(),
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm".try_into().unwrap(),
            false,
            false,
            vec![],
            move || {
                let lifecycle_controller = lifecycle_controller.clone();
                async move { Ok(lifecycle_controller) }.boxed()
            },
            &mut output,
        )
        .await;
        response.unwrap();
        Ok(())
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_fail() -> Result<()> {
        let mut output = Vec::new();
        let lifecycle_controller = setup_fake_lifecycle_controller_fail(
            "/core",
            "ffx-laboratory",
            "test",
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm",
        );
        let response = run_cmd(
            "/core/ffx-laboratory:test".try_into().unwrap(),
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm".try_into().unwrap(),
            true,
            false,
            vec![],
            move || {
                let lifecycle_controller = lifecycle_controller.clone();
                async move { Ok(lifecycle_controller) }.boxed()
            },
            &mut output,
        )
        .await;
        response.unwrap_err();
        Ok(())
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_recreate() -> Result<()> {
        let mut output = Vec::new();
        let lifecycle_controller = setup_fake_lifecycle_controller_recreate(
            "/core",
            "ffx-laboratory",
            "test",
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm",
            "/core/ffx-laboratory:test",
        );
        let response = run_cmd(
            "/core/ffx-laboratory:test".try_into().unwrap(),
            "fuchsia-pkg://fuchsia.com/test#meta/test.cm".try_into().unwrap(),
            true,
            false,
            vec![],
            move || {
                let lifecycle_controller = lifecycle_controller.clone();
                async move { Ok(lifecycle_controller) }.boxed()
            },
            &mut output,
        )
        .await;
        response.unwrap();
        Ok(())
    }
}