dnscrypto-proxy: Update to release 1.3.0
[tomato.git] / release / src / router / dnscrypt / src / libevent-modified / test / test-ratelim.c
blob8958572da4773822f1b13de2d875bf216ea8ef63
1 /*
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
6 * are met:
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.
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <assert.h>
31 #include <math.h>
33 #ifdef WIN32
34 #include <winsock2.h>
35 #include <ws2tcpip.h>
36 #else
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 # ifdef _XOPEN_SOURCE_EXTENDED
40 # include <arpa/inet.h>
41 # endif
42 #endif
43 #include <signal.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;
68 #ifdef _WIN32
69 static int cfg_enable_iocp = 0;
70 #endif
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;
79 struct client_state {
80 size_t queued;
81 ev_uint64_t received;
84 static int n_echo_conns_open = 0;
86 static void
87 loud_writecb(struct bufferevent *bev, void *ctx)
89 struct client_state *cs = ctx;
90 struct evbuffer *output = bufferevent_get_output(bev);
91 char buf[1024];
92 #ifdef WIN32
93 int r = rand() % 256;
94 #else
95 int r = random() % 256;
96 #endif
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);
104 static void
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);
111 cs->received += len;
114 static void
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);
124 static void
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);
135 static void
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);
143 static void
144 echo_eventcb(struct bufferevent *bev, short what, void *ctx)
146 if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
147 --n_echo_conns_open;
148 bufferevent_free(bev);
152 static void
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);
162 if (conn_bucket_cfg)
163 bufferevent_set_rate_limit(bev, conn_bucket_cfg);
164 if (ratelim_group)
165 bufferevent_add_to_rate_limit_group(bev, ratelim_group);
166 ++n_echo_conns_open;
167 bufferevent_enable(bev, EV_READ|EV_WRITE);
170 static int
171 test_ratelimiting(void)
173 struct event_base *base;
174 struct sockaddr_in sin;
175 struct evconnlistener *listener;
177 struct sockaddr_storage ss;
178 ev_socklen_t slen;
180 struct bufferevent **bevs;
181 struct client_state *states;
182 struct bufferevent_rate_limit_group *group = NULL;
184 int i;
186 struct timeval tv;
188 ev_uint64_t total_received;
189 double total_sq_persec, total_persec;
190 double variance;
191 double expected_total_persec = -1.0, expected_avg_persec = -1.0;
192 int ok = 1;
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 */
200 if (0)
201 event_enable_debug_mode();
203 base_cfg = event_config_new();
205 #ifdef _WIN32
206 # ifndef _EVENT_DISABLE_THREAD_SUPPORT
207 if (cfg_enable_iocp) {
208 evthread_use_windows_threads();
209 event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
211 # endif
212 #endif
214 base = event_base_new_with_config(base_cfg);
215 event_config_free(base_cfg);
217 listener = evconnlistener_new_bind(base, echo_listenercb, base,
218 LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
219 (struct sockaddr *)&sin, sizeof(sin));
221 slen = sizeof(ss);
222 if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
223 &slen) < 0) {
224 perror("getsockname");
225 return 1;
228 if (cfg_connlimit > 0) {
229 conn_bucket_cfg = ev_token_bucket_cfg_new(
230 cfg_connlimit, cfg_connlimit * 4,
231 cfg_connlimit, cfg_connlimit * 4,
232 &cfg_tick);
233 assert(conn_bucket_cfg);
236 if (cfg_grouplimit > 0) {
237 group_bucket_cfg = ev_token_bucket_cfg_new(
238 cfg_grouplimit, cfg_grouplimit * 4,
239 cfg_grouplimit, cfg_grouplimit * 4,
240 &cfg_tick);
241 group = ratelim_group = bufferevent_rate_limit_group_new(
242 base, group_bucket_cfg);
243 expected_total_persec = cfg_grouplimit;
244 expected_avg_persec = cfg_grouplimit / cfg_n_connections;
245 if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
246 expected_avg_persec = cfg_connlimit;
247 if (cfg_min_share >= 0)
248 bufferevent_rate_limit_group_set_min_share(
249 ratelim_group, cfg_min_share);
252 if (expected_avg_persec < 0 && cfg_connlimit > 0)
253 expected_avg_persec = cfg_connlimit;
255 if (expected_avg_persec > 0)
256 expected_avg_persec /= seconds_per_tick;
257 if (expected_total_persec > 0)
258 expected_total_persec /= seconds_per_tick;
260 bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
261 states = calloc(cfg_n_connections, sizeof(struct client_state));
263 for (i = 0; i < cfg_n_connections; ++i) {
264 bevs[i] = bufferevent_socket_new(base, -1,
265 BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
266 assert(bevs[i]);
267 bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
268 write_on_connectedcb, &states[i]);
269 bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
270 bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
271 slen);
274 tv.tv_sec = cfg_duration - 1;
275 tv.tv_usec = 995000;
277 event_base_loopexit(base, &tv);
279 event_base_dispatch(base);
281 ratelim_group = NULL; /* So no more responders get added */
283 for (i = 0; i < cfg_n_connections; ++i) {
284 bufferevent_free(bevs[i]);
286 evconnlistener_free(listener);
288 /* Make sure no new echo_conns get added to the group. */
289 ratelim_group = NULL;
291 /* This should get _everybody_ freed */
292 while (n_echo_conns_open) {
293 printf("waiting for %d conns\n", n_echo_conns_open);
294 tv.tv_sec = 0;
295 tv.tv_usec = 300000;
296 event_base_loopexit(base, &tv);
297 event_base_dispatch(base);
300 if (group)
301 bufferevent_rate_limit_group_free(group);
303 total_received = 0;
304 total_persec = 0.0;
305 total_sq_persec = 0.0;
306 for (i=0; i < cfg_n_connections; ++i) {
307 double persec = states[i].received;
308 persec /= cfg_duration;
309 total_received += states[i].received;
310 total_persec += persec;
311 total_sq_persec += persec*persec;
312 printf("%d: %f per second\n", i+1, persec);
314 printf(" total: %f per second\n",
315 ((double)total_received)/cfg_duration);
316 if (expected_total_persec > 0) {
317 double diff = expected_total_persec -
318 ((double)total_received/cfg_duration);
319 printf(" [Off by %lf]\n", diff);
320 if (cfg_grouplimit_tolerance > 0 &&
321 fabs(diff) > cfg_grouplimit_tolerance) {
322 fprintf(stderr, "Group bandwidth out of bounds\n");
323 ok = 0;
327 printf(" average: %f per second\n",
328 (((double)total_received)/cfg_duration)/cfg_n_connections);
329 if (expected_avg_persec > 0) {
330 double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
331 printf(" [Off by %lf]\n", diff);
332 if (cfg_connlimit_tolerance > 0 &&
333 fabs(diff) > cfg_connlimit_tolerance) {
334 fprintf(stderr, "Connection bandwidth out of bounds\n");
335 ok = 0;
339 variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);
341 printf(" stddev: %f per second\n", sqrt(variance));
342 if (cfg_stddev_tolerance > 0 &&
343 sqrt(variance) > cfg_stddev_tolerance) {
344 fprintf(stderr, "Connection variance out of bounds\n");
345 ok = 0;
348 event_base_free(base);
349 free(bevs);
350 free(states);
352 return ok ? 0 : 1;
355 static struct option {
356 const char *name; int *ptr; int min; int isbool;
357 } options[] = {
358 { "-v", &cfg_verbose, 0, 1 },
359 { "-h", &cfg_help, 0, 1 },
360 { "-n", &cfg_n_connections, 1, 0 },
361 { "-d", &cfg_duration, 1, 0 },
362 { "-c", &cfg_connlimit, 0, 0 },
363 { "-g", &cfg_grouplimit, 0, 0 },
364 { "-t", &cfg_tick_msec, 10, 0 },
365 { "--min-share", &cfg_min_share, 0, 0 },
366 { "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
367 { "--check-grouplimit", &cfg_grouplimit_tolerance, 0, 0 },
368 { "--check-stddev", &cfg_stddev_tolerance, 0, 0 },
369 #ifdef _WIN32
370 { "--iocp", &cfg_enable_iocp, 0, 1 },
371 #endif
372 { NULL, NULL, -1, 0 },
375 static int
376 handle_option(int argc, char **argv, int *i, const struct option *opt)
378 long val;
379 char *endptr = NULL;
380 if (opt->isbool) {
381 *opt->ptr = 1;
382 return 0;
384 if (*i + 1 == argc) {
385 fprintf(stderr, "Too few arguments to '%s'\n",argv[*i]);
386 return -1;
388 val = strtol(argv[*i+1], &endptr, 10);
389 if (*argv[*i+1] == '\0' || !endptr || *endptr != '\0') {
390 fprintf(stderr, "Couldn't parse numeric value '%s'\n",
391 argv[*i+1]);
392 return -1;
394 if (val < opt->min || val > 0x7fffffff) {
395 fprintf(stderr, "Value '%s' is out-of-range'\n",
396 argv[*i+1]);
397 return -1;
399 *opt->ptr = (int)val;
400 ++*i;
401 return 0;
404 static void
405 usage(void)
407 fprintf(stderr,
408 "test-ratelim [-v] [-n INT] [-d INT] [-c INT] [-g INT] [-t INT]\n\n"
409 "Pushes bytes through a number of possibly rate-limited connections, and\n"
410 "displays average throughput.\n\n"
411 " -n INT: Number of connections to open (default: 30)\n"
412 " -d INT: Duration of the test in seconds (default: 5 sec)\n");
413 fprintf(stderr,
414 " -c INT: Connection-rate limit applied to each connection in bytes per second\n"
415 " (default: None.)\n"
416 " -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
417 " (default: None.)\n"
418 " -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
422 main(int argc, char **argv)
424 int i,j;
425 double ratio;
427 #ifdef WIN32
428 WORD wVersionRequested = MAKEWORD(2,2);
429 WSADATA wsaData;
431 (void) WSAStartup(wVersionRequested, &wsaData);
432 #endif
434 #ifndef WIN32
435 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
436 return 1;
437 #endif
438 for (i = 1; i < argc; ++i) {
439 for (j = 0; options[j].name; ++j) {
440 if (!strcmp(argv[i],options[j].name)) {
441 if (handle_option(argc,argv,&i,&options[j])<0)
442 return 1;
443 goto again;
446 fprintf(stderr, "Unknown option '%s'\n", argv[i]);
447 usage();
448 return 1;
449 again:
452 if (cfg_help) {
453 usage();
454 return 0;
457 cfg_tick.tv_sec = cfg_tick_msec / 1000;
458 cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000;
460 seconds_per_tick = ratio = cfg_tick_msec / 1000.0;
462 cfg_connlimit *= ratio;
463 cfg_grouplimit *= ratio;
466 struct timeval tv;
467 evutil_gettimeofday(&tv, NULL);
468 #ifdef WIN32
469 srand(tv.tv_usec);
470 #else
471 srandom(tv.tv_usec);
472 #endif
475 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
476 evthread_enable_lock_debuging();
477 #endif
479 return test_ratelimiting();