2 * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "../util-internal.h"
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 # ifdef _XOPEN_SOURCE_EXTENDED
41 # include <arpa/inet.h>
46 #include "event2/bufferevent.h"
47 #include "event2/buffer.h"
48 #include "event2/event.h"
49 #include "event2/util.h"
50 #include "event2/listener.h"
51 #include "event2/thread.h"
53 static struct evutil_weakrand_state weakrand_state;
55 static int cfg_verbose = 0;
56 static int cfg_help = 0;
58 static int cfg_n_connections = 30;
59 static int cfg_duration = 5;
60 static int cfg_connlimit = 0;
61 static int cfg_grouplimit = 0;
62 static int cfg_tick_msec = 1000;
63 static int cfg_min_share = -1;
64 static int cfg_group_drain = 0;
66 static int cfg_connlimit_tolerance = -1;
67 static int cfg_grouplimit_tolerance = -1;
68 static int cfg_stddev_tolerance = -1;
71 static int cfg_enable_iocp = 0;
74 static struct timeval cfg_tick = { 0, 500*1000 };
76 static struct ev_token_bucket_cfg *conn_bucket_cfg = NULL;
77 static struct ev_token_bucket_cfg *group_bucket_cfg = NULL;
78 struct bufferevent_rate_limit_group *ratelim_group = NULL;
79 static double seconds_per_tick = 0.0;
86 static const struct timeval *ms100_common=NULL;
88 /* info from check_bucket_levels_cb */
89 static int total_n_bev_checks = 0;
90 static ev_int64_t total_rbucket_level=0;
91 static ev_int64_t total_wbucket_level=0;
92 static ev_int64_t total_max_to_read=0;
93 static ev_int64_t total_max_to_write=0;
94 static ev_int64_t max_bucket_level=EV_INT64_MIN;
95 static ev_int64_t min_bucket_level=EV_INT64_MAX;
97 /* from check_group_bucket_levels_cb */
98 static int total_n_group_bev_checks = 0;
99 static ev_int64_t total_group_rbucket_level = 0;
100 static ev_int64_t total_group_wbucket_level = 0;
102 static int n_echo_conns_open = 0;
104 /* Info on the open connections */
105 struct bufferevent **bevs;
106 struct client_state *states;
107 struct bufferevent_rate_limit_group *group = NULL;
109 static void check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg);
112 loud_writecb(struct bufferevent *bev, void *ctx)
114 struct client_state *cs = ctx;
115 struct evbuffer *output = bufferevent_get_output(bev);
117 int r = evutil_weakrand_(&weakrand_state);
118 memset(buf, r, sizeof(buf));
119 while (evbuffer_get_length(output) < 8192) {
120 evbuffer_add(output, buf, sizeof(buf));
121 cs->queued += sizeof(buf);
126 discard_readcb(struct bufferevent *bev, void *ctx)
128 struct client_state *cs = ctx;
129 struct evbuffer *input = bufferevent_get_input(bev);
130 size_t len = evbuffer_get_length(input);
131 evbuffer_drain(input, len);
136 write_on_connectedcb(struct bufferevent *bev, short what, void *ctx)
138 if (what & BEV_EVENT_CONNECTED) {
139 loud_writecb(bev, ctx);
140 /* XXXX this shouldn't be needed. */
141 bufferevent_enable(bev, EV_READ|EV_WRITE);
146 echo_readcb(struct bufferevent *bev, void *ctx)
148 struct evbuffer *input = bufferevent_get_input(bev);
149 struct evbuffer *output = bufferevent_get_output(bev);
151 evbuffer_add_buffer(output, input);
152 if (evbuffer_get_length(output) > 1024000)
153 bufferevent_disable(bev, EV_READ);
157 echo_writecb(struct bufferevent *bev, void *ctx)
159 struct evbuffer *output = bufferevent_get_output(bev);
160 if (evbuffer_get_length(output) < 512000)
161 bufferevent_enable(bev, EV_READ);
165 echo_eventcb(struct bufferevent *bev, short what, void *ctx)
167 if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
169 bufferevent_free(bev);
174 echo_listenercb(struct evconnlistener *listener, evutil_socket_t newsock,
175 struct sockaddr *sourceaddr, int socklen, void *ctx)
177 struct event_base *base = ctx;
178 int flags = BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE;
179 struct bufferevent *bev;
181 bev = bufferevent_socket_new(base, newsock, flags);
182 bufferevent_setcb(bev, echo_readcb, echo_writecb, echo_eventcb, NULL);
183 if (conn_bucket_cfg) {
184 struct event *check_event =
185 event_new(base, -1, EV_PERSIST, check_bucket_levels_cb, bev);
186 bufferevent_set_rate_limit(bev, conn_bucket_cfg);
188 assert(bufferevent_get_token_bucket_cfg(bev) != NULL);
189 event_add(check_event, ms100_common);
192 bufferevent_add_to_rate_limit_group(bev, ratelim_group);
194 bufferevent_enable(bev, EV_READ|EV_WRITE);
197 /* Called periodically to check up on how full the buckets are */
199 check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
201 struct bufferevent *bev = arg;
203 ev_ssize_t r = bufferevent_get_read_limit(bev);
204 ev_ssize_t w = bufferevent_get_write_limit(bev);
205 ev_ssize_t rm = bufferevent_get_max_to_read(bev);
206 ev_ssize_t wm = bufferevent_get_max_to_write(bev);
207 /* XXXX check that no value is above the cofigured burst
209 total_rbucket_level += r;
210 total_wbucket_level += w;
211 total_max_to_read += rm;
212 total_max_to_write += wm;
214 if ((x) > max_bucket_level) \
215 max_bucket_level = (x); \
216 if ((x) < min_bucket_level) \
217 min_bucket_level = (x)
222 total_n_bev_checks++;
223 if (total_n_bev_checks >= .8 * ((double)cfg_duration / cfg_tick_msec) * cfg_n_connections) {
224 event_free(event_base_get_running_event(bufferevent_get_base(bev)));
229 check_group_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
232 ev_ssize_t r = bufferevent_rate_limit_group_get_read_limit(ratelim_group);
233 ev_ssize_t w = bufferevent_rate_limit_group_get_write_limit(ratelim_group);
234 total_group_rbucket_level += r;
235 total_group_wbucket_level += w;
237 ++total_n_group_bev_checks;
241 group_drain_cb(evutil_socket_t fd, short events, void *arg)
243 bufferevent_rate_limit_group_decrement_read(ratelim_group, cfg_group_drain);
244 bufferevent_rate_limit_group_decrement_write(ratelim_group, cfg_group_drain);
248 test_ratelimiting(void)
250 struct event_base *base;
251 struct sockaddr_in sin;
252 struct evconnlistener *listener;
254 struct sockaddr_storage ss;
261 ev_uint64_t total_received;
262 double total_sq_persec, total_persec;
264 double expected_total_persec = -1.0, expected_avg_persec = -1.0;
266 struct event_config *base_cfg;
267 struct event *periodic_level_check;
268 struct event *group_drain_event=NULL;
270 memset(&sin, 0, sizeof(sin));
271 sin.sin_family = AF_INET;
272 sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
273 sin.sin_port = 0; /* unspecified port */
276 event_enable_debug_mode();
278 base_cfg = event_config_new();
281 if (cfg_enable_iocp) {
282 evthread_use_windows_threads();
283 event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
287 base = event_base_new_with_config(base_cfg);
288 event_config_free(base_cfg);
290 fprintf(stderr, "Couldn't create event_base");
294 listener = evconnlistener_new_bind(base, echo_listenercb, base,
295 LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
296 (struct sockaddr *)&sin, sizeof(sin));
298 fprintf(stderr, "Couldn't create listener");
303 if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
305 perror("getsockname");
309 if (cfg_connlimit > 0) {
310 conn_bucket_cfg = ev_token_bucket_cfg_new(
311 cfg_connlimit, cfg_connlimit * 4,
312 cfg_connlimit, cfg_connlimit * 4,
314 assert(conn_bucket_cfg);
317 if (cfg_grouplimit > 0) {
318 group_bucket_cfg = ev_token_bucket_cfg_new(
319 cfg_grouplimit, cfg_grouplimit * 4,
320 cfg_grouplimit, cfg_grouplimit * 4,
322 group = ratelim_group = bufferevent_rate_limit_group_new(
323 base, group_bucket_cfg);
324 expected_total_persec = cfg_grouplimit - (cfg_group_drain / seconds_per_tick);
325 expected_avg_persec = cfg_grouplimit / cfg_n_connections;
326 if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
327 expected_avg_persec = cfg_connlimit;
328 if (cfg_min_share >= 0)
329 bufferevent_rate_limit_group_set_min_share(
330 ratelim_group, cfg_min_share);
333 if (expected_avg_persec < 0 && cfg_connlimit > 0)
334 expected_avg_persec = cfg_connlimit;
336 if (expected_avg_persec > 0)
337 expected_avg_persec /= seconds_per_tick;
338 if (expected_total_persec > 0)
339 expected_total_persec /= seconds_per_tick;
341 bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
342 states = calloc(cfg_n_connections, sizeof(struct client_state));
344 for (i = 0; i < cfg_n_connections; ++i) {
345 bevs[i] = bufferevent_socket_new(base, -1,
346 BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
348 bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
349 write_on_connectedcb, &states[i]);
350 bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
351 bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
355 tv.tv_sec = cfg_duration - 1;
358 event_base_loopexit(base, &tv);
361 tv.tv_usec = 100*1000;
362 ms100_common = event_base_init_common_timeout(base, &tv);
364 periodic_level_check = event_new(base, -1, EV_PERSIST, check_group_bucket_levels_cb, NULL);
365 event_add(periodic_level_check, ms100_common);
367 if (cfg_group_drain && ratelim_group) {
368 group_drain_event = event_new(base, -1, EV_PERSIST, group_drain_cb, NULL);
369 event_add(group_drain_event, &cfg_tick);
372 event_base_dispatch(base);
374 ratelim_group = NULL; /* So no more responders get added */
375 event_free(periodic_level_check);
376 if (group_drain_event)
377 event_del(group_drain_event);
379 for (i = 0; i < cfg_n_connections; ++i) {
380 bufferevent_free(bevs[i]);
382 evconnlistener_free(listener);
384 /* Make sure no new echo_conns get added to the group. */
385 ratelim_group = NULL;
387 /* This should get _everybody_ freed */
388 while (n_echo_conns_open) {
389 printf("waiting for %d conns\n", n_echo_conns_open);
392 event_base_loopexit(base, &tv);
393 event_base_dispatch(base);
397 bufferevent_rate_limit_group_free(group);
399 if (total_n_bev_checks) {
400 printf("Average read bucket level: %f\n",
401 (double)total_rbucket_level/total_n_bev_checks);
402 printf("Average write bucket level: %f\n",
403 (double)total_wbucket_level/total_n_bev_checks);
404 printf("Highest read bucket level: %f\n",
405 (double)max_bucket_level);
406 printf("Highest write bucket level: %f\n",
407 (double)min_bucket_level);
408 printf("Average max-to-read: %f\n",
409 ((double)total_max_to_read)/total_n_bev_checks);
410 printf("Average max-to-write: %f\n",
411 ((double)total_max_to_write)/total_n_bev_checks);
413 if (total_n_group_bev_checks) {
414 printf("Average group read bucket level: %f\n",
415 ((double)total_group_rbucket_level)/total_n_group_bev_checks);
416 printf("Average group write bucket level: %f\n",
417 ((double)total_group_wbucket_level)/total_n_group_bev_checks);
422 total_sq_persec = 0.0;
423 for (i=0; i < cfg_n_connections; ++i) {
424 double persec = states[i].received;
425 persec /= cfg_duration;
426 total_received += states[i].received;
427 total_persec += persec;
428 total_sq_persec += persec*persec;
429 printf("%d: %f per second\n", i+1, persec);
431 printf(" total: %f per second\n",
432 ((double)total_received)/cfg_duration);
433 if (expected_total_persec > 0) {
434 double diff = expected_total_persec -
435 ((double)total_received/cfg_duration);
436 printf(" [Off by %lf]\n", diff);
437 if (cfg_grouplimit_tolerance > 0 &&
438 fabs(diff) > cfg_grouplimit_tolerance) {
439 fprintf(stderr, "Group bandwidth out of bounds\n");
444 printf(" average: %f per second\n",
445 (((double)total_received)/cfg_duration)/cfg_n_connections);
446 if (expected_avg_persec > 0) {
447 double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
448 printf(" [Off by %lf]\n", diff);
449 if (cfg_connlimit_tolerance > 0 &&
450 fabs(diff) > cfg_connlimit_tolerance) {
451 fprintf(stderr, "Connection bandwidth out of bounds\n");
456 variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);
458 printf(" stddev: %f per second\n", sqrt(variance));
459 if (cfg_stddev_tolerance > 0 &&
460 sqrt(variance) > cfg_stddev_tolerance) {
461 fprintf(stderr, "Connection variance out of bounds\n");
465 event_base_free(base);
472 static struct option {
473 const char *name; int *ptr; int min; int isbool;
475 { "-v", &cfg_verbose, 0, 1 },
476 { "-h", &cfg_help, 0, 1 },
477 { "-n", &cfg_n_connections, 1, 0 },
478 { "-d", &cfg_duration, 1, 0 },
479 { "-c", &cfg_connlimit, 0, 0 },
480 { "-g", &cfg_grouplimit, 0, 0 },
481 { "-G", &cfg_group_drain, -100000, 0 },
482 { "-t", &cfg_tick_msec, 10, 0 },
483 { "--min-share", &cfg_min_share, 0, 0 },
484 { "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
485 { "--check-grouplimit", &cfg_grouplimit_tolerance, 0, 0 },
486 { "--check-stddev", &cfg_stddev_tolerance, 0, 0 },
488 { "--iocp", &cfg_enable_iocp, 0, 1 },
490 { NULL, NULL, -1, 0 },
494 handle_option(int argc, char **argv, int *i, const struct option *opt)
502 if (*i + 1 == argc) {
503 fprintf(stderr, "Too few arguments to '%s'\n",argv[*i]);
506 val = strtol(argv[*i+1], &endptr, 10);
507 if (*argv[*i+1] == '\0' || !endptr || *endptr != '\0') {
508 fprintf(stderr, "Couldn't parse numeric value '%s'\n",
512 if (val < opt->min || val > 0x7fffffff) {
513 fprintf(stderr, "Value '%s' is out-of-range'\n",
517 *opt->ptr = (int)val;
526 "test-ratelim [-v] [-n INT] [-d INT] [-c INT] [-g INT] [-t INT]\n\n"
527 "Pushes bytes through a number of possibly rate-limited connections, and\n"
528 "displays average throughput.\n\n"
529 " -n INT: Number of connections to open (default: 30)\n"
530 " -d INT: Duration of the test in seconds (default: 5 sec)\n");
532 " -c INT: Connection-rate limit applied to each connection in bytes per second\n"
533 " (default: None.)\n"
534 " -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
535 " (default: None.)\n"
536 " -G INT: drain INT bytes from the group limit every tick. (default: 0)\n"
537 " -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
541 main(int argc, char **argv)
547 WORD wVersionRequested = MAKEWORD(2,2);
550 (void) WSAStartup(wVersionRequested, &wsaData);
553 evutil_weakrand_seed_(&weakrand_state, 0);
556 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
559 for (i = 1; i < argc; ++i) {
560 for (j = 0; options[j].name; ++j) {
561 if (!strcmp(argv[i],options[j].name)) {
562 if (handle_option(argc,argv,&i,&options[j])<0)
567 fprintf(stderr, "Unknown option '%s'\n", argv[i]);
578 cfg_tick.tv_sec = cfg_tick_msec / 1000;
579 cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000;
581 seconds_per_tick = ratio = cfg_tick_msec / 1000.0;
583 cfg_connlimit *= ratio;
584 cfg_grouplimit *= ratio;
588 evutil_gettimeofday(&tv, NULL);
596 #ifndef EVENT__DISABLE_THREAD_SUPPORT
597 evthread_enable_lock_debugging();
600 return test_ratelimiting();