-
Notifications
You must be signed in to change notification settings - Fork 7
/
httpress.c
2738 lines (2370 loc) · 75.4 KB
/
httpress.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) 2011-2012 Yaroslav Stavnichiy <yarosla@gmail.com>
*
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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.
*/
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <assert.h>
#include <malloc.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <signal.h>
#include <pthread.h>
#include <sys/stat.h>
#include <errno.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/sendfile.h>
#include <netdb.h>
#include <http_parser.h>
#include <parserutils/input/inputstream.h>
#include <parserutils/charset/mibenum.h>
#include <uchardet/uchardet.h>
//#define WITH_SSL
#ifdef WITH_SSL
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#endif
#include <ev.h>
enum { DBG_INFO = 1, DBG_DEBUG, DBG_BODY, DBG_MAX };
#define VERSION "1.1"
/****************************************************************************************
* List operations
****************************************************************************************/
struct cd_list {
struct cd_list *prev;
struct cd_list *next;
};
static inline void cd_list_add(struct cd_list *p, struct cd_list *list)
{
p->prev = list->prev;
p->next = list;
p->next->prev = p;
p->prev->next = p;
}
static inline void cd_list_del(struct cd_list *list)
{
list->prev->next = list->next;
list->next->prev = list->prev;
list->prev = 0;
list->next = 0;
}
static inline void cd_list_init(struct cd_list *list)
{
list->prev = list;
list->next = list;
}
static inline void cd_list_del_init(struct cd_list *list)
{
cd_list_del(list);
cd_list_init(list);
}
static inline int cd_list_empty(const struct cd_list *list)
{
return (list->next == list);
}
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((ULONG_PTR) &((TYPE*)0)->MEMBER)
#endif
#ifndef container_of
#define container_of(ptr, type, member) \
((type *)(((char *)(ptr)) - offsetof(type,member)))
#endif
#define cd_list_entry(ptr, type, member) \
container_of(ptr, type, member)
#define cd_list_first_entry(ptr, type, member) \
cd_list_entry((ptr)->next, type, member)
#define cd_list_for_each_entry(typeof_pos, pos, head, member) \
for (pos = cd_list_entry((head)->next, typeof_pos, member); \
&pos->member != (head); \
pos = cd_list_entry(pos->member.next, typeof_pos, member))
#define cd_list_for_each_entry_safe(typeof_pos, pos, n, head, member) \
for (pos = cd_list_entry((head)->next, typeof_pos, member), \
n = cd_list_entry(pos->member.next, typeof_pos, member); \
&pos->member != (head); \
pos = n, n = cd_list_entry(n->member.next, typeof_pos, member))
/****************************************************************************************
* Atomic operations
****************************************************************************************/
typedef long long atomic_val_t;
typedef struct { volatile atomic_val_t val; } atomic_t;
atomic_t reqs_in_flight; // number of sent HTTP packets
int concurrency_max; // max reached concurrency
atomic_t concurrency_sum; // sum of concurrency values to calc average value later
static inline void atomic_set(atomic_t *p, atomic_val_t val)
{
p->val = val;
}
static inline atomic_val_t atomic_get(atomic_t *p)
{
return p->val;
}
static inline atomic_val_t atomic_inc(atomic_t *p)
{
return __sync_add_and_fetch(&p->val, 1);
}
static inline atomic_val_t atomic_add(atomic_t *p, int val)
{
return __sync_add_and_fetch(&p->val, val);
}
static inline atomic_val_t atomic_dec(atomic_t *p)
{
return __sync_sub_and_fetch(&p->val, 1);
}
/****************************************************************************************
* Requests stats
****************************************************************************************/
#define STATS_INC(conn, name) \
do { \
atomic_inc(&conn->tdata->stats.name); \
atomic_inc(&conn->stats.name); \
} while (0)
#define STATS_ADD(conn, name, val) \
do { \
atomic_add(&conn->tdata->stats.name, (val)); \
atomic_add(&conn->stats.name, (val)); \
} while (0)
struct req_stats {
atomic_t num_success;
atomic_t num_success_prev;
atomic_t num_fail;
atomic_t num_fail_prev;
atomic_t num_2xx;
atomic_t num_bytes_received;
atomic_t num_overhead_received;
atomic_t num_connect;
};
static void print_stats_sep(void)
{
printf("---------------------------------------------+-------------------+----------------------\n");
}
static void print_stats_header(void)
{
printf("========================================================================================\n");
printf("%8s | %8s %8s %8s %6s | %8s %8s | %10s %10s\n",
"", "Conns", "Requests", "Success", "Failed",
"2xx", "non-2xx", "Bytes", "Overhead");
print_stats_sep();
}
static void print_stats_row(char *pfx, struct req_stats *stats)
{
printf("%8s | %8lld %8lld %8lld %6lld | %8lld %8lld | %10lld %10lld\n",
pfx,
atomic_get(&stats->num_connect),
atomic_get(&stats->num_success) + atomic_get(&stats->num_fail),
atomic_get(&stats->num_success),
atomic_get(&stats->num_fail),
atomic_get(&stats->num_2xx),
atomic_get(&stats->num_success) - atomic_get(&stats->num_2xx),
atomic_get(&stats->num_bytes_received),
atomic_get(&stats->num_overhead_received));
}
/****************************************************************************************
* Structures
****************************************************************************************/
#if (__SIZEOF_POINTER__ == 8)
typedef uint64_t int_to_ptr;
#else
typedef uint32_t int_to_ptr;
#endif
#define MEM_GUARD 128
#define MAX_DOMAINS_NUMBER 1024
#define REQ_DELIM ("\r\n")
#define REQ_DELIM_LEN 2
enum comm_press_mode { PM_NUMBER, PM_TIME };
struct common_config {
int debug_level;
int tot_domains_number;
int concurrency;
int thread_concurrency_limit;
int num_connections;
int num_requests;
int num_threads;
int need_to_stop;
enum comm_press_mode press_mode;
int progress_step;
int secure;
const char* ssl_cipher_priority;
int keep_alive:1;
int quiet:1;
int save_cookies:1;
int include_non2xx:1;
char _padding1[MEM_GUARD];
volatile int request_counter;
char _padding2[MEM_GUARD];
int range;
int range_start;
int range_end;
double sleep_time;
int percentile;
};
enum body_parser_parsing_state {PS_NORMAL, PS_DIGITS};
struct body_parser {
parserutils_inputstream *stream;
parserutils_inputstream *regexp;
int found;
int enabled;
enum body_parser_parsing_state pstate;
int got_digit;
};
struct config {
struct addrinfo *saddr;
const char* uri_path;
const char* uri_host;
char* url;
char request_headers[4096];
int request_headers_length;
char* request_body;
size_t request_body_length;
int secure;
struct req_stats stats;
#ifdef WITH_SSL
gnutls_certificate_credentials_t ssl_cred;
gnutls_priority_t priority_cache;
#endif
};
static struct common_config common_config;
struct body_parser body_parser;
static struct config config[MAX_DOMAINS_NUMBER];
static char host_buf[1024];
enum nxweb_chunked_decoder_state_code {CDS_CR1 = -2, CDS_LF1 = -1, CDS_SIZE = 0, CDS_LF2, CDS_DATA};
typedef struct nxweb_chunked_decoder_state {
enum nxweb_chunked_decoder_state_code state;
unsigned short final_chunk:1;
unsigned short monitor_only:1;
int64_t chunk_bytes_left;
} nxweb_chunked_decoder_state;
enum connection_state {C_CONNECTING, C_HANDSHAKING, C_WRITING, C_READING_HEADERS, C_READING_BODY, C_THROTTLED};
typedef struct connection {
struct cd_list throttled_list;
struct ev_loop* loop;
struct thread_config* tdata;
int fd;
int idx; //domain index in case of multiple domains
int socket_id; // global socket ID
ev_io watch_read;
ev_io watch_write;
ev_timer watch_resume_write;
ev_tstamp last_activity;
ev_tstamp tstamp_request_sent;
ev_tstamp tstamp_response_first_byte;
nxweb_chunked_decoder_state cdstate;
#ifdef WITH_SSL
gnutls_session_t session;
#endif
int write_pos;
int read_pos;
int bytes_to_read;
int bytes_received;
int alive_count;
struct req_stats stats;
int keep_alive:1;
int chunked:1;
int done:1;
int secure:1;
int in_use:1;
int yield:1;
int status_code;
char buf[32768];
int cookie_len;
char* cookies;
char* body_ptr;
enum connection_state state;
ev_tstamp start_time;
} connection;
typedef struct thread_config {
pthread_t tid;
connection *conns;
struct cd_list throttled_conns;
int id;
int num_conn;
int reqs_in_flight;
struct ev_loop* loop;
ev_tstamp start_time;
ev_timer watch_heartbeat;
int shutdown_in_progress;
struct req_stats stats;
ev_tstamp avg_req_time;
long long request_counter;
#ifdef WITH_SSL
_Bool ssl_identified;
_Bool ssl_dhe;
_Bool ssl_ecdh;
gnutls_kx_algorithm_t ssl_kx;
gnutls_credentials_type_t ssl_cred;
int ssl_dh_prime_bits;
# ifdef GNUTLS3
gnutls_ecc_curve_t ssl_ecc_curve;
# endif
gnutls_protocol_t ssl_protocol;
gnutls_certificate_type_t ssl_cert_type;
gnutls_x509_crt_t ssl_cert;
gnutls_compression_method_t ssl_compression;
gnutls_cipher_algorithm_t ssl_cipher;
gnutls_mac_algorithm_t ssl_mac;
#endif
} thread_config;
#define CLASS_NUM 5
struct stat_class {
int begin;
int end;
atomic_t *counter;
};
struct stat_codes {
struct stat_class codes[CLASS_NUM];
atomic_t counter;
atomic_t out_of_class;
};
static struct stat_codes stat_codes;
/****************************************************************************************
* Logging
****************************************************************************************/
void nxweb_die(const char* fmt, ...)
{
va_list ap;
fprintf(stderr, "FATAL: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
exit(EXIT_FAILURE);
}
static inline const char* get_current_time(char* buf, int max_buf_size)
{
time_t t;
struct tm tm;
time(&t);
localtime_r(&t, &tm);
strftime(buf, max_buf_size, "%T", &tm); // %T=%H:%M:%S
return buf;
}
void nxweb_log_error(connection *conn, const char* fmt, ...)
{
char cur_time[32];
va_list ap;
int socket_id = 0;
int conn_tdata_id = (conn == NULL) ? 0 : (conn->tdata->id - 1);
if (conn)
socket_id = conn->socket_id;
get_current_time(cur_time, sizeof(cur_time));
flockfile(stderr);
fprintf(stderr, "%s %s [%2d:%2u] ", cur_time, "ERROR", conn_tdata_id, socket_id);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
fflush(stderr);
funlockfile(stderr);
}
void nxweb_dbg(int level, connection *conn, const char *fmt, ...)
{
static const char* level_str[] = {"", " INFO", "DEBUG", "BODY", NULL};
char cur_time[32];
va_list ap;
char buf[1024];
int n = 0;
int socket_id = 0;
if (level > DBG_MAX)
return;
if (level > common_config.debug_level)
return;
if (conn)
socket_id = conn->socket_id;
get_current_time(cur_time, sizeof(cur_time));
n += snprintf(buf, sizeof(buf) - n, "%s %s [%2d:%2u] ",
cur_time, level_str[level], conn->tdata->id - 1, socket_id);
va_start(ap, fmt);
n += vsnprintf(buf + n, sizeof(buf) - n, fmt, ap);
va_end(ap);
fprintf(stdout, "%s", buf);
}
/****************************************************************************************
* Percentile calculation
****************************************************************************************/
#define P_UPPER_BOUND 10 // in seconds
#define P_RANGE 100000 // discretization between 0 and P_UPPER_BOUND
atomic_t percentile[P_RANGE+1];
/* register a request time in storage for percentile calculation */
static void reg_percentile_val(double val)
{
double range = P_RANGE;
double step = P_UPPER_BOUND / range;
int idx = val / step;
if (idx > P_RANGE)
idx = P_RANGE;
atomic_inc(&percentile[idx]);
}
/* returns a total number of requests registered in precentile */
static atomic_val_t get_num_registered()
{
atomic_val_t num = 0;
for (int i = 0; i <= P_RANGE; i++)
num += atomic_get(&percentile[i]);
return num;
}
/* returns percentile value in seconds */
static double get_percentile(int p) // p - %
{
if (!(p > 0 && p < 100))
nxweb_die("Percentile value should be between 1 and 99");
atomic_val_t val_num = get_num_registered();
double th = val_num * (100 - p) / 100.0;
atomic_val_t threshold = (atomic_val_t) (th - (atomic_val_t) th >= 0.5) ? th + 1 : th;
int idx = P_RANGE;
while(idx > 0) {
threshold -= atomic_get(&percentile[idx]);
if (threshold <= 0)
break;
idx--;
}
return idx * P_UPPER_BOUND / (double) P_RANGE;
}
/****************************************************************************************
* HTTP-level callbacks
****************************************************************************************/
static void unthrottle(connection *conn, thread_config *tdata);
/* Called when first byte of response received */
static void http_response_first_byte(connection *conn)
{
nxweb_dbg(DBG_DEBUG, conn, "%2d ... rcv %3d %-20s HTTP header received, CL: %d%s\n",
atomic_get(&reqs_in_flight),
conn->status_code,
config[conn->idx].url,
conn->bytes_to_read, conn->keep_alive ? ", KA" : "");
conn->tstamp_response_first_byte = conn->last_activity;
reg_percentile_val(conn->tstamp_response_first_byte - conn->tstamp_request_sent);
}
/* Called when last byte of response received */
static void http_response_last_byte(connection *conn)
{
unthrottle(conn, conn->tdata);
nxweb_dbg(DBG_INFO, conn, "%2d --- rcv %3d %-20s TTFB: %.3f, TTLB: %.3f, CL: %d%s\n",
atomic_get(&reqs_in_flight),
conn->status_code,
config[conn->idx].url,
conn->tstamp_response_first_byte - conn->tstamp_request_sent,
conn->last_activity - conn->tstamp_request_sent,
conn->bytes_to_read,
conn->keep_alive ? ", KA" : "");
}
/* Called before sending new request to the server */
static void http_before_request_send(struct ev_loop *loop, connection *conn)
{
}
/* Called after sending new request to the server */
static void http_after_request_send(struct ev_loop *loop, connection *conn)
{
nxweb_dbg(DBG_INFO, conn, "%2d +++ snd GET %-20s\n",
atomic_get(&reqs_in_flight),
config[conn->idx].url);
conn->tstamp_request_sent = ev_now(loop);
}
static inline int conn_get(connection *conn)
{
int in_flight;
if (conn->yield) {
conn->yield = 0;
return -1;
}
if (conn->tdata->reqs_in_flight == common_config.thread_concurrency_limit)
return -1;
conn->tdata->reqs_in_flight++;
atomic_inc(&reqs_in_flight);
in_flight = atomic_get(&reqs_in_flight);
if (in_flight > concurrency_max)
concurrency_max = in_flight;
atomic_add(&concurrency_sum, in_flight);
conn->in_use = 1;
nxweb_dbg(DBG_DEBUG, conn, "%d conn_get\n", in_flight);
return 0;
}
static inline void conn_put(connection *conn, int good)
{
if (!conn->in_use)
return;
conn->tdata->reqs_in_flight--;
atomic_dec(&reqs_in_flight);
conn->in_use = 0;
nxweb_dbg(DBG_DEBUG, conn, "%d conn_put: state %d\n", atomic_get(&reqs_in_flight), conn->state);
if (good) {
switch(conn->state) {
case C_READING_HEADERS:
case C_READING_BODY:
http_response_last_byte(conn);
default:
;
}
}
}
/* Say libev that we are ready to handle read or write (i.e. *wr*) */
static void conn_io_start(connection *conn, int wr)
{
nxweb_dbg(DBG_DEBUG, conn, "start watching %s\n", (wr == EV_WRITE) ? "WRITEs" : "READs");
ev_io_start(conn->loop, (wr == EV_WRITE) ? &conn->watch_write : &conn->watch_read);
}
/* Say libev that we are not ready to handle read or write (i.e. *wr*) */
static void conn_io_stop(connection *conn, int wr)
{
nxweb_dbg(DBG_DEBUG, conn, "stop watching %s\n", (wr == EV_WRITE) ? "WRITEs" : "READs");
ev_io_stop(conn->loop, (wr == EV_WRITE) ? &conn->watch_write : &conn->watch_read);
}
static void start_write(connection* conn)
{
conn_io_start(conn, EV_WRITE);
ev_feed_event(conn->loop, &conn->watch_write, EV_WRITE);
}
static void resume_write_cb(struct ev_loop *loop, ev_timer *w, int revents);
static void resume_write(connection* conn)
{
if(common_config.sleep_time) {
struct req_stats* stats = &conn->stats;
int request_num = atomic_get(&stats->num_success) + atomic_get(&stats->num_fail);
double sched_time = (request_num + 1) * common_config.sleep_time;
ev_tstamp now_ts = ev_time();
double sleep_time = sched_time - (now_ts - conn->start_time);
if (sleep_time > 0) {
// start writing in sleep seconds
ev_timer_init(&conn->watch_resume_write, resume_write_cb, sleep_time, 0);
ev_timer_start(conn->tdata->loop, &conn->watch_resume_write);
}
else
start_write(conn);
}
else
start_write(conn);
}
static void conn_throttle(connection *conn)
{
cd_list_add(&conn->throttled_list, &conn->tdata->throttled_conns);
conn->state = C_THROTTLED;
nxweb_dbg(DBG_DEBUG, conn, "connection throttled!\n");
conn_io_stop(conn, EV_WRITE);
/*
* FIXME: remove me!?
*
* if (!ev_is_active(&conn->watch_read))
* conn_io_start(conn, EV_READ);
* ev_feed_event(conn->loop, &conn->watch_read, EV_READ);
*/
}
static void conn_unthrottle(connection *conn)
{
cd_list_del(&conn->throttled_list);
conn->state = C_WRITING;
nxweb_dbg(DBG_DEBUG, conn, "connection unthrottled!\n");
conn->write_pos = 0;
resume_write(conn);
}
/* Find throttled connectionss and unthrottle them */
static void unthrottle(connection *conn, thread_config *tdata)
{
connection *c;
if (cd_list_empty(&tdata->throttled_conns))
return;
c = cd_list_first_entry(&tdata->throttled_conns, connection, throttled_list);
assert(c);
assert(c->state == C_THROTTLED);
if (conn)
conn->yield = 1; // be fair and let others work
conn_unthrottle(c);
}
/****************************************************************************************
* Connection stats
****************************************************************************************/
static inline void inc_http_status(connection* conn)
{
int code = conn->status_code;
int cl = code / 100;
atomic_inc(&stat_codes.counter);
if (cl > CLASS_NUM || cl < 1 || stat_codes.codes[cl - 1].end < code) {
nxweb_dbg(DBG_DEBUG, conn, "unknown status code %3d\n", code);
atomic_inc(&stat_codes.out_of_class);
return;
}
atomic_inc(stat_codes.codes[cl - 1].counter + code % 100);
}
static inline void inc_success(connection* conn)
{
conn_put(conn, 1);
switch (conn->status_code) {
case 200: /* OK */
case 201: /* Created */
case 202: /* Accepted */
/*
* Important.
*
* Only these 3 codes are treated as success for performance testing.
* Others are not ok, for instance:
*
* 204 (No Content) - it is not OK, because we are expecting data
*
* 206 (Partial content) - it is not OK, because it means we will
* have different number of sent and recieved packets
*/
STATS_INC(conn, num_2xx);
}
STATS_INC(conn, num_success);
STATS_ADD(conn, num_bytes_received, conn->bytes_received);
STATS_ADD(conn, num_overhead_received, (conn->body_ptr - conn->buf));
inc_http_status(conn);
}
static inline void inc_fail(connection* conn)
{
STATS_INC(conn, num_fail);
}
static inline void inc_connect(connection* conn)
{
STATS_INC(conn, num_connect);
}
enum {ERR_AGAIN = -2, ERR_ERROR = -1, ERR_RDCLOSED = -3};
/****************************************************************************************
* Socket and connection management
****************************************************************************************/
static void process_http_chunk(connection *conn, const char *buf, size_t len);
static inline ssize_t conn_read(connection* conn, void* buf, size_t size)
{
#ifdef WITH_SSL
if (conn->secure) {
ssize_t ret;
ret = gnutls_record_recv(conn->session, buf, size);
if (ret > 0) {
process_http_chunk(conn, buf, size);
return ret;
}
if (ret == GNUTLS_E_AGAIN)
return ERR_AGAIN;
if (ret == 0)
return ERR_RDCLOSED;
return ERR_ERROR;
}
else
#endif
{
ssize_t ret;
ret = read(conn->fd, buf, size);
if (ret > 0) {
process_http_chunk(conn, buf, size);
return ret;
}
if (ret == 0)
return ERR_RDCLOSED;
if (errno == EAGAIN)
return ERR_AGAIN;
return ERR_ERROR;
}
}
static inline ssize_t conn_write(connection* conn, const void* buf, size_t size)
{
#ifdef WITH_SSL
if (conn->secure) {
ssize_t ret;
ret = gnutls_record_send(conn->session, buf, size);
if (ret >= 0)
return ret;
if (ret == GNUTLS_E_AGAIN)
return ERR_AGAIN;
return ERR_ERROR;
}
else
#endif
{
ssize_t ret;
ret = write(conn->fd, buf, size);
if (ret >= 0)
return ret;
if (errno == EAGAIN)
return ERR_AGAIN;
return ERR_ERROR;
}
}
static inline void _nxweb_close_good_socket(int fd)
{
// struct linger linger;
// linger.l_onoff = 0; // gracefully shutdown connection
// linger.l_linger = 0;
// setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
// shutdown(fd, SHUT_RDWR);
close(fd);
}
static inline void _nxweb_close_bad_socket(int fd)
{
struct linger linger;
linger.l_onoff = 1;
linger.l_linger = 0; // timeout for completing writes
setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
close(fd);
}
static inline void conn_close(connection* conn, int good)
{
conn_put(conn, good);
#ifdef WITH_SSL
if (conn->secure)
gnutls_deinit(conn->session);
#endif
if (good)
_nxweb_close_good_socket(conn->fd);
else
_nxweb_close_bad_socket(conn->fd);
}
static inline int setup_socket(int fd)
{
int flags = fcntl(fd, F_GETFL);
if (flags < 0)
return flags;
if (fcntl(fd, F_SETFL, flags |= O_NONBLOCK) < 0)
return -1;
int nodelay = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)))
return -1;
// struct linger linger;
// linger.l_onoff = 1;
// linger.l_linger = 10; // timeout for completing reads/writes
// setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
return 0;
}
static int more_requests_to_run()
{
int rc = __sync_add_and_fetch(&common_config.request_counter, 1);
if ((common_config.press_mode == PM_NUMBER && rc > common_config.num_requests) ||
(common_config.press_mode == PM_TIME && common_config.need_to_stop)) {
return 0;
}
if (!common_config.quiet && common_config.progress_step >= 10 &&
(rc % common_config.progress_step == 0 || rc == common_config.num_requests)) {
printf("%d requests launched\n", rc);
}
return 1;
}
static void reset_body_parser();
static int open_socket(connection* conn)
{
if (ev_is_active(&conn->watch_write))
conn_io_stop(conn, EV_WRITE);
if (ev_is_active(&conn->watch_read))
conn_io_stop(conn, EV_READ);
if (!more_requests_to_run(conn)) {
conn->done = 1;
ev_feed_event(conn->tdata->loop, &conn->tdata->watch_heartbeat, EV_TIMER);
return 1;
}
inc_connect(conn);
nxweb_dbg(DBG_DEBUG, conn, "open socket to '%s'\n", config[conn->idx].uri_host);
conn->fd = socket(config[conn->idx].saddr->ai_family, config[conn->idx].saddr->ai_socktype,
config[conn->idx].saddr->ai_protocol);
if (conn->fd == -1) {
fprintf(stderr, "%s", strerror_r(errno, conn->buf, sizeof(conn->buf)));
nxweb_log_error(conn, "can't open socket [%d] %s", errno, conn->buf);
return -1;
}
if (setup_socket(conn->fd)) {
nxweb_log_error(conn, "can't setup socket");
return -1;
}
if (connect(conn->fd, config[conn->idx].saddr->ai_addr, config[conn->idx].saddr->ai_addrlen)) {
if (errno != EINPROGRESS && errno != EALREADY && errno != EISCONN) {
nxweb_log_error(conn, "can't connect %d", errno);
return -1;
}
}
#ifdef WITH_SSL
if (config[conn->idx].secure) {
gnutls_init(&conn->session, GNUTLS_CLIENT);
gnutls_server_name_set(conn->session, GNUTLS_NAME_DNS, config[conn->idx].uri_host,
strlen(config[conn->idx].uri_host));
gnutls_priority_set(conn->session, config[conn->idx].priority_cache);
gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, config[conn->idx].ssl_cred);
gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr_t)(int_to_ptr)conn->fd);
}
#endif // WITH_SSL
conn->state = C_CONNECTING;
conn->write_pos = 0;
conn->alive_count = 0;
conn->done = 0;
if (body_parser.enabled)
reset_body_parser();
ev_io_set(&conn->watch_write, conn->fd, EV_WRITE);
ev_io_set(&conn->watch_read, conn->fd, EV_READ);
resume_write(conn);
return 0;
}
static void rearm_socket(connection* conn)
{
if (ev_is_active(&conn->watch_write))
conn_io_stop(conn, EV_WRITE);
if (ev_is_active(&conn->watch_read))
conn_io_stop(conn, EV_READ);
if (body_parser.enabled && !body_parser.found) {
inc_fail(conn);
nxweb_log_error(conn, "regular expression is not found");
}
else {
inc_success(conn);
}