xref: /netbsd-src/external/bsd/ntp/dist/sntp/libevent/test/test-ratelim.c (revision 2dd295436a0082eb4f8d294f4aa73c223413d0f2)
1 /*	$NetBSD: test-ratelim.c,v 1.7 2020/05/25 20:47:34 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 #include "../util-internal.h"
29 
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34 #include <math.h>
35 
36 #ifdef _WIN32
37 #include <winsock2.h>
38 #include <ws2tcpip.h>
39 #else
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 # ifdef _XOPEN_SOURCE_EXTENDED
43 #  include <arpa/inet.h>
44 # endif
45 #endif
46 #include <signal.h>
47 
48 #include "event2/bufferevent.h"
49 #include "event2/buffer.h"
50 #include "event2/event.h"
51 #include "event2/util.h"
52 #include "event2/listener.h"
53 #include "event2/thread.h"
54 
55 static struct evutil_weakrand_state weakrand_state;
56 
57 static int cfg_verbose = 0;
58 static int cfg_help = 0;
59 
60 static int cfg_n_connections = 30;
61 static int cfg_duration = 5;
62 static int cfg_connlimit = 0;
63 static int cfg_grouplimit = 0;
64 static int cfg_tick_msec = 1000;
65 static int cfg_min_share = -1;
66 static int cfg_group_drain = 0;
67 
68 static int cfg_connlimit_tolerance = -1;
69 static int cfg_grouplimit_tolerance = -1;
70 static int cfg_stddev_tolerance = -1;
71 
72 #ifdef _WIN32
73 static int cfg_enable_iocp = 0;
74 #endif
75 
76 static struct timeval cfg_tick = { 0, 500*1000 };
77 
78 static struct ev_token_bucket_cfg *conn_bucket_cfg = NULL;
79 static struct ev_token_bucket_cfg *group_bucket_cfg = NULL;
80 struct bufferevent_rate_limit_group *ratelim_group = NULL;
81 static double seconds_per_tick = 0.0;
82 
83 struct client_state {
84 	size_t queued;
85 	ev_uint64_t received;
86 
87 };
88 static const struct timeval *ms100_common=NULL;
89 
90 /* info from check_bucket_levels_cb */
91 static int total_n_bev_checks = 0;
92 static ev_int64_t total_rbucket_level=0;
93 static ev_int64_t total_wbucket_level=0;
94 static ev_int64_t total_max_to_read=0;
95 static ev_int64_t total_max_to_write=0;
96 static ev_int64_t max_bucket_level=EV_INT64_MIN;
97 static ev_int64_t min_bucket_level=EV_INT64_MAX;
98 
99 /* from check_group_bucket_levels_cb */
100 static int total_n_group_bev_checks = 0;
101 static ev_int64_t total_group_rbucket_level = 0;
102 static ev_int64_t total_group_wbucket_level = 0;
103 
104 static int n_echo_conns_open = 0;
105 
106 /* Info on the open connections */
107 struct bufferevent **bevs;
108 struct client_state *states;
109 struct bufferevent_rate_limit_group *group = NULL;
110 
111 static void check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg);
112 
113 static void
114 loud_writecb(struct bufferevent *bev, void *ctx)
115 {
116 	struct client_state *cs = ctx;
117 	struct evbuffer *output = bufferevent_get_output(bev);
118 	char buf[1024];
119 	int r = evutil_weakrand_(&weakrand_state);
120 	memset(buf, r, sizeof(buf));
121 	while (evbuffer_get_length(output) < 8192) {
122 		evbuffer_add(output, buf, sizeof(buf));
123 		cs->queued += sizeof(buf);
124 	}
125 }
126 
127 static void
128 discard_readcb(struct bufferevent *bev, void *ctx)
129 {
130 	struct client_state *cs = ctx;
131 	struct evbuffer *input = bufferevent_get_input(bev);
132 	size_t len = evbuffer_get_length(input);
133 	evbuffer_drain(input, len);
134 	cs->received += len;
135 }
136 
137 static void
138 write_on_connectedcb(struct bufferevent *bev, short what, void *ctx)
139 {
140 	if (what & BEV_EVENT_CONNECTED) {
141 		loud_writecb(bev, ctx);
142 		/* XXXX this shouldn't be needed. */
143 		bufferevent_enable(bev, EV_READ|EV_WRITE);
144 	}
145 }
146 
147 static void
148 echo_readcb(struct bufferevent *bev, void *ctx)
149 {
150 	struct evbuffer *input = bufferevent_get_input(bev);
151 	struct evbuffer *output = bufferevent_get_output(bev);
152 
153 	evbuffer_add_buffer(output, input);
154 	if (evbuffer_get_length(output) > 1024000)
155 		bufferevent_disable(bev, EV_READ);
156 }
157 
158 static void
159 echo_writecb(struct bufferevent *bev, void *ctx)
160 {
161 	struct evbuffer *output = bufferevent_get_output(bev);
162 	if (evbuffer_get_length(output) < 512000)
163 		bufferevent_enable(bev, EV_READ);
164 }
165 
166 static void
167 echo_eventcb(struct bufferevent *bev, short what, void *ctx)
168 {
169 	if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
170 		--n_echo_conns_open;
171 		bufferevent_free(bev);
172 	}
173 }
174 
175 static void
176 echo_listenercb(struct evconnlistener *listener, evutil_socket_t newsock,
177     struct sockaddr *sourceaddr, int socklen, void *ctx)
178 {
179 	struct event_base *base = ctx;
180 	int flags = BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE;
181 	struct bufferevent *bev;
182 
183 	bev = bufferevent_socket_new(base, newsock, flags);
184 	bufferevent_setcb(bev, echo_readcb, echo_writecb, echo_eventcb, NULL);
185 	if (conn_bucket_cfg) {
186 		struct event *check_event =
187 		    event_new(base, -1, EV_PERSIST, check_bucket_levels_cb, bev);
188 		bufferevent_set_rate_limit(bev, conn_bucket_cfg);
189 
190 		assert(bufferevent_get_token_bucket_cfg(bev) != NULL);
191 		event_add(check_event, ms100_common);
192 	}
193 	if (ratelim_group)
194 		bufferevent_add_to_rate_limit_group(bev, ratelim_group);
195 	++n_echo_conns_open;
196 	bufferevent_enable(bev, EV_READ|EV_WRITE);
197 }
198 
199 /* Called periodically to check up on how full the buckets are */
200 static void
201 check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
202 {
203 	struct bufferevent *bev = arg;
204 
205 	ev_ssize_t r = bufferevent_get_read_limit(bev);
206 	ev_ssize_t w = bufferevent_get_write_limit(bev);
207 	ev_ssize_t rm = bufferevent_get_max_to_read(bev);
208 	ev_ssize_t wm = bufferevent_get_max_to_write(bev);
209 	/* XXXX check that no value is above the cofigured burst
210 	 * limit */
211 	total_rbucket_level += r;
212 	total_wbucket_level += w;
213 	total_max_to_read += rm;
214 	total_max_to_write += wm;
215 #define B(x) \
216 	if ((x) > max_bucket_level)		\
217 		max_bucket_level = (x);		\
218 	if ((x) < min_bucket_level)		\
219 		min_bucket_level = (x)
220 	B(r);
221 	B(w);
222 #undef B
223 
224 	total_n_bev_checks++;
225 	if (total_n_bev_checks >= .8 * ((double)cfg_duration / cfg_tick_msec) * cfg_n_connections) {
226 		event_free(event_base_get_running_event(bufferevent_get_base(bev)));
227 	}
228 }
229 
230 static void
231 check_group_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
232 {
233 	if (ratelim_group) {
234 		ev_ssize_t r = bufferevent_rate_limit_group_get_read_limit(ratelim_group);
235 		ev_ssize_t w = bufferevent_rate_limit_group_get_write_limit(ratelim_group);
236 		total_group_rbucket_level += r;
237 		total_group_wbucket_level += w;
238 	}
239 	++total_n_group_bev_checks;
240 }
241 
242 static void
243 group_drain_cb(evutil_socket_t fd, short events, void *arg)
244 {
245 	bufferevent_rate_limit_group_decrement_read(ratelim_group, cfg_group_drain);
246 	bufferevent_rate_limit_group_decrement_write(ratelim_group, cfg_group_drain);
247 }
248 
249 static int
250 test_ratelimiting(void)
251 {
252 	struct event_base *base;
253 	struct sockaddr_in sin;
254 	struct evconnlistener *listener;
255 
256 	struct sockaddr_storage ss;
257 	ev_socklen_t slen;
258 
259 	int i;
260 
261 	struct timeval tv;
262 
263 	ev_uint64_t total_received;
264 	double total_sq_persec, total_persec;
265 	double variance;
266 	double expected_total_persec = -1.0, expected_avg_persec = -1.0;
267 	int ok = 1;
268 	struct event_config *base_cfg;
269 	struct event *periodic_level_check;
270 	struct event *group_drain_event=NULL;
271 
272 	memset(&sin, 0, sizeof(sin));
273 	sin.sin_family = AF_INET;
274 	sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
275 	sin.sin_port = 0; /* unspecified port */
276 
277 	if (0)
278 		event_enable_debug_mode();
279 
280 	base_cfg = event_config_new();
281 
282 #ifdef _WIN32
283 	if (cfg_enable_iocp) {
284 		evthread_use_windows_threads();
285 		event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
286 	}
287 #endif
288 
289 	base = event_base_new_with_config(base_cfg);
290 	event_config_free(base_cfg);
291 	if (! base) {
292 		fprintf(stderr, "Couldn't create event_base");
293 		return 1;
294 	}
295 
296 	listener = evconnlistener_new_bind(base, echo_listenercb, base,
297 	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
298 	    (struct sockaddr *)&sin, sizeof(sin));
299 	if (! listener) {
300 		fprintf(stderr, "Couldn't create listener");
301 		return 1;
302 	}
303 
304 	slen = sizeof(ss);
305 	if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
306 		&slen) < 0) {
307 		perror("getsockname");
308 		return 1;
309 	}
310 
311 	if (cfg_connlimit > 0) {
312 		conn_bucket_cfg = ev_token_bucket_cfg_new(
313 			cfg_connlimit, cfg_connlimit * 4,
314 			cfg_connlimit, cfg_connlimit * 4,
315 			&cfg_tick);
316 		assert(conn_bucket_cfg);
317 	}
318 
319 	if (cfg_grouplimit > 0) {
320 		group_bucket_cfg = ev_token_bucket_cfg_new(
321 			cfg_grouplimit, cfg_grouplimit * 4,
322 			cfg_grouplimit, cfg_grouplimit * 4,
323 			&cfg_tick);
324 		group = ratelim_group = bufferevent_rate_limit_group_new(
325 			base, group_bucket_cfg);
326 		expected_total_persec = cfg_grouplimit - (cfg_group_drain / seconds_per_tick);
327 		expected_avg_persec = cfg_grouplimit / cfg_n_connections;
328 		if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
329 			expected_avg_persec = cfg_connlimit;
330 		if (cfg_min_share >= 0)
331 			bufferevent_rate_limit_group_set_min_share(
332 				ratelim_group, cfg_min_share);
333 	}
334 
335 	if (expected_avg_persec < 0 && cfg_connlimit > 0)
336 		expected_avg_persec = cfg_connlimit;
337 
338 	if (expected_avg_persec > 0)
339 		expected_avg_persec /= seconds_per_tick;
340 	if (expected_total_persec > 0)
341 		expected_total_persec /= seconds_per_tick;
342 
343 	bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
344 	states = calloc(cfg_n_connections, sizeof(struct client_state));
345 	if (bevs == NULL || states == NULL) {
346 		printf("Unable to allocate memory...\n");
347 		return 1;
348 	}
349 
350 	for (i = 0; i < cfg_n_connections; ++i) {
351 		bevs[i] = bufferevent_socket_new(base, -1,
352 		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
353 		assert(bevs[i]);
354 		bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
355 		    write_on_connectedcb, &states[i]);
356 		bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
357 		bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
358 		    slen);
359 	}
360 
361 	tv.tv_sec = cfg_duration - 1;
362 	tv.tv_usec = 995000;
363 
364 	event_base_loopexit(base, &tv);
365 
366 	tv.tv_sec = 0;
367 	tv.tv_usec = 100*1000;
368 	ms100_common = event_base_init_common_timeout(base, &tv);
369 
370 	periodic_level_check = event_new(base, -1, EV_PERSIST, check_group_bucket_levels_cb, NULL);
371 	event_add(periodic_level_check, ms100_common);
372 
373 	if (cfg_group_drain && ratelim_group) {
374 		group_drain_event = event_new(base, -1, EV_PERSIST, group_drain_cb, NULL);
375 		event_add(group_drain_event, &cfg_tick);
376 	}
377 
378 	event_base_dispatch(base);
379 
380 	ratelim_group = NULL; /* So no more responders get added */
381 	event_free(periodic_level_check);
382 	if (group_drain_event)
383 		event_del(group_drain_event);
384 
385 	for (i = 0; i < cfg_n_connections; ++i) {
386 		bufferevent_free(bevs[i]);
387 	}
388 	evconnlistener_free(listener);
389 
390 	/* Make sure no new echo_conns get added to the group. */
391 	ratelim_group = NULL;
392 
393 	/* This should get _everybody_ freed */
394 	while (n_echo_conns_open) {
395 		printf("waiting for %d conns\n", n_echo_conns_open);
396 		tv.tv_sec = 0;
397 		tv.tv_usec = 300000;
398 		event_base_loopexit(base, &tv);
399 		event_base_dispatch(base);
400 	}
401 
402 	if (group)
403 		bufferevent_rate_limit_group_free(group);
404 
405 	if (total_n_bev_checks) {
406 		printf("Average read bucket level: %f\n",
407 		    (double)total_rbucket_level/total_n_bev_checks);
408 		printf("Average write bucket level: %f\n",
409 		    (double)total_wbucket_level/total_n_bev_checks);
410 		printf("Highest read bucket level: %f\n",
411 		    (double)max_bucket_level);
412 		printf("Highest write bucket level: %f\n",
413 		    (double)min_bucket_level);
414 		printf("Average max-to-read: %f\n",
415 		    ((double)total_max_to_read)/total_n_bev_checks);
416 		printf("Average max-to-write: %f\n",
417 		    ((double)total_max_to_write)/total_n_bev_checks);
418 	}
419 	if (total_n_group_bev_checks) {
420 		printf("Average group read bucket level: %f\n",
421 		    ((double)total_group_rbucket_level)/total_n_group_bev_checks);
422 		printf("Average group write bucket level: %f\n",
423 		    ((double)total_group_wbucket_level)/total_n_group_bev_checks);
424 	}
425 
426 	total_received = 0;
427 	total_persec = 0.0;
428 	total_sq_persec = 0.0;
429 	for (i=0; i < cfg_n_connections; ++i) {
430 		double persec = states[i].received;
431 		persec /= cfg_duration;
432 		total_received += states[i].received;
433 		total_persec += persec;
434 		total_sq_persec += persec*persec;
435 		printf("%d: %f per second\n", i+1, persec);
436 	}
437 	printf("   total: %f per second\n",
438 	    ((double)total_received)/cfg_duration);
439 	if (expected_total_persec > 0) {
440 		double diff = expected_total_persec -
441 		    ((double)total_received/cfg_duration);
442 		printf("  [Off by %lf]\n", diff);
443 		if (cfg_grouplimit_tolerance > 0 &&
444 		    fabs(diff) > cfg_grouplimit_tolerance) {
445 			fprintf(stderr, "Group bandwidth out of bounds\n");
446 			ok = 0;
447 		}
448 	}
449 
450 	printf(" average: %f per second\n",
451 	    (((double)total_received)/cfg_duration)/cfg_n_connections);
452 	if (expected_avg_persec > 0) {
453 		double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
454 		printf("  [Off by %lf]\n", diff);
455 		if (cfg_connlimit_tolerance > 0 &&
456 		    fabs(diff) > cfg_connlimit_tolerance) {
457 			fprintf(stderr, "Connection bandwidth out of bounds\n");
458 			ok = 0;
459 		}
460 	}
461 
462 	variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);
463 
464 	printf("  stddev: %f per second\n", sqrt(variance));
465 	if (cfg_stddev_tolerance > 0 &&
466 	    sqrt(variance) > cfg_stddev_tolerance) {
467 		fprintf(stderr, "Connection variance out of bounds\n");
468 		ok = 0;
469 	}
470 
471 	event_base_free(base);
472 	free(bevs);
473 	free(states);
474 
475 	return ok ? 0 : 1;
476 }
477 
478 static struct option {
479 	const char *name; int *ptr; int min; int isbool;
480 } options[] = {
481 	{ "-v", &cfg_verbose, 0, 1 },
482 	{ "-h", &cfg_help, 0, 1 },
483 	{ "-n", &cfg_n_connections, 1, 0 },
484 	{ "-d", &cfg_duration, 1, 0 },
485 	{ "-c", &cfg_connlimit, 0, 0 },
486 	{ "-g", &cfg_grouplimit, 0, 0 },
487 	{ "-G", &cfg_group_drain, -100000, 0 },
488 	{ "-t", &cfg_tick_msec, 10, 0 },
489 	{ "--min-share", &cfg_min_share, 0, 0 },
490 	{ "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
491 	{ "--check-grouplimit", &cfg_grouplimit_tolerance, 0, 0 },
492 	{ "--check-stddev", &cfg_stddev_tolerance, 0, 0 },
493 #ifdef _WIN32
494 	{ "--iocp", &cfg_enable_iocp, 0, 1 },
495 #endif
496 	{ NULL, NULL, -1, 0 },
497 };
498 
499 static int
500 handle_option(int argc, char **argv, int *i, const struct option *opt)
501 {
502 	long val;
503 	char *endptr = NULL;
504 	if (opt->isbool) {
505 		*opt->ptr = 1;
506 		return 0;
507 	}
508 	if (*i + 1 == argc) {
509 		fprintf(stderr, "Too few arguments to '%s'\n",argv[*i]);
510 		return -1;
511 	}
512 	val = strtol(argv[*i+1], &endptr, 10);
513 	if (*argv[*i+1] == '\0' || !endptr || *endptr != '\0') {
514 		fprintf(stderr, "Couldn't parse numeric value '%s'\n",
515 		    argv[*i+1]);
516 		return -1;
517 	}
518 	if (val < opt->min || val > 0x7fffffff) {
519 		fprintf(stderr, "Value '%s' is out-of-range'\n",
520 		    argv[*i+1]);
521 		return -1;
522 	}
523 	*opt->ptr = (int)val;
524 	++*i;
525 	return 0;
526 }
527 
528 static void
529 usage(void)
530 {
531 	fprintf(stderr,
532 "test-ratelim [-v] [-n INT] [-d INT] [-c INT] [-g INT] [-t INT]\n\n"
533 "Pushes bytes through a number of possibly rate-limited connections, and\n"
534 "displays average throughput.\n\n"
535 "  -n INT: Number of connections to open (default: 30)\n"
536 "  -d INT: Duration of the test in seconds (default: 5 sec)\n");
537 	fprintf(stderr,
538 "  -c INT: Connection-rate limit applied to each connection in bytes per second\n"
539 "	   (default: None.)\n"
540 "  -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
541 "	   (default: None.)\n"
542 "  -G INT: drain INT bytes from the group limit every tick. (default: 0)\n"
543 "  -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
544 }
545 
546 int
547 main(int argc, char **argv)
548 {
549 	int i,j;
550 	double ratio;
551 
552 #ifdef _WIN32
553 	WORD wVersionRequested = MAKEWORD(2,2);
554 	WSADATA wsaData;
555 
556 	(void) WSAStartup(wVersionRequested, &wsaData);
557 #endif
558 
559 	evutil_weakrand_seed_(&weakrand_state, 0);
560 
561 #ifndef _WIN32
562 	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
563 		return 1;
564 #endif
565 	for (i = 1; i < argc; ++i) {
566 		for (j = 0; options[j].name; ++j) {
567 			if (!strcmp(argv[i],options[j].name)) {
568 				if (handle_option(argc,argv,&i,&options[j])<0)
569 					return 1;
570 				goto again;
571 			}
572 		}
573 		fprintf(stderr, "Unknown option '%s'\n", argv[i]);
574 		usage();
575 		return 1;
576 	again:
577 		;
578 	}
579 	if (cfg_help) {
580 		usage();
581 		return 0;
582 	}
583 
584 	cfg_tick.tv_sec = cfg_tick_msec / 1000;
585 	cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000;
586 
587 	seconds_per_tick = ratio = cfg_tick_msec / 1000.0;
588 
589 	cfg_connlimit *= ratio;
590 	cfg_grouplimit *= ratio;
591 
592 	{
593 		struct timeval tv;
594 		evutil_gettimeofday(&tv, NULL);
595 #ifdef _WIN32
596 		srand(tv.tv_usec);
597 #else
598 		srandom(tv.tv_usec);
599 #endif
600 	}
601 
602 #ifndef EVENT__DISABLE_THREAD_SUPPORT
603 	evthread_enable_lock_debugging();
604 #endif
605 
606 	return test_ratelimiting();
607 }
608