-
Notifications
You must be signed in to change notification settings - Fork 99
/
tquic_client.rs
1579 lines (1374 loc) · 49.3 KB
/
tquic_client.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 The TQUIC Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::cell::RefCell;
use std::cell::RefMut;
use std::cmp::max;
use std::fs::create_dir_all;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::path::Path;
use std::rc::Rc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::Instant;
use bytes::Bytes;
use clap::error::ErrorKind;
use clap::CommandFactory;
use clap::Parser;
use log::debug;
use log::error;
use log::info;
use log::warn;
use mio::event::Event;
use rand::Rng;
use rustc_hash::FxHashMap;
use statrs::statistics::Data;
use statrs::statistics::Distribution;
use statrs::statistics::Max;
use statrs::statistics::Min;
use statrs::statistics::OrderStatistics;
use tquic::h3::NameValue;
use url::Url;
use tquic::connection::ConnectionStats;
use tquic::error::Error;
use tquic::h3::connection::Http3Connection;
use tquic::h3::Header;
use tquic::h3::Http3Config;
use tquic::Config;
use tquic::CongestionControlAlgorithm;
use tquic::Connection;
use tquic::Endpoint;
use tquic::MultipathAlgorithm;
use tquic::PacketInfo;
use tquic::TlsConfig;
use tquic::TransportHandler;
use tquic_tools::ApplicationProto;
use tquic_tools::QuicSocket;
use tquic_tools::Result;
#[cfg(unix)]
#[global_allocator]
static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc;
#[derive(Parser, Debug, Clone)]
#[clap(name = "client", version=env!("CARGO_PKG_VERSION"))]
pub struct ClientOpt {
/// Server's address.
#[clap(short, long, value_name = "ADDR")]
pub connect_to: Option<SocketAddr>,
/// Optional local IP addresses for client. e.g 192.168.1.10,192.168.2.20
#[clap(long, value_delimiter = ',', value_name = "ADDR")]
pub local_addresses: Vec<IpAddr>,
/// Request URLs. The host of the first url is used as TLS SNI.
#[clap(value_delimiter = ' ')]
pub urls: Vec<Url>,
/// Number of threads.
#[clap(
short,
long,
default_value = "1",
value_name = "NUM",
help_heading = "Concurrency"
)]
pub threads: u32,
/// Number of concurrent connections per thread.
#[clap(
long,
default_value = "1",
value_name = "NUM",
help_heading = "Concurrency"
)]
pub max_concurrent_conns: u32,
/// Number of concurrent requests per connection.
#[clap(
long,
default_value = "1",
value_name = "NUM",
help_heading = "Concurrency"
)]
pub max_concurrent_requests: u64,
/// Number of max requests per connection before re-establishment. "0" means infinity mode.
#[clap(
long,
default_value = "1",
value_name = "NUM",
help_heading = "Concurrency"
)]
pub max_requests_per_conn: u64,
/// Total number of requests to send per thread. "0" means infinity mode.
/// Values below number of urls will be considered as number of urls.
#[clap(
long,
default_value = "1",
value_name = "NUM",
help_heading = "Concurrency"
)]
pub total_requests_per_thread: u64,
/// Benchmarking duration in seconds. "0" means infinity mode.
/// Client will exit upon reaching the total_requests_per_thread or duration limit.
#[clap(
short,
long,
default_value = "0",
value_name = "TIME",
help_heading = "Concurrency"
)]
pub duration: u64,
/// ALPN, separated by ",".
#[clap(
short,
long,
value_delimiter = ',',
default_value = "h3,http/0.9,hq-interop",
value_name = "STR",
help_heading = "Protocol"
)]
pub alpn: Vec<ApplicationProto>,
/// File used for session resumption.
#[clap(short, long, value_name = "FILE", help_heading = "Protocol")]
pub session_file: Option<String>,
/// Enable early data.
#[clap(short, long, help_heading = "Protocol")]
pub enable_early_data: bool,
/// Disable stateless reset.
#[clap(long, help_heading = "Protocol")]
pub disable_stateless_reset: bool,
/// Congestion control algorithm.
#[clap(long, default_value = "BBR", help_heading = "Protocol")]
pub congestion_control_algor: CongestionControlAlgorithm,
/// Initial congestion window in packets.
#[clap(
long,
default_value = "32",
value_name = "NUM",
help_heading = "Protocol"
)]
pub initial_congestion_window: u64,
/// Minimum congestion window in packets.
#[clap(
long,
default_value = "4",
value_name = "NUM",
help_heading = "Protocol"
)]
pub min_congestion_window: u64,
/// Enable multipath transport.
#[clap(long, help_heading = "Protocol")]
pub enable_multipath: bool,
/// Multipath scheduling algorithm.
#[clap(long, default_value = "MINRTT", help_heading = "Protocol")]
pub multipath_algor: MultipathAlgorithm,
/// Set active_connection_id_limit transport parameter. Values lower than 2 will be ignored.
#[clap(
long,
default_value = "2",
value_name = "NUM",
help_heading = "Protocol"
)]
pub active_cid_limit: u64,
/// Set max_udp_payload_size transport parameter.
#[clap(
long,
default_value = "65527",
value_name = "NUM",
help_heading = "Protocol"
)]
pub recv_udp_payload_size: u16,
/// Set the maximum outgoing UDP payload size.
#[clap(
long,
default_value = "1200",
value_name = "NUM",
help_heading = "Protocol"
)]
pub send_udp_payload_size: usize,
/// Handshake timeout in microseconds.
#[clap(
long,
default_value = "10000",
value_name = "TIME",
help_heading = "Protocol"
)]
pub handshake_timeout: u64,
/// Connection idle timeout in microseconds.
#[clap(
long,
default_value = "30000",
value_name = "TIME",
help_heading = "Protocol"
)]
pub idle_timeout: u64,
/// Initial RTT in milliseconds.
#[clap(
long,
default_value = "333",
value_name = "TIME",
help_heading = "Protocol"
)]
pub initial_rtt: u64,
/// Linear factor for calculating the probe timeout.
#[clap(
long,
default_value = "10",
value_name = "NUM",
help_heading = "Protocol"
)]
pub pto_linear_factor: u64,
/// Upper limit of probe timeout in microseconds.
#[clap(
long,
default_value = "10000",
value_name = "TIME",
help_heading = "Protocol"
)]
pub max_pto: u64,
/// Length of connection id in bytes.
#[clap(
long,
default_value = "8",
value_name = "NUM",
help_heading = "Protocol"
)]
pub cid_len: usize,
/// Print response header and body to stdout.
#[clap(short, long, help_heading = "Output")]
pub print_res: bool,
/// Dump response body into the given directory.
/// If the specified directory does not exist, a new directory will be created.
#[clap(long, value_name = "DIR", help_heading = "Output")]
pub dump_dir: Option<String>,
/// Log level, support OFF/ERROR/WARN/INFO/DEBUG/TRACE.
#[clap(
long,
default_value = "INFO",
value_name = "STR",
help_heading = "Output"
)]
pub log_level: log::LevelFilter,
/// Log file path. If no file is specified, logs will be written to `stderr`.
#[clap(long, value_name = "FILE", help_heading = "Output")]
pub log_file: Option<String>,
/// Save TLS key log into the given file.
#[clap(short, long, value_name = "FILE", help_heading = "Output")]
pub keylog_file: Option<String>,
/// Save qlog file (<trace_id>.qlog) into the given directory.
#[clap(long, value_name = "DIR", help_heading = "Output")]
pub qlog_dir: Option<String>,
/// Client will exit if consecutive failure reaches the threshold at the beginning.
#[clap(long, default_value = "10", value_name = "NUM", help_heading = "Misc")]
pub connection_failure_threshold: u64,
/// Batch size for sending packets.
#[clap(long, default_value = "1", value_name = "NUM", help_heading = "Misc")]
pub send_batch_size: usize,
/// Disable encryption on 1-RTT packets.
#[clap(long, help_heading = "Misc")]
pub disable_encryption: bool,
/// Number of max samples per thread used for request time statistics.
#[clap(
long,
default_value = "100000",
value_name = "NUM",
help_heading = "Misc"
)]
pub max_sample: usize,
}
const MAX_BUF_SIZE: usize = 65536;
/// Multi-threads QUIC client.
struct Client {
/// Client option.
option: ClientOpt,
/// Context shared between threads.
context: Arc<Mutex<ClientContext>>,
/// Client start time.
start_time: Instant,
/// If terminated by system signal.
terminated: Arc<AtomicBool>,
}
impl Client {
/// Create a new multi-threads client.
pub fn new(option: ClientOpt) -> Result<Self> {
let client_ctx = Arc::new(Mutex::new(ClientContext::default()));
let terminated = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::SIGINT, Arc::clone(&terminated))?;
Ok(Self {
option,
context: client_ctx,
start_time: Instant::now(),
terminated,
})
}
/// Start the client.
pub fn start(&mut self) {
self.start_time = Instant::now();
let mut threads = vec![];
for _ in 0..self.option.threads {
let client_opt = self.option.clone();
let client_ctx = self.context.clone();
let terminated = self.terminated.clone();
let thread = thread::spawn(move || {
let mut worker = Worker::new(client_opt, client_ctx, terminated).unwrap();
worker.start().unwrap();
});
threads.push(thread);
}
for thread in threads {
thread.join().unwrap();
}
self.finish();
}
fn finish(&self) {
// Print stats.
self.stats();
// Write session resumption file.
let context = self.context.lock().unwrap();
if let Some(session) = &context.session {
if let Some(session_file) = &self.option.session_file {
std::fs::write(session_file, session).ok();
}
}
}
fn stats(&self) {
let context = self.context.lock().unwrap();
let d = context.end_time.unwrap() - self.start_time;
// TODO: support more statistical items.
println!();
println!(
"finished in {:?}, {:.2} req/s",
d,
context.request_success as f64 / d.as_millis() as f64 * 1000.0
);
println!(
"conns: total {}, finish {}, success {}, failure {}",
context.conn_total,
context.conn_finish,
context.conn_finish_success,
context.conn_finish_failed,
);
println!(
"requests: sent {}, finish {}, success {}",
context.request_sent, context.request_done, context.request_success,
);
let mut s = Data::new(context.request_time_samples.clone());
println!("time for request(µs):");
println!(
"\tmin: {:.2}, max: {:.2}, mean: {:.2}, sd: {:.2}",
s.min(),
s.max(),
s.mean().unwrap(),
s.std_dev().unwrap(),
);
println!(
"\tmedian: {:.2}, p80: {:.2}, p90: {:.2}, p99: {:.2}",
s.median(),
s.percentile(80),
s.percentile(90),
s.percentile(99),
);
println!(
"recv pkts: {}, sent pkts: {}, lost pkts: {}",
context.conn_stats.recv_count,
context.conn_stats.sent_count,
context.conn_stats.lost_count
);
println!(
"recv bytes: {}, sent bytes: {}, lost bytes: {}",
context.conn_stats.recv_bytes,
context.conn_stats.sent_bytes,
context.conn_stats.lost_bytes
);
println!();
}
}
/// Context used for single thread client.
#[derive(Default)]
struct ClientContext {
session: Option<Vec<u8>>,
request_sent: u64,
request_done: u64,
request_success: u64,
request_time_samples: Vec<f64>,
conn_total: u64,
conn_handshake_success: u64,
conn_finish: u64,
conn_finish_success: u64,
conn_finish_failed: u64,
end_time: Option<Instant>,
conn_stats: ConnectionStats,
}
fn update_conn_stats(total: &mut ConnectionStats, one: &ConnectionStats) {
total.recv_count += one.recv_count;
total.sent_count += one.sent_count;
total.lost_count += one.lost_count;
total.recv_bytes += one.recv_bytes;
total.sent_bytes += one.sent_bytes;
total.lost_bytes += one.lost_bytes;
}
/// Client worker with single thread.
struct Worker {
/// Client option.
option: ClientOpt,
/// QUIC endpoint.
endpoint: Endpoint,
/// Event poll.
poll: mio::Poll,
/// Remote socket address.
remote: SocketAddr,
/// Socket connecting to server.
sock: Rc<QuicSocket>,
/// Worker context.
worker_ctx: Rc<RefCell<WorkerContext>>,
/// Context shared between workers.
client_ctx: Arc<Mutex<ClientContext>>,
/// Request senders.
senders: Rc<RefCell<FxHashMap<u64, RequestSender>>>,
/// Packet read buffer.
recv_buf: Vec<u8>,
/// Worker start time.
start_time: Instant,
/// Worker end time.
end_time: Option<Instant>,
/// If terminated by system signal.
terminated: Arc<AtomicBool>,
}
impl Worker {
/// Create a new single thread client.
pub fn new(
option: ClientOpt,
client_ctx: Arc<Mutex<ClientContext>>,
terminated: Arc<AtomicBool>,
) -> Result<Self> {
let mut config = Config::new()?;
config.enable_stateless_reset(!option.disable_stateless_reset);
config.set_max_handshake_timeout(option.handshake_timeout);
config.set_max_idle_timeout(option.idle_timeout);
config.set_initial_rtt(option.initial_rtt);
config.set_pto_linear_factor(option.pto_linear_factor);
config.set_max_pto(option.max_pto);
config.set_max_concurrent_conns(option.max_concurrent_conns);
config.set_initial_max_streams_bidi(option.max_concurrent_requests);
config.set_cid_len(option.cid_len);
config.set_send_batch_size(option.send_batch_size);
config.set_recv_udp_payload_size(option.recv_udp_payload_size);
config.set_send_udp_payload_size(option.send_udp_payload_size);
config.set_congestion_control_algorithm(option.congestion_control_algor);
config.set_initial_congestion_window(option.initial_congestion_window);
config.set_min_congestion_window(option.min_congestion_window);
config.enable_multipath(option.enable_multipath);
config.set_multipath_algorithm(option.multipath_algor);
config.set_active_connection_id_limit(option.active_cid_limit);
config.enable_encryption(!option.disable_encryption);
let tls_config = TlsConfig::new_client_config(
ApplicationProto::convert_to_vec(&option.alpn),
option.enable_early_data,
)?;
config.set_tls_config(tls_config);
let poll = mio::Poll::new()?;
let registry = poll.registry();
let worker_ctx = Rc::new(RefCell::new(WorkerContext::with_option(&option)));
let senders = Rc::new(RefCell::new(FxHashMap::default()));
// Use unspecified local addr or the given local addr
let remote = option.connect_to.unwrap();
let local = if !option.local_addresses.is_empty() {
SocketAddr::new(option.local_addresses[0], 0)
} else {
match remote.is_ipv4() {
true => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
false => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
}
};
let mut sock = QuicSocket::new(&local, registry)?;
let mut assigned_addrs = Vec::new();
assigned_addrs.push(sock.local_addr());
if let Some(addrs) = option.local_addresses.get(1..) {
for local in addrs {
let addr = sock.add(&SocketAddr::new(*local, 0), registry)?;
assigned_addrs.push(addr);
}
}
let sock = Rc::new(sock);
let handlers = WorkerHandler::new(
&option,
&assigned_addrs,
worker_ctx.clone(),
senders.clone(),
);
Ok(Worker {
option,
endpoint: Endpoint::new(Box::new(config), false, Box::new(handlers), sock.clone()),
poll,
remote,
sock,
worker_ctx,
client_ctx,
senders,
recv_buf: vec![0u8; MAX_BUF_SIZE],
start_time: Instant::now(),
end_time: None,
terminated,
})
}
/// Start the worker.
pub fn start(&mut self) -> Result<()> {
debug!("worker start, endpoint({:?})", self.endpoint.trace_id());
self.start_time = Instant::now();
let mut events = mio::Events::with_capacity(1024);
loop {
if self.process()? {
debug!("worker tasks finished, exit");
break;
}
self.poll.poll(&mut events, self.endpoint.timeout())?;
// Process IO events
for event in events.iter() {
if event.is_readable() {
self.process_read_event(event)?;
}
}
// Process timeout events.
// Note: Since `poll()` doesn't clearly tell if there was a timeout when it returns,
// it is up to the endpoint to check for a timeout and deal with it.
self.endpoint.on_timeout(Instant::now());
}
self.finish();
Ok(())
}
fn should_exit(&self) -> bool {
if self.terminated.load(Ordering::Relaxed) {
info!("worker terminated by system signal and waiting for tasks to finish.");
return true;
}
let worker_ctx = self.worker_ctx.borrow();
debug!("worker concurrent conns {}", worker_ctx.concurrent_conns);
if !worker_ctx.connected
&& worker_ctx.conn_finish_failed >= self.option.connection_failure_threshold
{
error!(
"connect server[{:?}] failed",
self.option.connect_to.unwrap()
);
return true;
}
if (self.option.duration > 0
&& (Instant::now() - self.start_time).as_secs() > self.option.duration)
|| (self.option.total_requests_per_thread > 0
&& worker_ctx.request_done >= self.option.total_requests_per_thread)
{
debug!(
"worker should exit, concurrent conns {}, request sent {}, request done {}",
worker_ctx.concurrent_conns, worker_ctx.request_sent, worker_ctx.request_done,
);
return true;
}
false
}
fn process(&mut self) -> Result<bool> {
// Process connections.
self.endpoint.process_connections()?;
// Check exit.
if self.should_exit() {
// Close endpoint.
self.endpoint.close(false);
// Close connections.
let mut senders = self.senders.borrow_mut();
for (index, _) in senders.iter_mut() {
let conn = self.endpoint.conn_get_mut(*index).unwrap();
_ = conn.close(true, 0x00, b"ok");
}
// Update worker end time.
if self.end_time.is_none() {
debug!("all tasks finished, update the end time and wait for saving session.");
self.end_time = Some(Instant::now());
}
if senders.len() == 0 {
// All connections are closed.
return Ok(true);
}
return Ok(false);
}
// Check and create new connections.
self.create_new_conns()?;
// Try to send requests.
self.try_send_requests();
Ok(false)
}
fn create_new_conns(&mut self) -> Result<()> {
let mut worker_ctx = self.worker_ctx.borrow_mut();
while worker_ctx.concurrent_conns < self.option.max_concurrent_conns {
match self.endpoint.connect(
self.sock.local_addr(),
self.remote,
self.option.urls[0].domain(),
worker_ctx.session.as_deref(),
None,
None,
) {
Ok(_) => {
worker_ctx.concurrent_conns += 1;
worker_ctx.conn_total += 1;
}
Err(e) => {
return Err(format!("connect error: {:?}", e).into());
}
};
}
Ok(())
}
fn try_send_requests(&mut self) {
let mut senders = self.senders.borrow_mut();
for (index, sender) in senders.iter_mut() {
let conn = self.endpoint.conn_get_mut(*index).unwrap();
sender.send_requests(conn);
}
}
fn process_read_event(&mut self, event: &Event) -> Result<()> {
loop {
// Read datagram from the socket.
// TODO: support recvmmsg
let (len, local, remote) = match self.sock.recv_from(&mut self.recv_buf, event.token())
{
Ok(v) => v,
Err(e) => {
if e.kind() == std::io::ErrorKind::WouldBlock {
debug!("socket recv would block");
break;
}
return Err(format!("socket recv error: {:?}", e).into());
}
};
debug!("socket recv {} bytes from {:?}", len, remote);
let pkt_buf = &mut self.recv_buf[..len];
let pkt_info = PacketInfo {
src: remote,
dst: local,
time: Instant::now(),
};
// Process the incoming packet.
match self.endpoint.recv(pkt_buf, &pkt_info) {
Ok(_) => {}
Err(e) => {
error!("recv failed: {:?}", e);
continue;
}
};
}
Ok(())
}
fn finish(&mut self) {
debug!("worker finished in {:?}", Instant::now() - self.start_time);
let mut worker_ctx = self.worker_ctx.borrow_mut();
let mut client_ctx = self.client_ctx.lock().unwrap();
client_ctx.session.clone_from(&worker_ctx.session);
client_ctx.request_sent += worker_ctx.request_sent;
client_ctx.request_done += worker_ctx.request_done;
client_ctx.request_success += worker_ctx.request_success;
client_ctx.conn_total += worker_ctx.conn_total;
client_ctx.conn_handshake_success += worker_ctx.conn_handshake_success;
client_ctx.conn_finish += worker_ctx.conn_finish;
client_ctx.conn_finish_success += worker_ctx.conn_finish_success;
client_ctx.conn_finish_failed += worker_ctx.conn_finish_failed;
client_ctx
.request_time_samples
.append(&mut worker_ctx.request_time_samples);
if self.end_time > client_ctx.end_time {
client_ctx.end_time = self.end_time;
}
update_conn_stats(&mut client_ctx.conn_stats, &worker_ctx.conn_stats);
}
}
/// Context used for single thread worker.
#[derive(Default)]
struct WorkerContext {
session: Option<Vec<u8>>,
request_sent: u64,
request_done: u64,
request_success: u64,
max_sample: usize,
request_time_samples: Vec<f64>,
conn_total: u64,
conn_handshake_success: u64,
conn_finish: u64,
conn_finish_success: u64,
conn_finish_failed: u64,
concurrent_conns: u32,
conn_stats: ConnectionStats,
connected: bool,
}
impl WorkerContext {
fn with_option(option: &ClientOpt) -> Self {
let mut worker_ctx = WorkerContext {
max_sample: option.max_sample,
..Default::default()
};
if let Some(session_file) = &option.session_file {
if let Ok(session_data) = std::fs::read(session_file) {
worker_ctx.session = Some(session_data);
} else {
debug!("no session file {:?}", option.session_file);
}
}
worker_ctx
}
}
struct Request {
url: Url,
line: String, // Used in http/0.9.
headers: Vec<Header>, // Used in h3.
response_writer: Option<std::io::BufWriter<std::fs::File>>,
start_time: Option<Instant>,
}
impl Request {
/// Make a response body writer.
/// The name of file is same as the URL's last path segment.
fn make_response_writer(url: &Url, target_path: &Option<String>) -> Option<BufWriter<File>> {
if let Some(target_path) = target_path {
let f = match url.path_segments().map(|c| c.collect::<Vec<_>>()) {
Some(f) => f,
None => {
error!("make response writer failed, url {:?}", url);
return None;
}
};
let f = match f.iter().last() {
Some(f) => f,
None => {
error!("make response writer failed, url {:?}", url);
return None;
}
};
let path = format!("{}/{}", target_path, f,);
match File::create(path) {
Ok(f) => Some(BufWriter::new(f)),
Err(e) => {
error!("create file error {:?}, url {:?}", e, url);
None
}
}
} else {
None
}
}
// TODO: support custom headers.
fn new(method: &str, url: &Url, body: &Option<Vec<u8>>, dump_dir: &Option<String>) -> Self {
let authority = match url.port() {
Some(port) => format!("{}:{}", url.host_str().unwrap(), port),
None => url.host_str().unwrap().to_string(),
};
let mut headers = vec![
tquic::h3::Header::new(b":method", method.as_bytes()),
tquic::h3::Header::new(b":scheme", url.scheme().as_bytes()),
tquic::h3::Header::new(b":authority", authority.as_bytes()),
tquic::h3::Header::new(b":path", url[url::Position::BeforePath..].as_bytes()),
tquic::h3::Header::new(b"user-agent", b"tquic"),
];
if body.is_some() {
headers.push(tquic::h3::Header::new(
b"content-length",
body.as_ref().unwrap().len().to_string().as_bytes(),
));
}
Self {
url: url.clone(),
line: format!("GET {}\r\n", url.path()),
headers,
response_writer: Self::make_response_writer(url, dump_dir),
start_time: None,
}
}
}
/// Used for sending http/0.9 or h3 requests. One connection has only one request sender.
struct RequestSender {
/// Sender option.
option: ClientOpt,
/// Current index of URLs.
current_url_idx: usize,
/// Concurrent requests of this sender.
concurrent_requests: u64,
/// Requests already sent of this sender.
request_sent: u64,
/// Requests already done of this sender.
request_done: u64,
/// Read buffer.
buf: Vec<u8>,
/// Mapping stream id to request.
streams: FxHashMap<u64, Request>,
/// Worker context.
worker_ctx: Rc<RefCell<WorkerContext>>,
/// Application protocol, http/0.9 or h3.
app_proto: ApplicationProto,
/// Next available stream id, used in http/0.9 mode.
next_stream_id: u64,
/// H3 connection, used in h3 mode.
h3_conn: Option<Http3Connection>,
}
impl RequestSender {
/// Create a new request sender.
pub fn new(
option: &ClientOpt,
conn: &mut Connection,
worker_ctx: Rc<RefCell<WorkerContext>>,
) -> Self {
let mut sender = Self {
option: option.clone(),
current_url_idx: 0,
concurrent_requests: 0,
request_sent: 0,
request_done: 0,
buf: vec![0; MAX_BUF_SIZE],
streams: FxHashMap::default(),
worker_ctx,
app_proto: ApplicationProto::from_slice(conn.application_proto()),
next_stream_id: 0,
h3_conn: None,
};
if sender.app_proto == ApplicationProto::H3 {
sender.h3_conn = Some(
Http3Connection::new_with_quic_conn(conn, &Http3Config::new().unwrap()).unwrap(),
);
}
sender
}
/// Send requests.
pub fn send_requests(&mut self, conn: &mut Connection) {
debug!(
"{} send requests {} {} {} {}",
conn.trace_id(),
self.concurrent_requests,
self.option.max_concurrent_requests,
self.request_sent,
self.option.max_requests_per_conn
);
while self.concurrent_requests < self.option.max_concurrent_requests
&& (self.option.max_requests_per_conn == 0
|| self.request_sent < self.option.max_requests_per_conn)
{
if let Err(e) = self.send_request(conn) {
error!("{} send request error {}", conn.trace_id(), e);
break;
}
}
}