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