iquery/commands/
utils.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
// Copyright 2020 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::commands::types::{Command, DiagnosticsProvider};
use crate::commands::ListCommand;
use crate::types::Error;
use anyhow::anyhow;
use cm_rust::{ExposeDeclCommon, ExposeSource, SourceName};
use component_debug::dirs::*;
use component_debug::realm::*;
use fidl::endpoints::DiscoverableProtocolMarker;
use fidl_fuchsia_diagnostics::{All, ArchiveAccessorMarker, Selector, TreeNames};
use fuchsia_fs::directory;
use moniker::Moniker;
use {fidl_fuchsia_io as fio, fidl_fuchsia_sys2 as fsys2};

const ACCESSORS_DICTIONARY: &str = "diagnostics-accessors";

/// Attempt to connect to the `fuchsia.diagnostics.*ArchiveAccessor` with the selector
/// specified.
pub async fn connect_accessor<P: DiscoverableProtocolMarker>(
    moniker: &Moniker,
    accessor_name: &str,
    proxy: &fsys2::RealmQueryProxy,
) -> Result<P::Proxy, Error> {
    let proxy = connect_to_instance_protocol_at_path::<P>(
        moniker,
        OpenDirType::Exposed,
        &format!("{ACCESSORS_DICTIONARY}/{accessor_name}"),
        proxy,
    )
    .await
    .map_err(|e| Error::ConnectToProtocol(accessor_name.to_string(), anyhow!("{:?}", e)))?;
    Ok(proxy)
}

/// Returns the selectors for a component whose url contains the `manifest` string.
pub async fn get_selectors_for_manifest<P: DiagnosticsProvider>(
    manifest: String,
    tree_selectors: Vec<String>,
    accessor: Option<String>,
    provider: &P,
) -> Result<Vec<Selector>, Error> {
    let list_command = ListCommand {
        manifest: Some(manifest.clone()),
        component: None,
        with_url: false,
        accessor: accessor.clone(),
    };
    let monikers = list_command
        .execute(provider)
        .await?
        .into_inner()
        .into_iter()
        .map(|item| item.into_moniker())
        .collect::<Vec<_>>();
    if monikers.is_empty() {
        Err(Error::ManifestNotFound(manifest.clone()))
    } else if tree_selectors.is_empty() {
        Ok(monikers
            .into_iter()
            .map(|moniker| {
                let selector_string = format!("{moniker}:root");
                selectors::parse_verbose(&selector_string)
                    .map_err(|e| Error::ParseSelector(selector_string, e.into()))
            })
            .collect::<Result<Vec<_>, _>>()?)
    } else {
        Ok(monikers
            .into_iter()
            .flat_map(|moniker| {
                tree_selectors.iter().map(move |tree_selector| {
                    let selector_string = format!("{moniker}:{tree_selector}");
                    selectors::parse_verbose(&selector_string)
                        .map_err(|e| Error::ParseSelector(selector_string, e.into()))
                })
            })
            .collect::<Result<Vec<_>, _>>()?)
    }
}

async fn fuzzy_search(
    query: &str,
    realm_query: &fsys2::RealmQueryProxy,
) -> Result<Instance, Error> {
    let mut instances = component_debug::query::get_instances_from_query(query, realm_query)
        .await
        .map_err(Error::FuzzyMatchRealmQuery)?;
    if instances.is_empty() {
        return Err(Error::SearchParameterNotFound(query.to_string()));
    } else if instances.len() > 1 {
        return Err(Error::FuzzyMatchTooManyMatches(
            instances.into_iter().map(|i| i.moniker.to_string()).collect(),
        ));
    }

    Ok(instances.pop().unwrap())
}

pub async fn process_fuzzy_inputs<P: DiagnosticsProvider>(
    queries: impl IntoIterator<Item = String>,
    provider: &P,
) -> Result<Vec<Selector>, Error> {
    let mut queries = queries.into_iter().peekable();
    if queries.peek().is_none() {
        return Ok(vec![]);
    }

    let realm_query = provider.realm_query();
    let mut results = vec![];
    for value in queries {
        match fuzzy_search(&value, realm_query).await {
            // try again in case this is a fully escaped moniker or selector
            Err(Error::SearchParameterNotFound(_)) => {
                // In case they included a tree-selector segment, attempt to parse but don't bail
                // on failure
                if let Ok(selector) = selectors::parse_verbose(&value) {
                    results.push(selector);
                } else {
                    // Note the lack of `sanitize_moniker_for_selectors`. `value` is assumed to
                    // either
                    //   A) Be a component that isn't running; therefore the selector being
                    //      right or wrong is irrelevant
                    //   B) Already be sanitized by the caller
                    let selector_string = format!("{}:root", value);
                    results.push(
                        selectors::parse_verbose(&selector_string)
                            .map_err(|e| Error::ParseSelector(selector_string, e.into()))?,
                    )
                }
            }
            Err(e) => return Err(e),
            Ok(instance) => {
                let selector_string = format!(
                    "{}:root",
                    selectors::sanitize_moniker_for_selectors(instance.moniker.to_string()),
                );
                results.push(
                    selectors::parse_verbose(&selector_string)
                        .map_err(|e| Error::ParseSelector(selector_string, e.into()))?,
                )
            }
        }
    }

    Ok(results)
}

/// Returns the selectors for a component whose url, manifest, or moniker contains the
/// `component` string.
pub async fn process_component_query_with_partial_selectors<P: DiagnosticsProvider>(
    component: String,
    tree_selectors: impl Iterator<Item = String>,
    provider: &P,
) -> Result<Vec<Selector>, Error> {
    let mut tree_selectors = tree_selectors.into_iter().peekable();
    let realm_query = provider.realm_query();
    let instance = fuzzy_search(component.as_str(), realm_query).await?;

    let mut results = vec![];
    if tree_selectors.peek().is_none() {
        let selector_string = format!(
            "{}:root",
            selectors::sanitize_moniker_for_selectors(instance.moniker.to_string())
        );
        results
            .push(selectors::parse_verbose(&selector_string).map_err(Error::PartialSelectorHint)?);
    } else {
        for s in tree_selectors {
            let selector_string = format!(
                "{}:{}",
                selectors::sanitize_moniker_for_selectors(instance.moniker.to_string()),
                s
            );
            results.push(
                selectors::parse_verbose(&selector_string).map_err(Error::PartialSelectorHint)?,
            )
        }
    }

    Ok(results)
}

fn add_tree_name(selector: &mut Selector, tree_name: String) -> Result<(), Error> {
    match selector.tree_names {
        None => selector.tree_names = Some(TreeNames::Some(vec![tree_name])),
        Some(ref mut names) => match names {
            TreeNames::Some(ref mut names) => {
                if !names.iter().any(|n| n == &tree_name) {
                    names.push(tree_name)
                }
            }
            TreeNames::All(_) => {}
            TreeNames::__SourceBreaking { unknown_ordinal } => {
                let unknown_ordinal = *unknown_ordinal;
                return Err(Error::InvalidSelector(format!(
                    "selector had invalid TreeNames variant {unknown_ordinal}: {:?}",
                    selector,
                )));
            }
        },
    }
    Ok(())
}

/// Expand selectors with a tree name. If a tree name is given, the selectors will be guaranteed to
/// include the tree name given unless they already have a tree name set. If no tree name is given
/// and the selectors carry no tree name, then they'll be updated to target all tree names
/// associated with the component.
pub fn ensure_tree_field_is_set(
    selectors: &mut Vec<Selector>,
    tree_name: Option<String>,
) -> Result<(), Error> {
    if selectors.is_empty() {
        let Some(tree_name) = tree_name else {
            return Ok(());
        };

        // Safety: "**:*" is a valid selector
        let mut selector = selectors::parse_verbose("**:*").unwrap();
        selector.tree_names = Some(TreeNames::Some(vec![tree_name]));
        selectors.push(selector);
        return Ok(());
    }

    for selector in selectors.iter_mut() {
        if let Some(tree_name) = &tree_name {
            add_tree_name(selector, tree_name.clone())?;
        } else if selector.tree_names.is_none() {
            selector.tree_names = Some(TreeNames::All(All {}))
        }
    }

    Ok(())
}

/// Get all the exposed `ArchiveAccessor` from any child component which
/// directly exposes them or places them in its outgoing directory.
pub async fn get_accessor_selectors(
    realm_query: &fsys2::RealmQueryProxy,
) -> Result<Vec<String>, Error> {
    let mut result = vec![];
    let instances = get_all_instances(realm_query).await?;
    for instance in instances {
        match get_resolved_declaration(&instance.moniker, realm_query).await {
            Err(GetDeclarationError::InstanceNotFound(_))
            | Err(GetDeclarationError::InstanceNotResolved(_)) => continue,
            Err(err) => return Err(err.into()),
            Ok(decl) => {
                for capability in decl.capabilities {
                    let capability_name = capability.name().to_string();
                    if capability_name != ACCESSORS_DICTIONARY {
                        continue;
                    }
                    if !decl.exposes.iter().any(|expose| {
                        expose.source_name() == capability.name()
                            && *expose.source() == ExposeSource::Self_
                    }) {
                        continue;
                    }

                    let Ok(dir_proxy) = open_instance_subdir_readable(
                        &instance.moniker,
                        OpenDirType::Exposed,
                        ACCESSORS_DICTIONARY,
                        realm_query,
                    )
                    .await
                    else {
                        continue;
                    };

                    let Ok(entries) = directory::readdir(&dir_proxy).await else {
                        continue;
                    };

                    for entry in entries {
                        let directory::DirEntry { name, kind: fio::DirentType::Service } = entry
                        else {
                            continue;
                        };
                        // This skips .host accessors intentionally.
                        if !name.starts_with(ArchiveAccessorMarker::PROTOCOL_NAME) {
                            continue;
                        }
                        result.push(format!("{}:{name}", instance.moniker));
                    }
                }
            }
        }
    }
    result.sort();
    Ok(result)
}

#[cfg(test)]
mod test {
    use super::*;
    use assert_matches::assert_matches;
    use iquery_test_support::{MockRealmQuery, MockRealmQueryBuilder};
    use selectors::parse_verbose;
    use std::rc::Rc;

    #[fuchsia::test]
    async fn test_get_accessors() {
        let fake_realm_query = Rc::new(MockRealmQuery::default());
        let realm_query = Rc::clone(&fake_realm_query).get_proxy().await;

        let res = get_accessor_selectors(&realm_query).await;

        assert_matches!(res, Ok(_));

        assert_eq!(
            res.unwrap(),
            vec![
                String::from("example/component:fuchsia.diagnostics.ArchiveAccessor"),
                String::from("foo/bar/thing:instance:fuchsia.diagnostics.ArchiveAccessor.feedback"),
                String::from("foo/component:fuchsia.diagnostics.ArchiveAccessor.feedback"),
            ]
        );
    }

    #[fuchsia::test]
    fn test_ensure_tree_field_is_set() {
        let name = Some("abc".to_string());
        let expected = vec![
            parse_verbose("core/one:[name=abc]root").unwrap(),
            parse_verbose("core/one:[name=xyz, name=abc]root").unwrap(),
        ];

        let mut actual = vec![
            parse_verbose("core/one:root").unwrap(),
            parse_verbose("core/one:[name=xyz]root").unwrap(),
        ];
        ensure_tree_field_is_set(&mut actual, name.clone()).unwrap();
        assert_eq!(actual, expected);
    }

    #[fuchsia::test]
    fn test_ensure_tree_field_is_set_noop_when_tree_names_set() {
        let expected = vec![
            parse_verbose("core/one:[...]root").unwrap(),
            parse_verbose("core/one:[name=xyz]root").unwrap(),
        ];
        let mut actual = vec![
            parse_verbose("core/one:root").unwrap(),
            parse_verbose("core/one:[name=xyz]root").unwrap(),
        ];
        ensure_tree_field_is_set(&mut actual, None).unwrap();
        assert_eq!(actual, expected);
    }

    #[fuchsia::test]
    fn test_ensure_tree_field_is_set_noop_on_empty_vec_no_name() {
        let mut actual = vec![];
        ensure_tree_field_is_set(&mut actual, None).unwrap();
        assert_eq!(actual, vec![]);
    }

    #[fuchsia::test]
    fn test_ensure_tree_field_is_set_all_components_when_empty_and_name() {
        let expected = vec![parse_verbose("**:[name=abc]*").unwrap()];
        let mut actual = vec![];
        let name = Some("abc".to_string());
        ensure_tree_field_is_set(&mut actual, name).unwrap();
        assert_eq!(actual, expected);
    }

    struct FakeProvider {
        realm_query: fsys2::RealmQueryProxy,
    }

    impl FakeProvider {
        async fn new(monikers: &'static [&'static str]) -> Self {
            let mut builder = MockRealmQueryBuilder::default();
            for name in monikers {
                builder = builder.when(name).moniker(name).add();
            }
            let realm_query_proxy = Rc::new(builder.build()).get_proxy().await;
            Self { realm_query: realm_query_proxy }
        }
    }

    impl DiagnosticsProvider for FakeProvider {
        async fn snapshot<D: diagnostics_data::DiagnosticsData>(
            &self,
            _: Option<&str>,
            _: impl IntoIterator<Item = Selector>,
        ) -> Result<Vec<diagnostics_data::Data<D>>, Error> {
            unreachable!("unimplemented");
        }

        async fn get_accessor_paths(&self) -> Result<Vec<String>, Error> {
            unreachable!("unimplemented");
        }

        fn realm_query(&self) -> &fsys2::RealmQueryProxy {
            &self.realm_query
        }
    }

    #[fuchsia::test]
    async fn test_process_fuzzy_inputs_success() {
        let actual = process_fuzzy_inputs(
            ["moniker1".to_string()],
            &FakeProvider::new(&["core/moniker1", "core/moniker2"]).await,
        )
        .await
        .unwrap();

        let expected = vec![parse_verbose("core/moniker1:root").unwrap()];

        assert_eq!(actual, expected);

        let actual = process_fuzzy_inputs(
            ["moniker1:collection".to_string()],
            &FakeProvider::new(&["core/moniker1:collection", "core/moniker1", "core/moniker2"])
                .await,
        )
        .await
        .unwrap();

        let expected = vec![parse_verbose(r"core/moniker1\:collection:root").unwrap()];

        assert_eq!(actual, expected);

        let actual = process_fuzzy_inputs(
            [r"core/moniker1\:collection".to_string()],
            &FakeProvider::new(&["core/moniker1:collection"]).await,
        )
        .await
        .unwrap();

        let expected = vec![parse_verbose(r"core/moniker1\:collection:root").unwrap()];

        assert_eq!(actual, expected);

        let actual = process_fuzzy_inputs(
            ["core/moniker1:root:prop".to_string()],
            &FakeProvider::new(&["core/moniker1:collection", "core/moniker1"]).await,
        )
        .await
        .unwrap();

        let expected = vec![parse_verbose(r"core/moniker1:root:prop").unwrap()];

        assert_eq!(actual, expected);

        let actual = process_fuzzy_inputs(
            ["core/moniker1".to_string(), "core/moniker2".to_string()],
            &FakeProvider::new(&["core/moniker1", "core/moniker2"]).await,
        )
        .await
        .unwrap();

        let expected = vec![
            parse_verbose(r"core/moniker1:root").unwrap(),
            parse_verbose(r"core/moniker2:root").unwrap(),
        ];

        assert_eq!(actual, expected);

        let actual = process_fuzzy_inputs(
            ["moniker1".to_string(), "moniker2".to_string()],
            &FakeProvider::new(&["core/moniker1"]).await,
        )
        .await
        .unwrap();

        let expected = vec![
            parse_verbose(r"core/moniker1:root").unwrap(),
            // fallback is to assume that moniker2 is a valid moniker
            parse_verbose("moniker2:root").unwrap(),
        ];

        assert_eq!(actual, expected);

        let actual = process_fuzzy_inputs(
            ["core/moniker1:root:prop".to_string(), "core/moniker2".to_string()],
            &FakeProvider::new(&["core/moniker1", "core/moniker2"]).await,
        )
        .await
        .unwrap();

        let expected = vec![
            parse_verbose(r"core/moniker1:root:prop").unwrap(),
            parse_verbose(r"core/moniker2:root").unwrap(),
        ];

        assert_eq!(actual, expected);
    }

    #[fuchsia::test]
    async fn test_process_fuzzy_inputs_failures() {
        let actual =
            process_fuzzy_inputs(["moniker ".to_string()], &FakeProvider::new(&["moniker"]).await)
                .await;

        assert_matches!(actual, Err(Error::ParseSelector(_, _)));

        let actual = process_fuzzy_inputs(
            ["moniker".to_string()],
            &FakeProvider::new(&["core/moniker1", "core/moniker2"]).await,
        )
        .await;

        assert_matches!(actual, Err(Error::FuzzyMatchTooManyMatches(_)));
    }

    #[fuchsia::test]
    async fn test_fuzzy_component_search() {
        let actual = process_component_query_with_partial_selectors(
            "moniker1".to_string(),
            [].into_iter(),
            &FakeProvider::new(&["core/moniker1", "core/moniker2"]).await,
        )
        .await
        .unwrap();

        let expected = vec![parse_verbose(r"core/moniker1:root").unwrap()];

        assert_eq!(actual, expected);

        let actual = process_component_query_with_partial_selectors(
            "moniker1".to_string(),
            ["root/foo:bar".to_string()].into_iter(),
            &FakeProvider::new(&["core/moniker1", "core/moniker2"]).await,
        )
        .await
        .unwrap();

        let expected = vec![parse_verbose(r"core/moniker1:root/foo:bar").unwrap()];

        assert_eq!(actual, expected);

        let actual = process_component_query_with_partial_selectors(
            "moniker1".to_string(),
            ["root/foo:bar".to_string()].into_iter(),
            &FakeProvider::new(&["core/moniker2", "core/moniker3"]).await,
        )
        .await;

        assert_matches!(actual, Err(Error::SearchParameterNotFound(_)));
    }
}