component_debug/cli/
graph.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
// 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::realm::{get_all_instances, Instance};
use anyhow::Result;
use fidl_fuchsia_sys2 as fsys;
use std::collections::HashSet;
use std::fmt::Write;
use std::str::FromStr;
use url::Url;

/// The starting part of our Graphviz graph output. This should be printed before any contents.
static GRAPHVIZ_START: &str = r##"digraph {
    graph [ pad = 0.2 ]
    node [ shape = "box" color = "#2a5b4f" penwidth = 2.25 fontname = "prompt medium" fontsize = 10 target = "_parent" margin = 0.22, ordering = out ];
    edge [ color = "#37474f" penwidth = 1 arrowhead = none target = "_parent" fontname = "roboto mono" fontsize = 10 ]
    splines = "ortho"
"##;

/// The ending part of our Graphviz graph output. This should be printed after `GRAPHVIZ_START` and the
/// contents of the graph.
static GRAPHVIZ_END: &str = "}";

/// Filters that can be applied when creating component graphs
#[derive(Debug, PartialEq)]
pub enum GraphFilter {
    /// Filters components that are an ancestor of the component with the given name.
    /// Includes the named component.
    Ancestor(String),
    /// Filters components that are a descendant of the component with the given name.
    /// Includes the named component.
    Descendant(String),
    /// Filters components that are a relative (either an ancestor or a descendant) of the
    /// component with the given name. Includes the named component.
    Relative(String),
}

impl FromStr for GraphFilter {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.split_once(":") {
            Some((function, arg)) => match function {
                "ancestor" | "ancestors" => Ok(Self::Ancestor(arg.to_string())),
                "descendant" | "descendants" => Ok(Self::Descendant(arg.to_string())),
                "relative" | "relatives" => Ok(Self::Relative(arg.to_string())),
                _ => Err("unknown function for list filter."),
            },
            None => Err("list filter should be 'ancestors:<component_name>', 'descendants:<component_name>', or 'relatives:<component_name>'."),
        }
    }
}

/// Determines the visual orientation of the graph's nodes.
#[derive(Debug, PartialEq)]
pub enum GraphOrientation {
    /// The graph's nodes should be ordered from top to bottom.
    TopToBottom,
    /// The graph's nodes should be ordered from left to right.
    LeftToRight,
}

impl FromStr for GraphOrientation {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().replace("_", "").replace("-", "").as_str() {
            "tb" | "toptobottom" => Ok(GraphOrientation::TopToBottom),
            "lr" | "lefttoright" => Ok(GraphOrientation::LeftToRight),
            _ => Err("graph orientation should be 'toptobottom' or 'lefttoright'."),
        }
    }
}

pub async fn graph_cmd<W: std::io::Write>(
    filter: Option<GraphFilter>,
    orientation: GraphOrientation,
    realm_query: fsys::RealmQueryProxy,
    mut writer: W,
) -> Result<()> {
    let mut instances = get_all_instances(&realm_query).await?;

    instances = match filter {
        Some(GraphFilter::Ancestor(m)) => filter_ancestors(instances, m),
        Some(GraphFilter::Descendant(m)) => filter_descendants(instances, m),
        Some(GraphFilter::Relative(m)) => filter_relatives(instances, m),
        _ => instances,
    };

    let output = create_dot_graph(instances, orientation);
    writeln!(writer, "{}", output)?;

    Ok(())
}

fn filter_ancestors(instances: Vec<Instance>, child_str: String) -> Vec<Instance> {
    let mut ancestors = HashSet::new();

    // Find monikers with this child as the leaf.
    for instance in &instances {
        if let Some(child) = instance.moniker.leaf() {
            if child.to_string() == child_str {
                // Add this moniker to ancestor list.
                let mut cur_moniker = instance.moniker.clone();
                ancestors.insert(cur_moniker.clone());

                // Loop over parents of this moniker and add them to ancestor list.
                while let Some(parent) = cur_moniker.parent() {
                    ancestors.insert(parent.clone());
                    cur_moniker = parent;
                }
            }
        }
    }

    instances.into_iter().filter(|i| ancestors.contains(&i.moniker)).collect()
}

fn filter_descendants(instances: Vec<Instance>, child_str: String) -> Vec<Instance> {
    let mut descendants = HashSet::new();

    // Find monikers with this child as the leaf.
    for instance in &instances {
        if let Some(child) = instance.moniker.leaf() {
            if child.to_string() == child_str {
                // Get all descendants of this moniker.
                for possible_child_instance in &instances {
                    if possible_child_instance.moniker.has_prefix(&instance.moniker) {
                        descendants.insert(possible_child_instance.moniker.clone());
                    }
                }
            }
        }
    }

    instances.into_iter().filter(|i| descendants.contains(&i.moniker)).collect()
}

fn filter_relatives(instances: Vec<Instance>, child_str: String) -> Vec<Instance> {
    let mut relatives = HashSet::new();

    // Find monikers with this child as the leaf.
    for instance in &instances {
        if let Some(child) = instance.moniker.leaf() {
            if child.to_string() == child_str {
                // Loop over parents of this moniker and add them to relatives list.
                let mut cur_moniker = instance.moniker.clone();
                while let Some(parent) = cur_moniker.parent() {
                    relatives.insert(parent.clone());
                    cur_moniker = parent;
                }

                // Get all descendants of this moniker and add them to relatives list.
                for possible_child_instance in &instances {
                    if possible_child_instance.moniker.has_prefix(&instance.moniker) {
                        relatives.insert(possible_child_instance.moniker.clone());
                    }
                }
            }
        }
    }

    instances.into_iter().filter(|i| relatives.contains(&i.moniker)).collect()
}

fn construct_codesearch_url(component_url: &str) -> String {
    // Extract the last part of the component URL
    let mut name_with_filetype = match component_url.rsplit_once("/") {
        Some(parts) => parts.1.to_string(),
        // No parts of the path contain `/`, this is already the last part of the component URL.
        // Out-of-tree components may be standalone.
        None => component_url.to_string(),
    };
    if name_with_filetype.ends_with(".cm") {
        name_with_filetype.push('l');
    }

    // We mix dashes and underscores between the manifest name and the instance name
    // sometimes, so search using both.
    let name_with_underscores = name_with_filetype.replace("-", "_");
    let name_with_dashes = name_with_filetype.replace("_", "-");

    let query = if name_with_underscores == name_with_dashes {
        format!("f:{}", &name_with_underscores)
    } else {
        format!("f:{}|{}", &name_with_underscores, &name_with_dashes)
    };

    let mut code_search_url = Url::parse("https://cs.opensource.google/search").unwrap();
    code_search_url.query_pairs_mut().append_pair("q", &query).append_pair("ss", "fuchsia/fuchsia");

    code_search_url.into()
}

/// Create a graphviz dot graph from component instance information.
pub fn create_dot_graph(instances: Vec<Instance>, orientation: GraphOrientation) -> String {
    let mut output = GRAPHVIZ_START.to_string();

    // Switch the orientation of the graph.
    match orientation {
        GraphOrientation::TopToBottom => writeln!(output, r#"    rankdir = "TB""#).unwrap(),
        GraphOrientation::LeftToRight => writeln!(output, r#"    rankdir = "LR""#).unwrap(),
    };

    for instance in &instances {
        let moniker = instance.moniker.to_string();
        let label = if let Some(leaf) = instance.moniker.leaf() {
            leaf.to_string()
        } else {
            ".".to_string()
        };

        // Running components are filled.
        let running_attrs =
            if instance.resolved_info.as_ref().map_or(false, |r| r.execution_info.is_some()) {
                r##"style = "filled" fontcolor = "#ffffff""##
            } else {
                ""
            };

        // Components can be clicked to search for them on Code Search.
        let url_attrs = if !instance.url.is_empty() {
            let code_search_url = construct_codesearch_url(&instance.url);
            format!(r#"href = "{}""#, code_search_url.as_str())
        } else {
            String::new()
        };

        // Draw the component.
        writeln!(
            output,
            r#"    "{}" [ label = "{}" {} {} ]"#,
            &moniker, &label, &running_attrs, &url_attrs
        )
        .unwrap();

        // Component has a parent and the parent is also in the list of components
        if let Some(parent_moniker) = instance.moniker.parent() {
            if let Some(parent) = instances.iter().find(|i| i.moniker == parent_moniker) {
                // Connect parent to component
                writeln!(output, r#"    "{}" -> "{}""#, &parent.moniker.to_string(), &moniker)
                    .unwrap();
            }
        }
    }

    writeln!(output, "{}", GRAPHVIZ_END).unwrap();
    output
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::realm::{ExecutionInfo, ResolvedInfo};
    use moniker::Moniker;

    fn instances_for_test() -> Vec<Instance> {
        vec![
            Instance {
                moniker: Moniker::root(),
                url: "fuchsia-boot:///#meta/root.cm".to_owned(),
                environment: None,
                instance_id: None,
                resolved_info: Some(ResolvedInfo {
                    resolved_url: "fuchsia-boot:///#meta/root.cm".to_owned(),
                    execution_info: None,
                }),
            },
            Instance {
                moniker: Moniker::parse_str("appmgr").unwrap(),
                url: "fuchsia-pkg://fuchsia.com/appmgr#meta/appmgr.cm".to_owned(),
                environment: None,
                instance_id: None,
                resolved_info: Some(ResolvedInfo {
                    resolved_url: "fuchsia-pkg://fuchsia.com/appmgr#meta/appmgr.cm".to_owned(),
                    execution_info: Some(ExecutionInfo {
                        start_reason: "Debugging Workflow".to_owned(),
                    }),
                }),
            },
            Instance {
                moniker: Moniker::parse_str("sys").unwrap(),
                url: "fuchsia-pkg://fuchsia.com/sys#meta/sys.cm".to_owned(),
                environment: None,
                instance_id: None,
                resolved_info: Some(ResolvedInfo {
                    resolved_url: "fuchsia-pkg://fuchsia.com/sys#meta/sys.cm".to_owned(),
                    execution_info: None,
                }),
            },
            Instance {
                moniker: Moniker::parse_str("sys/baz").unwrap(),
                url: "fuchsia-pkg://fuchsia.com/baz#meta/baz.cm".to_owned(),
                environment: None,
                instance_id: None,
                resolved_info: Some(ResolvedInfo {
                    resolved_url: "fuchsia-pkg://fuchsia.com/baz#meta/baz.cm".to_owned(),
                    execution_info: Some(ExecutionInfo {
                        start_reason: "Debugging Workflow".to_owned(),
                    }),
                }),
            },
            Instance {
                moniker: Moniker::parse_str("sys/fuzz").unwrap(),
                url: "fuchsia-pkg://fuchsia.com/fuzz#meta/fuzz.cm".to_owned(),
                environment: None,
                instance_id: None,
                resolved_info: Some(ResolvedInfo {
                    resolved_url: "fuchsia-pkg://fuchsia.com/fuzz#meta/fuzz.cm".to_owned(),
                    execution_info: None,
                }),
            },
            Instance {
                moniker: Moniker::parse_str("sys/fuzz/hello").unwrap(),
                url: "fuchsia-pkg://fuchsia.com/hello#meta/hello.cm".to_owned(),
                environment: None,
                instance_id: None,
                resolved_info: Some(ResolvedInfo {
                    resolved_url: "fuchsia-pkg://fuchsia.com/hello#meta/hello.cm".to_owned(),
                    execution_info: None,
                }),
            },
        ]
    }

    // The tests in this file are change-detectors because they will fail on
    // any style changes to the graph. This isn't great, but it makes it easy
    // to view the changes in a Graphviz visualizer.
    async fn test_graph_orientation(orientation: GraphOrientation, expected_rankdir: &str) {
        let instances = instances_for_test();

        let graph = create_dot_graph(instances, orientation);
        pretty_assertions::assert_eq!(
            graph,
            format!(
                r##"digraph {{
    graph [ pad = 0.2 ]
    node [ shape = "box" color = "#2a5b4f" penwidth = 2.25 fontname = "prompt medium" fontsize = 10 target = "_parent" margin = 0.22, ordering = out ];
    edge [ color = "#37474f" penwidth = 1 arrowhead = none target = "_parent" fontname = "roboto mono" fontsize = 10 ]
    splines = "ortho"
    rankdir = "{}"
    "." [ label = "."  href = "https://cs.opensource.google/search?q=f%3Aroot.cml&ss=fuchsia%2Ffuchsia" ]
    "appmgr" [ label = "appmgr" style = "filled" fontcolor = "#ffffff" href = "https://cs.opensource.google/search?q=f%3Aappmgr.cml&ss=fuchsia%2Ffuchsia" ]
    "." -> "appmgr"
    "sys" [ label = "sys"  href = "https://cs.opensource.google/search?q=f%3Asys.cml&ss=fuchsia%2Ffuchsia" ]
    "." -> "sys"
    "sys/baz" [ label = "baz" style = "filled" fontcolor = "#ffffff" href = "https://cs.opensource.google/search?q=f%3Abaz.cml&ss=fuchsia%2Ffuchsia" ]
    "sys" -> "sys/baz"
    "sys/fuzz" [ label = "fuzz"  href = "https://cs.opensource.google/search?q=f%3Afuzz.cml&ss=fuchsia%2Ffuchsia" ]
    "sys" -> "sys/fuzz"
    "sys/fuzz/hello" [ label = "hello"  href = "https://cs.opensource.google/search?q=f%3Ahello.cml&ss=fuchsia%2Ffuchsia" ]
    "sys/fuzz" -> "sys/fuzz/hello"
}}
"##,
                expected_rankdir
            )
        );
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_graph_top_to_bottom_orientation() {
        test_graph_orientation(GraphOrientation::TopToBottom, "TB").await;
    }

    #[fuchsia_async::run_singlethreaded(test)]
    async fn test_graph_left_to_right_orientation() {
        test_graph_orientation(GraphOrientation::LeftToRight, "LR").await;
    }
}