bulk/
bulk.rs

1use std::collections::BTreeMap;
2
3use clap::Parser;
4#[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
5use iroh_bench::quinn;
6use iroh_bench::{configure_tracing_subscriber, iroh, rt, s2n, Commands, Opt};
7use iroh_metrics::{MetricValue, MetricsGroup};
8use n0_snafu::Result;
9
10fn main() {
11    let cmd = Commands::parse();
12    configure_tracing_subscriber();
13
14    match cmd {
15        Commands::Iroh(opt) => {
16            if let Err(e) = run_iroh(opt) {
17                eprintln!("failed: {e:#}");
18            }
19        }
20        #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
21        Commands::Quinn(opt) => {
22            if let Err(e) = run_quinn(opt) {
23                eprintln!("failed: {e:#}");
24            }
25        }
26        Commands::S2n(opt) => {
27            if let Err(e) = run_s2n(opt) {
28                eprintln!("failed: {e:#}");
29            }
30        }
31    }
32}
33
34pub fn run_iroh(opt: Opt) -> Result<()> {
35    let server_span = tracing::error_span!("server");
36    let runtime = rt();
37
38    #[cfg(feature = "local-relay")]
39    let (relay_url, relay_server) = if opt.only_relay {
40        let (_, relay_url, relay_server) =
41            runtime.block_on(::iroh::test_utils::run_relay_server())?;
42
43        (Some(relay_url), Some(relay_server))
44    } else {
45        (None, None)
46    };
47    #[cfg(not(feature = "local-relay"))]
48    let relay_url = None;
49
50    let (server_addr, endpoint) = {
51        let _guard = server_span.enter();
52        iroh::server_endpoint(&runtime, &relay_url, &opt)
53    };
54
55    let endpoint_metrics = endpoint.metrics().clone();
56
57    let server_thread = std::thread::spawn(move || {
58        let _guard = server_span.entered();
59        if let Err(e) = runtime.block_on(iroh::server(endpoint, opt)) {
60            eprintln!("server failed: {e:#}");
61        }
62    });
63
64    let mut handles = Vec::new();
65    for id in 0..opt.clients {
66        let server_addr = server_addr.clone();
67        let relay_url = relay_url.clone();
68        handles.push(std::thread::spawn(move || {
69            let _guard = tracing::error_span!("client", id).entered();
70            let runtime = rt();
71            match runtime.block_on(iroh::client(server_addr, relay_url.clone(), opt)) {
72                Ok(stats) => Ok(stats),
73                Err(e) => {
74                    eprintln!("client failed: {e:#}");
75                    Err(e)
76                }
77            }
78        }));
79    }
80
81    for (id, handle) in handles.into_iter().enumerate() {
82        // We print all stats at the end of the test sequentially to avoid
83        // them being garbled due to being printed concurrently
84        if let Ok(stats) = handle.join().expect("client thread") {
85            stats.print(id);
86        }
87    }
88
89    if opt.metrics {
90        // print metrics
91        println!("\nMetrics:");
92        collect_and_print("MagicsockMetrics", &*endpoint_metrics.magicsock);
93        collect_and_print("NetReportMetrics", &*endpoint_metrics.net_report);
94        collect_and_print("PortmapMetrics", &*endpoint_metrics.portmapper);
95        #[cfg(feature = "local-relay")]
96        if let Some(relay_server) = relay_server.as_ref() {
97            collect_and_print("RelayServerMetrics", &*relay_server.metrics().server);
98            collect_and_print("RelayStunMetrics", &*relay_server.metrics().stun);
99        }
100    }
101
102    server_thread.join().expect("server thread");
103
104    Ok(())
105}
106
107#[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
108pub fn run_quinn(opt: Opt) -> Result<()> {
109    use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
110
111    let server_span = tracing::error_span!("server");
112    let runtime = rt();
113    let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
114    let key = PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der());
115    let cert = CertificateDer::from(cert.cert);
116
117    let (server_addr, endpoint) = {
118        let _guard = server_span.enter();
119        quinn::server_endpoint(&runtime, cert.clone(), key.into(), &opt)
120    };
121
122    let server_thread = std::thread::spawn(move || {
123        let _guard = server_span.entered();
124        if let Err(e) = runtime.block_on(quinn::server(endpoint, opt)) {
125            eprintln!("server failed: {e:#}");
126        }
127    });
128
129    let mut handles = Vec::new();
130    for id in 0..opt.clients {
131        let cert = cert.clone();
132        handles.push(std::thread::spawn(move || {
133            let _guard = tracing::error_span!("client", id).entered();
134            let runtime = rt();
135            match runtime.block_on(quinn::client(server_addr, cert, opt)) {
136                Ok(stats) => Ok(stats),
137                Err(e) => {
138                    eprintln!("client failed: {e:#}");
139                    Err(e)
140                }
141            }
142        }));
143    }
144
145    for (id, handle) in handles.into_iter().enumerate() {
146        // We print all stats at the end of the test sequentially to avoid
147        // them being garbled due to being printed concurrently
148        if let Ok(stats) = handle.join().expect("client thread") {
149            stats.print(id);
150        }
151    }
152
153    server_thread.join().expect("server thread");
154
155    Ok(())
156}
157
158pub fn run_s2n(_opt: s2n::Opt) -> Result<()> {
159    unimplemented!()
160}
161
162fn collect_and_print(category: &'static str, metrics: &dyn MetricsGroup) {
163    let mut map = BTreeMap::new();
164    for item in metrics.iter() {
165        let value: i64 = match item.value() {
166            MetricValue::Counter(v) => v as i64,
167            MetricValue::Gauge(v) => v,
168            _ => continue,
169        };
170        map.insert(item.name().to_string(), value);
171    }
172    println!("{category}: {map:#?}");
173}