bulk/
bulk.rs

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