forked from satori-com/tcpkali
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpkali_engine.c
2963 lines (2716 loc) · 107 KB
/
tcpkali_engine.c
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) 2014, 2015, 2016, 2017 Machine Zone, Inc.
*
* Original author: Lev Walkin <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h> /* for TCP_NODELAY */
#include <unistd.h>
#include <stddef.h> /* offsetof(3) */
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include <sys/queue.h>
#include <sysexits.h>
#include <math.h>
#include <sys/time.h>
#include <config.h>
#ifdef HAVE_SCHED_H
#include <sched.h>
#endif
#include <StreamBoyerMooreHorspool.h>
#include <hdr_histogram.h>
#include <pcg_basic.h>
#include "tcpkali.h"
#include "tcpkali_ring.h"
#include "tcpkali_atomic.h"
#include "tcpkali_events.h"
#include "tcpkali_pacefier.h"
#include "tcpkali_websocket.h"
#include "tcpkali_terminfo.h"
#include "tcpkali_logging.h"
#include "tcpkali_expr.h"
#include "tcpkali_data.h"
#include "tcpkali_traffic_stats.h"
#include "tcpkali_connection.h"
#include "tcpkali_ssl.h"
#ifndef TAILQ_FOREACH_SAFE
#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \
for((var) = TAILQ_FIRST((head)); \
(var) && ((tvar) = TAILQ_NEXT((var), field), 1); (var) = (tvar))
#endif
struct loop_arguments {
/**************************
* NON-SHARED WORKER DATA *
**************************/
struct engine_params params; /* A copy of engine parameters */
unsigned int
address_offset; /* An offset into the params.remote_addresses[] */
tk_timer stats_timer;
tk_timer channel_lifetime_timer;
int global_control_pipe_rd_nbio; /* Non-blocking pipe anyone could read
from. */
int global_feedback_pipe_wr; /* Blocking pipe for progress reporting. */
int private_control_pipe_rd; /* Private blocking pipe for this worker (read
side). */
int private_control_pipe_wr; /* Private blocking pipe for this worker (write
side). */
int thread_no;
int dump_connect_fd; /* Which connection to dump */
TAILQ_HEAD(, connection) open_conns; /* Thread-local connections */
unsigned long worker_connections_initiated;
unsigned long worker_connections_accepted;
unsigned long worker_connection_failures;
unsigned long worker_connection_timeouts;
struct hdr_histogram *connect_histogram_local; /* --latency-connect */
struct hdr_histogram *firstbyte_histogram_local; /* --latency-first-byte */
struct hdr_histogram *marker_histogram_local; /* --latency-marker */
/* Per-worker scratch buffer allows debugging the last received data */
char scratch_recv_buf[16384];
size_t scratch_recv_last_size;
pcg32_random_t rng;
/*******************************************
* WORKER DATA SHARED WITH OTHER PROCESSES *
*******************************************/
const struct engine_params *shared_eng_params;
/*
* Connection identifier counter is shared between all connections
* across all workers. We don't allocate it per worker, so it points
* to the same memory in the parameters of all workers.
*/
atomic_narrow_t *connection_unique_id_atomic;
/*
* Reporting histograms should not be touched
* unless asked through a private control pipe.
*/
struct hdr_histogram *connect_histogram_shared;
struct hdr_histogram *firstbyte_histogram_shared;
struct hdr_histogram *marker_histogram_shared;
pthread_mutex_t shared_histograms_lock;
/*
* Per-remote server stats, pointing to a global table.
*/
struct remote_stats {
atomic_narrow_t connection_attempts;
atomic_narrow_t connection_failures;
} * remote_stats;
/* The following atomic members are accessed outside of worker thread */
atomic_traffic_stats worker_traffic_stats;
atomic_narrow_t outgoing_connecting;
atomic_narrow_t outgoing_established;
atomic_narrow_t incoming_established;
atomic_narrow_t connections_counter;
/* Avoid mixing output from several threads when dumping complex state */
pthread_mutex_t *serialize_output_lock;
};
/*
* Types of control messages which might require fair ordering between channels.
*/
enum control_message_type_e {
CONTROL_MESSAGE_CONNECT,
_CONTROL_MESSAGES_MAXID /* Do not use. */
};
/*
* Engine abstracts over workers.
*/
struct engine {
struct engine_params params; /* A copy of engine parameters */
struct loop_arguments *loops;
pthread_t *threads;
int global_control_pipe_wr;
int global_feedback_pipe_rd;
int next_worker_order[_CONTROL_MESSAGES_MAXID];
int n_workers;
non_atomic_traffic_stats total_traffic_stats;
atomic_narrow_t connection_unique_id_global;
pthread_mutex_t serialize_output_lock;
};
const struct engine_params *
engine_params(struct engine *eng) {
return &eng->params;
}
/*
* Helper functions defined at the end of the file.
*/
enum connection_close_reason {
CCR_CLEAN, /* No failure */
CCR_LIFETIME, /* Channel lifetime limit (no failure) */
CCR_TIMEOUT, /* Connection timeout */
CCR_REMOTE, /* Remote side closed connection */
CCR_DATA, /* Data framing error */
};
static void *single_engine_loop_thread(void *argp);
static void start_new_connection(TK_P);
static void close_connection(TK_P_ struct connection *conn,
enum connection_close_reason reason);
static void connections_flush_stats(TK_P);
static void connection_flush_stats(TK_P_ struct connection *conn);
static void close_all_connections(TK_P_ enum connection_close_reason reason);
static void connection_cb(TK_P_ tk_io *w, int revents);
static void passive_websocket_cb(TK_P_ tk_io *w, int revents);
static void control_cb(TK_P_ tk_io *w, int revents);
static void accept_cb(TK_P_ tk_io *w, int revents);
static void stats_timer_cb(TK_P_ tk_timer UNUSED *w, int UNUSED revents);
static void conn_timer_cb(TK_P_ tk_timer *w, int revents); /* Timeout timer */
static void expire_channel_lives(TK_P_ tk_timer *w, int revents);
static void setup_channel_lifetime_timer(TK_P_ double first_timeout);
static void update_io_interest(TK_P_ struct connection *conn);
static struct sockaddr_storage *pick_remote_address(
struct loop_arguments *largs, size_t *remote_index);
static char *express_bytes(size_t bytes, char *buf, size_t size);
static int limit_channel_lifetime(struct loop_arguments *largs);
static void set_nbio(int fd, int onoff);
static void set_socket_options(int fd, struct loop_arguments *largs);
static void common_connection_init(TK_P_ struct connection *conn,
enum conn_type conn_type,
enum conn_state conn_state, int sockfd);
static void largest_contiguous_chunk(struct loop_arguments *largs,
struct connection *conn,
const void **position,
size_t *available_header,
size_t *available_body);
static void debug_dump_data(const char *prefix, int fd, const void *data,
size_t size, ssize_t limit);
static void debug_dump_data_highlight(const char *prefix, int fd,
const void *data, size_t size,
ssize_t limit, size_t hl_offset,
size_t hl_length);
static void
latency_record_incoming_ts(TK_P_ struct connection *conn, char *buf,
size_t size);
#ifdef USE_LIBUV
static void
expire_channel_lives_uv(tk_timer *w) {
expire_channel_lives(w->loop, w, 0);
}
static void
stats_timer_cb_uv(tk_timer *w) {
stats_timer_cb(w->loop, w, 0);
}
static void
conn_timer_cb_uv(tk_timer *w) {
conn_timer_cb(w->loop, w, 0);
}
static void
passive_websocket_cb_uv(tk_io *w, int UNUSED status, int revents) {
passive_websocket_cb(w->loop, w, revents);
}
static void
connection_cb_uv(tk_io *w, int UNUSED status, int revents) {
connection_cb(w->loop, w, revents);
}
static void
accept_cb_uv(tk_io *w, int UNUSED status, int revents) {
accept_cb(w->loop, w, revents);
}
static void
control_cb_uv(tk_io *w, int UNUSED status, int revents) {
control_cb(w->loop, w, revents);
}
#endif
#define DEBUG(level, fmt, args...) \
do { \
if((int)largs->params.verbosity_level >= level) \
debug_log(level, largs->params.verbosity_level, fmt, ##args); \
} while(0)
struct engine *
engine_start(struct engine_params params) {
int fildes[2];
/* Global control pipe. Engine -> workers. */
int rc = pipe(fildes);
assert(rc == 0);
int gctl_pipe_rd = fildes[0];
int gctl_pipe_wr = fildes[1];
set_nbio(gctl_pipe_rd, 1);
/* Global feedback pipe. Engine <- workers. */
rc = pipe(fildes);
assert(rc == 0);
int gfbk_pipe_rd = fildes[0];
int gfbk_pipe_wr = fildes[1];
/* Figure out number of asynchronous workers to start. */
int n_workers = params.requested_workers;
if(!n_workers) {
long n_cpus = number_of_cpus();
fprintf(stderr, "Using %ld available CPUs\n", n_cpus);
assert(n_cpus >= 1);
n_workers = n_cpus;
}
/*
* The data template creation may fail because the message collection
* might contain expressions which must be resolved
* on a per connection or per message basis.
*/
enum transport_websocket_side tws_side;
for(tws_side = TWS_SIDE_CLIENT; tws_side <= TWS_SIDE_SERVER; tws_side++) {
assert(params.data_templates[tws_side] == NULL);
pcg32_random_t rng;
pcg32_srandom_r(&rng, random(), tws_side);
params.data_templates[tws_side] =
transport_spec_from_message_collection(
0, ¶ms.message_collection, 0, 0, tws_side,
TS_CONVERSION_INITIAL, &rng);
assert(params.data_templates[tws_side]
|| params.message_collection.most_dynamic_expression
!= DS_GLOBAL_FIXED);
}
if(params.data_templates[0])
replicate_payload(params.data_templates[0], REPLICATE_MAX_SIZE);
if(params.data_templates[1])
replicate_payload(params.data_templates[1], REPLICATE_MAX_SIZE);
struct engine *eng = calloc(1, sizeof(*eng));
eng->params = params;
eng->loops = calloc(n_workers, sizeof(eng->loops[0]));
eng->threads = calloc(n_workers, sizeof(eng->threads[0]));
eng->n_workers = n_workers;
eng->global_control_pipe_wr = gctl_pipe_wr;
eng->global_feedback_pipe_rd = gfbk_pipe_rd;
if(pthread_mutex_init(&eng->serialize_output_lock, 0) != 0) {
/* At this stage in the program, no point to continue. */
assert(!"Should really be unreachable");
return NULL;
}
/*
* Initialize the Boyer-Moore-Horspool occurrences table once,
* if it can be shared between connections. It can only be shared
* if it is trivial (does not depend on dynamic \{expressions}).
*/
if(params.latency_marker_expr /* --latency-marker, --message-marker */
&& EXPR_IS_TRIVIAL(params.latency_marker_expr)) {
sbmh_init(NULL, ¶ms.sbmh_shared_marker_occ,
(void *)params.latency_marker_expr->u.data.data,
params.latency_marker_expr->u.data.size);
}
if(params.message_stop_expr /* --message-stop */
&& EXPR_IS_TRIVIAL(params.message_stop_expr)) {
sbmh_init(NULL, ¶ms.sbmh_shared_stop_occ,
(void *)params.message_stop_expr->u.data.data,
params.message_stop_expr->u.data.size);
}
params.epoch = tk_now(TK_DEFAULT); /* Single epoch for all threads */
for(int n = 0; n < eng->n_workers; n++) {
struct loop_arguments *largs = &eng->loops[n];
TAILQ_INIT(&largs->open_conns);
largs->connection_unique_id_atomic = &eng->connection_unique_id_global;
largs->params = params;
largs->shared_eng_params = &eng->params;
largs->remote_stats = calloc(params.remote_addresses.n_addrs,
sizeof(largs->remote_stats[0]));
largs->address_offset = n;
largs->thread_no = n;
largs->serialize_output_lock = &eng->serialize_output_lock;
const int decims_in_1s = 10 * 1000; /* decimilliseconds, 1/10 ms */
if(params.latency_setting & SLT_CONNECT) {
int ret = hdr_init(
1, /* 1/10 milliseconds is the lowest storable value. */
100 * decims_in_1s, /* 100 seconds is a max storable value */
3, &largs->connect_histogram_local);
assert(ret == 0);
}
if(params.latency_setting & SLT_FIRSTBYTE) {
int ret = hdr_init(
1, /* 1/10 milliseconds is the lowest storable value. */
100 * decims_in_1s, /* 100 seconds is a max storable value */
3, &largs->firstbyte_histogram_local);
assert(ret == 0);
}
if(params.latency_setting & SLT_MARKER) {
int ret = hdr_init(
1, /* 1/10 milliseconds is the lowest storable value. */
100 * decims_in_1s, /* 100 seconds is a max storable value */
3, &largs->marker_histogram_local);
assert(ret == 0);
DEBUG(DBG_DETAIL, "Initialized HdrHistogram with size %ld\n",
(long)hdr_get_memory_size(largs->marker_histogram_local));
}
if(pthread_mutex_init(&largs->shared_histograms_lock, 0) != 0) {
/* At this stage in the program, no point to continue. */
assert(!"Should really be unreachable");
}
int private_pipe[2];
int rc = pipe(private_pipe);
assert(rc == 0);
largs->private_control_pipe_rd = private_pipe[0];
largs->private_control_pipe_wr = private_pipe[1];
largs->global_control_pipe_rd_nbio = gctl_pipe_rd;
largs->global_feedback_pipe_wr = gfbk_pipe_wr;
pcg32_srandom_r(&largs->rng, random(), n);
rc = pthread_create(&eng->threads[n], 0, single_engine_loop_thread,
largs);
assert(rc == 0);
}
return eng;
}
/*
* Format and print latency snapshot.
*/
static void
print_latency_hdr_histrogram_percentiles(
const char *title, const struct percentile_values *report_percentiles,
struct hdr_histogram *histogram) {
assert(histogram);
size_t size = report_percentiles->size;
printf("%s latency at percentiles: ", title);
for(size_t i = 0; i < size; i++) {
double per_d = report_percentiles->values[i].value_d;
printf("%.1f%s", hdr_value_at_percentile(histogram, per_d) / 10.0,
i == size - 1 ? "" : "/");
}
printf(" ms (");
for(size_t i = 0; i < size; i++) {
printf("%s%s", report_percentiles->values[i].value_s,
i == size - 1 ? "" : "/");
}
printf("%%)\n");
}
static void
latency_snapshot_print(const struct percentile_values *latency_percentiles,
const struct latency_snapshot *latency) {
if(latency->connect_histogram) {
print_latency_hdr_histrogram_percentiles(
"TCP connect", latency_percentiles, latency->connect_histogram);
}
if(latency->firstbyte_histogram) {
print_latency_hdr_histrogram_percentiles("First byte", latency_percentiles,
latency->firstbyte_histogram);
}
if(latency->marker_histogram) {
print_latency_hdr_histrogram_percentiles("Message", latency_percentiles,
latency->marker_histogram);
}
}
/*
* Estimate packets per second.
*/
static unsigned int
estimate_segments_per_op(non_atomic_wide_t ops, non_atomic_wide_t bytes) {
const int tcp_mss = 1460; /* TCP Maximum Segment Size, estimate! */
return ops ? ((bytes / ops) + (tcp_mss - 1)) / tcp_mss : 0;
}
static double
estimate_pps(double duration, non_atomic_wide_t ops, non_atomic_wide_t bytes) {
unsigned packets_per_op = estimate_segments_per_op(ops, bytes);
return (packets_per_op * ops) / duration;
}
void
engine_update_workers_send_rate(struct engine *eng, rate_spec_t rate_spec) {
/*
* Ask workers to recompute per-connection rates.
*/
eng->params.channel_send_rate = rate_spec;
for(int n = 0; n < eng->n_workers; n++) {
int rc = write(eng->loops[n].private_control_pipe_wr, "r", 1);
assert(rc == 1);
}
}
rate_spec_t
engine_set_message_send_rate(struct engine *eng, double msg_rate) {
rate_spec_t new_rate = RATE_MPS(msg_rate);
engine_update_workers_send_rate(eng, new_rate);
return new_rate;
}
rate_spec_t
engine_update_send_rate(struct engine *eng, double multiplier) {
rate_spec_t new_rate = eng->params.channel_send_rate;
new_rate.value = new_rate.value * multiplier;
engine_update_workers_send_rate(eng, new_rate);
return new_rate;
}
/*
* Send a signal to finish work and wait for all workers to terminate.
*/
void
engine_terminate(struct engine *eng, double epoch,
non_atomic_traffic_stats initial_traffic_stats,
struct percentile_values *latency_percentiles) {
size_t connecting, conn_in, conn_out, conn_counter;
engine_get_connection_stats(eng, &connecting, &conn_in, &conn_out,
&conn_counter);
/*
* Terminate all workers.
*/
for(int n = 0; n < eng->n_workers; n++) {
int rc = write(eng->loops[n].private_control_pipe_wr, "T", 1);
assert(rc == 1);
}
for(int n = 0; n < eng->n_workers; n++) {
struct loop_arguments *largs = &eng->loops[n];
void *value;
pthread_join(eng->threads[n], &value);
add_traffic_numbers_AtoN(&largs->worker_traffic_stats,
&eng->total_traffic_stats);
}
/*
* The engine termination (using 'T') will implicitly prepare
* latency snapshots. We only need to collect it now.
*/
struct latency_snapshot *latency = engine_collect_latency_snapshot(eng);
eng->n_workers = 0;
/* Data snd/rcv after ramp-up (since epoch) */
double now = tk_now(TK_DEFAULT);
double test_duration = now - epoch;
non_atomic_traffic_stats epoch_traffic =
subtract_traffic_stats(eng->total_traffic_stats, initial_traffic_stats);
non_atomic_wide_t epoch_data_transmitted =
epoch_traffic.bytes_sent + epoch_traffic.bytes_rcvd;
char buf[64];
printf("Total data sent: %s (%" PRIu64 " bytes)\n",
express_bytes(epoch_traffic.bytes_sent, buf, sizeof(buf)),
(uint64_t)epoch_traffic.bytes_sent);
printf("Total data received: %s (%" PRIu64 " bytes)\n",
express_bytes(epoch_traffic.bytes_rcvd, buf, sizeof(buf)),
(uint64_t)epoch_traffic.bytes_rcvd);
long conns = (0 * connecting) + conn_in + conn_out;
if(!conns) conns = 1; /* Assume a single channel. */
printf("Bandwidth per channel: %.3f⇅ Mbps (%.1f kBps)\n",
8 * ((epoch_data_transmitted / test_duration) / conns) / 1000000.0,
(epoch_data_transmitted / test_duration) / conns / 1000.0);
printf("Aggregate bandwidth: %.3f↓, %.3f↑ Mbps\n",
8 * (epoch_traffic.bytes_rcvd / test_duration) / 1000000.0,
8 * (epoch_traffic.bytes_sent / test_duration) / 1000000.0);
if(eng->params.message_marker) {
printf("Aggregate message rate: %.3f↓, %.3f↑ mps\n",
(epoch_traffic.msgs_rcvd / test_duration),
(epoch_traffic.msgs_sent / test_duration));
}
printf("Packet rate estimate: %.1f↓, %.1f↑ (%u↓, %u↑ TCP MSS/op)\n",
estimate_pps(test_duration, epoch_traffic.num_reads,
epoch_traffic.bytes_rcvd),
estimate_pps(test_duration, epoch_traffic.num_writes,
epoch_traffic.bytes_sent),
estimate_segments_per_op(epoch_traffic.num_reads,
epoch_traffic.bytes_rcvd),
estimate_segments_per_op(epoch_traffic.num_writes,
epoch_traffic.bytes_sent));
latency_snapshot_print(latency_percentiles, latency);
engine_free_latency_snapshot(latency);
printf("Test duration: %g s.\n", test_duration);
}
static char *
express_bytes(size_t bytes, char *buf, size_t size) {
if(bytes < 2048) {
snprintf(buf, size, "%ld bytes", (long)bytes);
} else if(bytes < 512 * 1024) {
snprintf(buf, size, "%.1f KiB", (bytes / 1024.0));
} else {
snprintf(buf, size, "%.1f MiB", (bytes / (1024 * 1024.0)));
}
return buf;
}
/*
* Get number of connections opened by all of the workers.
*/
void
engine_get_connection_stats(struct engine *eng, size_t *connecting,
size_t *incoming, size_t *outgoing,
size_t *counter) {
size_t c_conn = 0;
size_t c_in = 0;
size_t c_out = 0;
size_t c_count = 0;
for(int n = 0; n < eng->n_workers; n++) {
c_conn += atomic_get(&eng->loops[n].outgoing_connecting);
c_out += atomic_get(&eng->loops[n].outgoing_established);
c_in += atomic_get(&eng->loops[n].incoming_established);
c_count += atomic_get(&eng->loops[n].connections_counter);
}
*connecting = c_conn;
*incoming = c_in;
*outgoing = c_out;
*counter = c_count;
}
void
engine_free_latency_snapshot(struct latency_snapshot *latency) {
if(latency) {
free(latency->connect_histogram);
free(latency->firstbyte_histogram);
free(latency->marker_histogram);
free(latency);
}
}
/*
* Prepare latency snapshot data.
*/
void
engine_prepare_latency_snapshot(struct engine *eng) {
if(eng->params.latency_setting != 0) {
/*
* If histogram is requested, we first need to ask each worker to
* assemble that information among its connections.
*/
for(int n = 0; n < eng->n_workers; n++) {
int fd = eng->loops[n].private_control_pipe_wr;
int wrote = write(fd, "h", 1);
assert(wrote == 1);
}
/* Gather feedback. */
for(int n = 0; n < eng->n_workers; n++) {
char c;
int rd = read(eng->global_feedback_pipe_rd, &c, 1);
assert(rd == 1);
assert(c == '.');
}
}
}
/*
* Grab the prepared latency snapshot data.
*/
struct latency_snapshot *
engine_collect_latency_snapshot(struct engine *eng) {
struct latency_snapshot *latency = calloc(1, sizeof(*latency));
if(eng->params.latency_setting == 0) return latency;
struct hdr_init_values {
int64_t lowest_trackable_value;
int64_t highest_trackable_value;
int64_t significant_figures;
} conn_init = {0, 0, 0}, fb_init = {0, 0, 0}, mark_init = {0, 0, 0};
/* There's going to be no wait or contention here due
* to the pipe-driven command-response logic. However,
* we still lock the reporting histogram to pretend that
* we correctly deal with memory barriers (which we don't
* have to on x86).
*/
pthread_mutex_lock(&eng->loops[0].shared_histograms_lock);
if(eng->loops[0].connect_histogram_shared) {
conn_init.lowest_trackable_value =
eng->loops[0].connect_histogram_shared->lowest_trackable_value;
conn_init.highest_trackable_value =
eng->loops[0].connect_histogram_shared->highest_trackable_value;
conn_init.significant_figures =
eng->loops[0].connect_histogram_shared->significant_figures;
}
if(eng->loops[0].firstbyte_histogram_shared) {
fb_init.lowest_trackable_value =
eng->loops[0].firstbyte_histogram_shared->lowest_trackable_value;
fb_init.highest_trackable_value =
eng->loops[0].firstbyte_histogram_shared->highest_trackable_value;
fb_init.significant_figures =
eng->loops[0].firstbyte_histogram_shared->significant_figures;
}
if(eng->loops[0].marker_histogram_shared) {
mark_init.lowest_trackable_value =
eng->loops[0].marker_histogram_shared->lowest_trackable_value;
mark_init.highest_trackable_value =
eng->loops[0].marker_histogram_shared->highest_trackable_value;
mark_init.significant_figures =
eng->loops[0].marker_histogram_shared->significant_figures;
}
pthread_mutex_unlock(&eng->loops[0].shared_histograms_lock);
if(conn_init.significant_figures) {
int ret = hdr_init(
conn_init.lowest_trackable_value, conn_init.highest_trackable_value,
conn_init.significant_figures, &latency->connect_histogram);
assert(ret == 0);
}
if(fb_init.significant_figures) {
int ret = hdr_init(
fb_init.lowest_trackable_value, fb_init.highest_trackable_value,
fb_init.significant_figures, &latency->firstbyte_histogram);
assert(ret == 0);
}
if(mark_init.significant_figures) {
int ret = hdr_init(
mark_init.lowest_trackable_value, mark_init.highest_trackable_value,
mark_init.significant_figures, &latency->marker_histogram);
assert(ret == 0);
}
for(int n = 0; n < eng->n_workers; n++) {
pthread_mutex_lock(&eng->loops[n].shared_histograms_lock);
if(latency->connect_histogram)
hdr_add(latency->connect_histogram,
eng->loops[n].connect_histogram_shared);
if(latency->firstbyte_histogram)
hdr_add(latency->firstbyte_histogram,
eng->loops[n].firstbyte_histogram_shared);
if(latency->marker_histogram)
hdr_add(latency->marker_histogram,
eng->loops[n].marker_histogram_shared);
pthread_mutex_unlock(&eng->loops[n].shared_histograms_lock);
}
return latency;
}
struct latency_snapshot *
engine_diff_latency_snapshot(struct latency_snapshot *base, struct latency_snapshot *update) {
assert(base);
assert(update);
struct latency_snapshot *diff = calloc(1, sizeof(*diff));
assert(diff);
if(base->connect_histogram)
diff->connect_histogram =
hdr_diff(base->connect_histogram, update->connect_histogram);
if(base->firstbyte_histogram)
diff->firstbyte_histogram =
hdr_diff(base->firstbyte_histogram, update->firstbyte_histogram);
if(base->marker_histogram)
diff->marker_histogram =
hdr_diff(base->marker_histogram, update->marker_histogram);
return diff;
}
non_atomic_traffic_stats
engine_traffic(struct engine *eng) {
non_atomic_traffic_stats traffic = {0, 0, 0, 0, 0, 0};
for(int n = 0; n < eng->n_workers; n++) {
add_traffic_numbers_AtoN(&eng->loops[n].worker_traffic_stats, &traffic);
}
return traffic;
}
/*
* Enable (1) and disable (0) the non-blocking mode on a file descriptor.
*/
static void
set_nbio(int fd, int onoff) {
int rc;
if(onoff) {
/* Enable non-blocking mode. */
rc = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
} else {
/* Enable blocking mode (disable non-blocking). */
rc = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
}
assert(rc != -1);
}
#define SET_XXXBUF(fd, opt, value) \
do { \
if((value)) set_socket_xxxbuf(fd, opt, #opt, value, largs); \
} while(0)
static void
set_socket_xxxbuf(int fd, int opt, const char *opt_name, size_t value,
struct loop_arguments *largs) {
int rc = setsockopt(fd, SOL_SOCKET, opt, &value, sizeof(value));
assert(rc != -1);
if(largs->params.verbosity_level >= DBG_DETAIL) {
size_t end_value = value;
socklen_t end_value_size = sizeof(end_value);
int rc =
getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &end_value, &end_value_size);
assert(rc != -1);
DEBUG(DBG_DETAIL, "setsockopt(%d, %s, %ld) -> %ld\n", fd, opt_name,
(long)value, (long)end_value);
}
}
static void
set_socket_options(int fd, struct loop_arguments *largs) {
int on = ~0;
int rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
assert(rc != -1);
if(largs->params.nagle_setting != NSET_UNSET) {
int v = largs->params.nagle_setting;
rc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v));
assert(rc != -1);
}
SET_XXXBUF(fd, SO_RCVBUF, largs->params.sock_rcvbuf_size);
SET_XXXBUF(fd, SO_SNDBUF, largs->params.sock_sndbuf_size);
}
size_t
engine_initiate_new_connections(struct engine *eng, size_t n_req) {
static char buf[1024]; /* This is thread-safe! */
if(!buf[0]) {
memset(buf, 'c', sizeof(buf));
}
size_t n = 0;
enum {
ATTEMPT_FAIR_BALANCE,
FIRST_READER_WINS
} balance = ATTEMPT_FAIR_BALANCE;
if(balance == ATTEMPT_FAIR_BALANCE) {
while(n < n_req) {
int worker = eng->next_worker_order[CONTROL_MESSAGE_CONNECT]++
% eng->n_workers;
int fd = eng->loops[worker].private_control_pipe_wr;
int wrote = write(fd, buf, 1);
if(wrote == -1 && errno == EINTR) /* Ctrl+C? */
return n;
assert(wrote == 1);
n++;
}
} else {
int fd = eng->global_control_pipe_wr;
set_nbio(fd, 1);
while(n < n_req) {
int current_batch =
(n_req - n) < sizeof(buf) ? (n_req - n) : sizeof(buf);
int wrote = write(fd, buf, current_batch);
if(wrote == -1) {
if(errno == EAGAIN) break;
if(errno == EINTR) return n; /* Ctrl+C? */
assert(wrote != -1);
}
if(wrote > 0) n += wrote;
}
set_nbio(fd, 0);
}
return n;
}
static void
expire_channel_lives(TK_P_ tk_timer UNUSED *w, int UNUSED revents) {
struct loop_arguments *largs = tk_userdata(TK_A);
struct connection *conn;
struct connection *tmpconn;
assert(limit_channel_lifetime(largs));
double delta = tk_now(TK_A) - largs->params.epoch;
TAILQ_FOREACH_SAFE(conn, &largs->open_conns, hook, tmpconn) {
double expires_in = conn->channel_eol_point - delta;
if(expires_in <= 0.0) {
close_connection(TK_A_ conn, CCR_CLEAN);
} else {
/*
* Channels are added to the tail of the queue and have the same
* Expiration timeout. This channel and the others after it
* are not yet expired. Restart timeout so we'll get to it
* and the one after it when the time is really due.
*/
setup_channel_lifetime_timer(TK_A_ expires_in);
break;
}
}
}
static void
stats_timer_cb(TK_P_ tk_timer UNUSED *w, int UNUSED revents) {
connections_flush_stats(TK_A);
}
static void *
single_engine_loop_thread(void *argp) {
struct loop_arguments *largs = (struct loop_arguments *)argp;
tk_loop *loop = tk_loop_new();
tk_set_userdata(loop, largs);
tk_io global_control_watcher;
tk_io private_control_watcher;
const int on_main_thread = (largs->thread_no == 0);
#ifdef SO_REUSEPORT
const int have_reuseport = 1;
#else
const int have_reuseport = 0;
#endif
/*
* If want to serve connections but don't have SO_REUSEPORT,
* tell the user upfront.
*/
if(!have_reuseport && on_main_thread
&& largs->params.listen_addresses.n_addrs) {
warning(
"A system without SO_REUSEPORT detected."
" Using only one core for serving connections.\n");
}
signal(SIGPIPE, SIG_IGN);
tcpkali_ssl_thread_setup();
/*
* Open all listening sockets, if they are specified.
*/
if(largs->params.listen_addresses.n_addrs
/* Only listen on stuff on other cores when SO_REUSEPORT is available */
&& (have_reuseport || on_main_thread)) {
int opened_listening_sockets = 0;
for(size_t n = 0; n < largs->params.listen_addresses.n_addrs; n++) {
struct sockaddr_storage *ss =
&largs->params.listen_addresses.addrs[n];
int rc;
int lsock = socket(ss->ss_family, SOCK_STREAM, IPPROTO_TCP);
assert(lsock != -1);
set_nbio(lsock, 1);
#ifdef SO_REUSEPORT
int on = ~0;
rc = setsockopt(lsock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
assert(rc != -1);
#else
/*
* SO_REUSEPORT cannot be used, which means that only a single
* thread could create their own separate listening socket on
* a specified address/port. This is bad, but changing.
* See http://permalink.gmane.org/gmane.linux.network/158320
*/
#endif /* SO_REUSEPORT */
rc = bind(lsock, (struct sockaddr *)ss, sockaddr_len(ss));
if(rc == -1) {
char buf[256];
DEBUG(DBG_ALWAYS, "Bind %s is not done on thread %d: %s\n",
format_sockaddr(ss, buf, sizeof(buf)), largs->thread_no,
strerror(errno));
exit(EX_UNAVAILABLE);
}
assert(rc == 0);
rc = listen(lsock, 256);
assert(rc == 0);
opened_listening_sockets++;
struct connection *conn = calloc(1, sizeof(*conn));
conn->conn_type = CONN_ACCEPTOR;
/* avoid TAILQ_INSERT_TAIL(&largs->open_conns, conn, hook); */
pacefier_init(&conn->send_pace, -1.0, tk_now(TK_A));
pacefier_init(&conn->recv_pace, -1.0, tk_now(TK_A));
#ifdef USE_LIBUV
uv_poll_init(TK_A_ & conn->watcher, lsock);
uv_poll_start(&conn->watcher, TK_READ | TK_WRITE, accept_cb_uv);
#else
ev_io_init(&conn->watcher, accept_cb, lsock, TK_READ | TK_WRITE);
ev_io_start(TK_A_ & conn->watcher);
#endif
}
if(!opened_listening_sockets) {
DEBUG(DBG_ALWAYS, "Could not listen on any local sockets!\n");
exit(EX_UNAVAILABLE);
}
}
const int stats_flush_interval_ms = 42;
#ifdef USE_LIBUV
if(limit_channel_lifetime(largs)) {
uv_timer_init(TK_A_ & largs->channel_lifetime_timer);
uv_timer_start(&largs->channel_lifetime_timer, expire_channel_lives_uv,
0, 0);
}
uv_timer_init(TK_A_ & largs->stats_timer);
uv_timer_start(&largs->stats_timer, stats_timer_cb_uv, stats_flush_interval_ms, stats_flush_interval_ms);
uv_poll_init(TK_A_ & global_control_watcher,
largs->global_control_pipe_rd_nbio);
uv_poll_init(TK_A_ & private_control_watcher,
largs->private_control_pipe_rd);
uv_poll_start(&global_control_watcher, TK_READ, control_cb_uv);
uv_poll_start(&private_control_watcher, TK_READ, control_cb_uv);
uv_run(TK_A_ UV_RUN_DEFAULT);
uv_timer_stop(&largs->stats_timer);
uv_poll_stop(&global_control_watcher);
uv_poll_stop(&private_control_watcher);
#else
if(limit_channel_lifetime(largs)) {
ev_timer_init(&largs->channel_lifetime_timer, expire_channel_lives, 0,
0);
}
ev_timer_init(&largs->stats_timer, stats_timer_cb, stats_flush_interval_ms / 1000.0, stats_flush_interval_ms / 1000.0);
ev_timer_start(TK_A_ & largs->stats_timer);
ev_io_init(&global_control_watcher, control_cb,
largs->global_control_pipe_rd_nbio, TK_READ);
ev_io_init(&private_control_watcher, control_cb,
largs->private_control_pipe_rd, TK_READ);
ev_io_start(loop, &global_control_watcher);
ev_io_start(loop, &private_control_watcher);
ev_run(loop, 0);