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::{Commands, Opt, configure_tracing_subscriber, iroh, rt, s2n};
7use iroh_metrics::{MetricValue, MetricsGroup};
8use n0_error::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        }
99    }
100
101    server_thread.join().expect("server thread");
102
103    Ok(())
104}
105
106#[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
107pub fn run_quinn(opt: Opt) -> Result<()> {
108    use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
109
110    let server_span = tracing::error_span!("server");
111    let runtime = rt();
112    let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
113    let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
114    let cert = CertificateDer::from(cert.cert);
115
116    let (server_addr, endpoint) = {
117        let _guard = server_span.enter();
118        quinn::server_endpoint(&runtime, cert.clone(), key.into(), &opt)
119    };
120
121    let server_thread = std::thread::spawn(move || {
122        let _guard = server_span.entered();
123        if let Err(e) = runtime.block_on(quinn::server(endpoint, opt)) {
124            eprintln!("server failed: {e:#}");
125        }
126    });
127
128    let mut handles = Vec::new();
129    for id in 0..opt.clients {
130        let cert = cert.clone();
131        handles.push(std::thread::spawn(move || {
132            let _guard = tracing::error_span!("client", id).entered();
133            let runtime = rt();
134            match runtime.block_on(quinn::client(server_addr, cert, opt)) {
135                Ok(stats) => Ok(stats),
136                Err(e) => {
137                    eprintln!("client failed: {e:#}");
138                    Err(e)
139                }
140            }
141        }));
142    }
143
144    for (id, handle) in handles.into_iter().enumerate() {
145        // We print all stats at the end of the test sequentially to avoid
146        // them being garbled due to being printed concurrently
147        if let Ok(stats) = handle.join().expect("client thread") {
148            stats.print(id);
149        }
150    }
151
152    server_thread.join().expect("server thread");
153
154    Ok(())
155}
156
157pub fn run_s2n(_opt: s2n::Opt) -> Result<()> {
158    unimplemented!()
159}
160
161fn collect_and_print(category: &'static str, metrics: &dyn MetricsGroup) {
162    let mut map = BTreeMap::new();
163    for item in metrics.iter() {
164        let value: i64 = match item.value() {
165            MetricValue::Counter(v) => v as i64,
166            MetricValue::Gauge(v) => v,
167            _ => continue,
168        };
169        map.insert(item.name().to_string(), value);
170    }
171    println!("{category}: {map:#?}");
172}