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.
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 # ifdef _XOPEN_SOURCE_EXTENDED
40 # include <arpa/inet.h>
45 #include "event2/bufferevent.h"
46 #include "event2/buffer.h"
47 #include "event2/event.h"
48 #include "event2/util.h"
49 #include "event2/listener.h"
50 #include "event2/thread.h"
52 #include "../util-internal.h"
54 static int cfg_verbose = 0;
55 static int cfg_help = 0;
57 static int cfg_n_connections = 30;
58 static int cfg_duration = 5;
59 static int cfg_connlimit = 0;
60 static int cfg_grouplimit = 0;
61 static int cfg_tick_msec = 1000;
62 static int cfg_min_share = -1;
64 static int cfg_connlimit_tolerance = -1;
65 static int cfg_grouplimit_tolerance = -1;
66 static int cfg_stddev_tolerance = -1;
69 static int cfg_enable_iocp = 0;
72 static struct timeval cfg_tick = { 0, 500*1000 };
74 static struct ev_token_bucket_cfg *conn_bucket_cfg = NULL;
75 static struct ev_token_bucket_cfg *group_bucket_cfg = NULL;
76 struct bufferevent_rate_limit_group *ratelim_group = NULL;
77 static double seconds_per_tick = 0.0;
84 static int n_echo_conns_open = 0;
87 loud_writecb(struct bufferevent *bev, void *ctx)
89 struct client_state *cs = ctx;
90 struct evbuffer *output = bufferevent_get_output(bev);
95 int r = random() % 256;
97 memset(buf, r, sizeof(buf));
98 while (evbuffer_get_length(output) < 8192) {
99 evbuffer_add(output, buf, sizeof(buf));
100 cs->queued += sizeof(buf);
105 discard_readcb(struct bufferevent *bev, void *ctx)
107 struct client_state *cs = ctx;
108 struct evbuffer *input = bufferevent_get_input(bev);
109 size_t len = evbuffer_get_length(input);
110 evbuffer_drain(input, len);
115 write_on_connectedcb(struct bufferevent *bev, short what, void *ctx)
117 if (what & BEV_EVENT_CONNECTED) {
118 loud_writecb(bev, ctx);
119 /* XXXX this shouldn't be needed. */
120 bufferevent_enable(bev, EV_READ|EV_WRITE);
125 echo_readcb(struct bufferevent *bev, void *ctx)
127 struct evbuffer *input = bufferevent_get_input(bev);
128 struct evbuffer *output = bufferevent_get_output(bev);
130 evbuffer_add_buffer(output, input);
131 if (evbuffer_get_length(output) > 1024000)
132 bufferevent_disable(bev, EV_READ);
136 echo_writecb(struct bufferevent *bev, void *ctx)
138 struct evbuffer *output = bufferevent_get_output(bev);
139 if (evbuffer_get_length(output) < 512000)
140 bufferevent_enable(bev, EV_READ);
144 echo_eventcb(struct bufferevent *bev, short what, void *ctx)
146 if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
148 bufferevent_free(bev);
153 echo_listenercb(struct evconnlistener *listener, evutil_socket_t newsock,
154 struct sockaddr *sourceaddr, int socklen, void *ctx)
156 struct event_base *base = ctx;
157 int flags = BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE;
158 struct bufferevent *bev;
160 bev = bufferevent_socket_new(base, newsock, flags);
161 bufferevent_setcb(bev, echo_readcb, echo_writecb, echo_eventcb, NULL);
163 bufferevent_set_rate_limit(bev, conn_bucket_cfg);
165 bufferevent_add_to_rate_limit_group(bev, ratelim_group);
167 bufferevent_enable(bev, EV_READ|EV_WRITE);
171 test_ratelimiting(void)
173 struct event_base *base;
174 struct sockaddr_in sin;
175 struct evconnlistener *listener;
177 struct sockaddr_storage ss;
180 struct bufferevent **bevs;
181 struct client_state *states;
182 struct bufferevent_rate_limit_group *group = NULL;
188 ev_uint64_t total_received;
189 double total_sq_persec, total_persec;
191 double expected_total_persec = -1.0, expected_avg_persec = -1.0;
193 struct event_config *base_cfg;
195 memset(&sin, 0, sizeof(sin));
196 sin.sin_family = AF_INET;
197 sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
198 sin.sin_port = 0; /* unspecified port */
201 event_enable_debug_mode();
203 base_cfg = event_config_new();
206 if (cfg_enable_iocp) {
207 evthread_use_windows_threads();
208 event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
212 base = event_base_new_with_config(base_cfg);
214 listener = evconnlistener_new_bind(base, echo_listenercb, base,
215 LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
216 (struct sockaddr *)&sin, sizeof(sin));
219 if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
221 perror("getsockname");
225 if (cfg_connlimit > 0) {
226 conn_bucket_cfg = ev_token_bucket_cfg_new(
227 cfg_connlimit, cfg_connlimit * 4,
228 cfg_connlimit, cfg_connlimit * 4,
230 assert(conn_bucket_cfg);
233 if (cfg_grouplimit > 0) {
234 group_bucket_cfg = ev_token_bucket_cfg_new(
235 cfg_grouplimit, cfg_grouplimit * 4,
236 cfg_grouplimit, cfg_grouplimit * 4,
238 group = ratelim_group = bufferevent_rate_limit_group_new(
239 base, group_bucket_cfg);
240 expected_total_persec = cfg_grouplimit;
241 expected_avg_persec = cfg_grouplimit / cfg_n_connections;
242 if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
243 expected_avg_persec = cfg_connlimit;
244 if (cfg_min_share >= 0)
245 bufferevent_rate_limit_group_set_min_share(
246 ratelim_group, cfg_min_share);
249 if (expected_avg_persec < 0 && cfg_connlimit > 0)
250 expected_avg_persec = cfg_connlimit;
252 if (expected_avg_persec > 0)
253 expected_avg_persec /= seconds_per_tick;
254 if (expected_total_persec > 0)
255 expected_total_persec /= seconds_per_tick;
257 bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
258 states = calloc(cfg_n_connections, sizeof(struct client_state));
260 for (i = 0; i < cfg_n_connections; ++i) {
261 bevs[i] = bufferevent_socket_new(base, -1,
262 BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
264 bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
265 write_on_connectedcb, &states[i]);
266 bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
267 bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
271 tv.tv_sec = cfg_duration - 1;
274 event_base_loopexit(base, &tv);
276 event_base_dispatch(base);
278 ratelim_group = NULL; /* So no more responders get added */
280 for (i = 0; i < cfg_n_connections; ++i) {
281 bufferevent_free(bevs[i]);
283 evconnlistener_free(listener);
285 /* Make sure no new echo_conns get added to the group. */
286 ratelim_group = NULL;
288 /* This should get _everybody_ freed */
289 while (n_echo_conns_open) {
290 printf("waiting for %d conns\n", n_echo_conns_open);
293 event_base_loopexit(base, &tv);
294 event_base_dispatch(base);
298 bufferevent_rate_limit_group_free(group);
302 total_sq_persec = 0.0;
303 for (i=0; i < cfg_n_connections; ++i) {
304 double persec = states[i].received;
305 persec /= cfg_duration;
306 total_received += states[i].received;
307 total_persec += persec;
308 total_sq_persec += persec*persec;
309 printf("%d: %f per second\n", i+1, persec);
311 printf(" total: %f per second\n",
312 ((double)total_received)/cfg_duration);
313 if (expected_total_persec > 0) {
314 double diff = expected_total_persec -
315 ((double)total_received/cfg_duration);
316 printf(" [Off by %lf]\n", diff);
317 if (cfg_grouplimit_tolerance > 0 &&
318 fabs(diff) > cfg_grouplimit_tolerance) {
319 fprintf(stderr, "Group bandwidth out of bounds\n");
324 printf(" average: %f per second\n",
325 (((double)total_received)/cfg_duration)/cfg_n_connections);
326 if (expected_avg_persec > 0) {
327 double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
328 printf(" [Off by %lf]\n", diff);
329 if (cfg_connlimit_tolerance > 0 &&
330 fabs(diff) > cfg_connlimit_tolerance) {
331 fprintf(stderr, "Connection bandwidth out of bounds\n");
336 variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);
338 printf(" stddev: %f per second\n", sqrt(variance));
339 if (cfg_stddev_tolerance > 0 &&
340 sqrt(variance) > cfg_stddev_tolerance) {
341 fprintf(stderr, "Connection variance out of bounds\n");
345 event_base_free(base);
352 static struct option {
353 const char *name; int *ptr; int min; int isbool;
355 { "-v", &cfg_verbose, 0, 1 },
356 { "-h", &cfg_help, 0, 1 },
357 { "-n", &cfg_n_connections, 1, 0 },
358 { "-d", &cfg_duration, 1, 0 },
359 { "-c", &cfg_connlimit, 0, 0 },
360 { "-g", &cfg_grouplimit, 0, 0 },
361 { "-t", &cfg_tick_msec, 10, 0 },
362 { "--min-share", &cfg_min_share, 0, 0 },
363 { "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
364 { "--check-grouplimit", &cfg_grouplimit_tolerance, 0, 0 },
365 { "--check-stddev", &cfg_stddev_tolerance, 0, 0 },
367 { "--iocp", &cfg_enable_iocp, 0, 1 },
369 { NULL, NULL, -1, 0 },
373 handle_option(int argc, char **argv, int *i, const struct option *opt)
381 if (*i + 1 == argc) {
382 fprintf(stderr, "Too few arguments to '%s'\n",argv[*i]);
385 val = strtol(argv[*i+1], &endptr, 10);
386 if (*argv[*i+1] == '\0' || !endptr || *endptr != '\0') {
387 fprintf(stderr, "Couldn't parse numeric value '%s'\n",
391 if (val < opt->min || val > 0x7fffffff) {
392 fprintf(stderr, "Value '%s' is out-of-range'\n",
396 *opt->ptr = (int)val;
405 "test-ratelim [-v] [-n INT] [-d INT] [-c INT] [-g INT] [-t INT]\n\n"
406 "Pushes bytes through a number of possibly rate-limited connections, and\n"
407 "displays average throughput.\n\n"
408 " -n INT: Number of connections to open (default: 30)\n"
409 " -d INT: Duration of the test in seconds (default: 5 sec)\n");
411 " -c INT: Connection-rate limit applied to each connection in bytes per second\n"
412 " (default: None.)\n"
413 " -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
414 " (default: None.)\n"
415 " -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
419 main(int argc, char **argv)
425 WORD wVersionRequested = MAKEWORD(2,2);
429 err = WSAStartup(wVersionRequested, &wsaData);
433 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
436 for (i = 1; i < argc; ++i) {
437 for (j = 0; options[j].name; ++j) {
438 if (!strcmp(argv[i],options[j].name)) {
439 if (handle_option(argc,argv,&i,&options[j])<0)
444 fprintf(stderr, "Unknown option '%s'\n", argv[i]);
455 cfg_tick.tv_sec = cfg_tick_msec / 1000;
456 cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000;
458 seconds_per_tick = ratio = cfg_tick_msec / 1000.0;
460 cfg_connlimit *= ratio;
461 cfg_grouplimit *= ratio;
465 evutil_gettimeofday(&tv, NULL);
473 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
474 evthread_enable_lock_debuging();
477 return test_ratelimiting();