component_debug/
doctor.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
// 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 anyhow::{format_err, Result};
use fidl_fuchsia_sys2 as fsys;
use moniker::Moniker;
use prettytable::format::consts::FORMAT_CLEAN;
use prettytable::{cell, row, Row, Table};

const USE_TITLE: &'static str = "Used Capability";
const EXPOSE_TITLE: &'static str = "Exposed Capability";
const SUCCESS_SUMMARY: &'static str = "Success";
const CAPABILITY_COLUMN_WIDTH: usize = 50;
const SUMMARY_COLUMN_WIDTH: usize = 80;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// Analytical information about a capability.
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Debug)]
pub struct RouteReport {
    pub decl_type: DeclType,

    /// The name of the capability (for DeclType::Expose), or the path of
    /// the capability in the namespace (for DeclType::Use).
    pub capability: String,

    /// If Some, indicates a routing error for this route.
    pub error_summary: Option<String>,

    /// The requested level of availability of the capability.
    pub availability: Option<cm_rust::Availability>,
}

impl TryFrom<fsys::RouteReport> for RouteReport {
    type Error = anyhow::Error;

    fn try_from(report: fsys::RouteReport) -> Result<Self> {
        let decl_type =
            report.decl_type.ok_or_else(|| format_err!("missing decl type"))?.try_into()?;
        let capability = report.capability.ok_or_else(|| format_err!("missing capability name"))?;
        let availability: Option<cm_rust::Availability> =
            report.availability.map(cm_rust::Availability::from);
        let error_summary = if let Some(error) = report.error { error.summary } else { None };
        Ok(RouteReport { decl_type, capability, error_summary, availability })
    }
}

#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Debug, PartialEq)]
pub enum DeclType {
    Use,
    Expose,
}

impl TryFrom<fsys::DeclType> for DeclType {
    type Error = anyhow::Error;

    fn try_from(value: fsys::DeclType) -> std::result::Result<Self, Self::Error> {
        match value {
            fsys::DeclType::Use => Ok(DeclType::Use),
            fsys::DeclType::Expose => Ok(DeclType::Expose),
            _ => Err(format_err!("unknown decl type")),
        }
    }
}

/// Returns a list of individual RouteReports for use and expose declarations
/// for the component. Any individual report with `error_summary` set to Some()
/// indicates a routing error.
pub async fn validate_routes(
    route_validator: &fsys::RouteValidatorProxy,
    moniker: &Moniker,
) -> Result<Vec<RouteReport>> {
    let reports = match route_validator.validate(&moniker.to_string()).await? {
        Ok(reports) => reports,
        Err(e) => {
            return Err(format_err!(
                "Component manager returned an unexpected error during validation: {:?}\n\
                 The state of the component instance may have changed.\n\
                 Please report this to the Component Framework team.",
                e
            ));
        }
    };

    reports.into_iter().map(|r| r.try_into()).collect()
}

fn format(report: &RouteReport) -> Row {
    let capability = match report.availability {
        Some(cm_rust::Availability::Required) | None => report.capability.clone(),
        Some(availability) => format!("{} ({})", report.capability, availability),
    };
    let capability = textwrap::fill(&capability, CAPABILITY_COLUMN_WIDTH);
    let (mark, summary) = if let Some(summary) = &report.error_summary {
        let mark = ansi_term::Color::Red.paint("[✗]");
        let summary = textwrap::fill(summary, SUMMARY_COLUMN_WIDTH);
        (mark, summary)
    } else {
        let mark = ansi_term::Color::Green.paint("[✓]");
        let summary = textwrap::fill(SUCCESS_SUMMARY, SUMMARY_COLUMN_WIDTH);
        (mark, summary)
    };
    row!(mark, capability, summary)
}

// Construct the used and exposed capability tables from the given route reports.
pub fn create_tables(reports: &Vec<RouteReport>) -> (Table, Table) {
    let mut use_table = new_table(USE_TITLE);
    let mut expose_table = new_table(EXPOSE_TITLE);

    for report in reports {
        match &report.decl_type {
            DeclType::Use => use_table.add_row(format(&report)),
            DeclType::Expose => expose_table.add_row(format(&report)),
        };
    }
    (use_table, expose_table)
}

// Create a new table with the given title.
fn new_table(title: &str) -> Table {
    let mut table = Table::new();
    table.set_format(*FORMAT_CLEAN);
    table.set_titles(row!("", title.to_string(), "Result"));
    table
}

#[cfg(test)]
mod test {
    use super::*;
    use fidl::endpoints::create_proxy_and_stream;
    use futures::TryStreamExt;

    fn route_validator(
        expected_moniker: &'static str,
        reports: Vec<fsys::RouteReport>,
    ) -> fsys::RouteValidatorProxy {
        let (route_validator, mut stream) = create_proxy_and_stream::<fsys::RouteValidatorMarker>();
        fuchsia_async::Task::local(async move {
            match stream.try_next().await.unwrap().unwrap() {
                fsys::RouteValidatorRequest::Validate { moniker, responder, .. } => {
                    assert_eq!(Moniker::parse_str(expected_moniker), Moniker::parse_str(&moniker));
                    responder.send(Ok(&reports)).unwrap();
                }
                fsys::RouteValidatorRequest::Route { .. } => {
                    panic!("unexpected Route request");
                }
            }
        })
        .detach();
        route_validator
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_errors() {
        let validator = route_validator(
            "/test",
            vec![fsys::RouteReport {
                capability: Some("fuchsia.foo.bar".to_string()),
                decl_type: Some(fsys::DeclType::Use),
                error: Some(fsys::RouteError {
                    summary: Some("Access denied".to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }],
        );

        let mut reports =
            validate_routes(&validator, &Moniker::parse_str("test").unwrap()).await.unwrap();
        assert_eq!(reports.len(), 1);

        let report = reports.remove(0);
        assert_eq!(report.capability, "fuchsia.foo.bar");
        assert_eq!(report.decl_type, DeclType::Use);

        let error = report.error_summary.unwrap();
        assert_eq!(error, "Access denied");
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_no_errors() {
        let validator = route_validator(
            "/test",
            vec![fsys::RouteReport {
                capability: Some("fuchsia.foo.bar".to_string()),
                decl_type: Some(fsys::DeclType::Use),
                error: None,
                ..Default::default()
            }],
        );

        let mut reports =
            validate_routes(&validator, &Moniker::parse_str("test").unwrap()).await.unwrap();
        assert_eq!(reports.len(), 1);

        let report = reports.remove(0);
        assert_eq!(report.capability, "fuchsia.foo.bar");
        assert_eq!(report.decl_type, DeclType::Use);
        assert!(report.error_summary.is_none());
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_no_routes() {
        let validator = route_validator("test", vec![]);

        let reports =
            validate_routes(&validator, &Moniker::parse_str("test").unwrap()).await.unwrap();
        assert!(reports.is_empty());
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_parse_error() {
        let validator = route_validator(
            "/test",
            vec![
                // Don't set any fields
                fsys::RouteReport::default(),
            ],
        );

        let result = validate_routes(&validator, &Moniker::parse_str("test").unwrap()).await;
        assert!(result.is_err());
    }
}