]> git.sesse.net Git - jam/blob - jam.c
Stop malloc()-ing for each new connection.
[jam] / jam.c
1 #include <stdio.h>
2 #include <math.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <getopt.h>
6 #include <netdb.h>
7 #include <unistd.h>
8 #include <pthread.h>
9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <sys/epoll.h>
12 #include <sys/ioctl.h>
13 #include <errno.h>
14
15 unsigned short port = 2007;
16
17 struct in_addr *destinations = NULL;
18 unsigned num_destinations = 0;
19 unsigned room_destinations = 0;
20
21 struct in_addr *sources = NULL;
22 unsigned num_sources = 0;
23 unsigned room_sources = 0;
24
25 unsigned num_senders = 128;
26 unsigned num_sockets_per_sender = 16;
27 unsigned do_listen = 1;
28
29 unsigned long long total_bytes_received = 0;
30 pthread_mutex_t receive_mutex = PTHREAD_MUTEX_INITIALIZER;
31
32 unsigned long long total_bytes_sent = 0;
33 pthread_mutex_t send_mutex = PTHREAD_MUTEX_INITIALIZER;
34
35 const static struct option longopts[] = {
36         { "source-list", required_argument, NULL, 's' },
37         { "destination-list", required_argument, NULL, 'd' },
38         { "num-senders", required_argument, NULL, 'n' },
39         { "num-sockets-per-sender", required_argument, NULL, 'N' },
40         { "port", required_argument, NULL, 'p' },
41         { "sender-only", no_argument, NULL, 'o' },
42         { NULL, 0, NULL, 0 }
43 };
44
45 // generates from [0,1>
46 double gen_uniform_random()
47 {
48         return rand() / (RAND_MAX+1.0);
49 }
50
51 double gen_pareto_random(double min, double k)
52 {
53         double u = gen_uniform_random();
54         return min * pow(u, -1.0 / k);
55 }
56
57 void read_ip_list(char *filename, struct in_addr **addr_list, unsigned *num, unsigned *room)
58 {
59         char buf[256];
60         FILE *in = fopen(filename, "r");
61         if (in == NULL) {
62                 perror(filename);
63                 exit(1);
64         }
65
66         for ( ;; ) {
67                 char *ptr;
68                 struct in_addr addr;
69                 struct hostent *he;
70
71                 if (fgets(buf, 256, in) == NULL)
72                         break;
73
74                 ptr = strchr(buf, '\n');
75                 if (ptr != NULL)
76                         *ptr = 0;
77
78                 ptr = strchr(buf, '\r');
79                 if (ptr != NULL)
80                         *ptr = 0;
81                 
82                 ptr = buf + strspn(buf, " \t");
83
84                 if (ptr[0] == '#' || ptr[0] == 0)
85                         continue;
86
87                 he = gethostbyname(ptr);
88                 if (he == NULL) {
89                         perror(ptr);
90                         exit(1);
91                 }
92
93                 // just pick the first for now
94                 memcpy(&addr.s_addr, he->h_addr_list[0], sizeof(addr.s_addr));
95
96                 if (*num >= *room) {
97                         if (*room == 0) {
98                                 *room = 16;
99                         } else {
100                                 *room <<= 1;
101                         }
102                         *addr_list = (struct in_addr *)realloc(*addr_list, *room * sizeof(struct in_addr));
103                 }
104
105                 (*addr_list)[*num] = addr;
106                 ++*num;
107         }
108
109         fclose(in);
110 }
111
112 void parse_options(int argc, char **argv)
113 {
114         int option_index = 0;
115
116         for ( ;; ) {
117                 int c = getopt_long(argc, argv, "s:d:n:N:p:o", longopts, &option_index); 
118                 switch (c) {
119                 case 's':
120                         read_ip_list(optarg, &sources, &num_sources, &room_sources);
121                         break;
122                 case 'd':
123                         read_ip_list(optarg, &destinations, &num_destinations, &room_destinations);
124                         break;
125                 case 'n':
126                         num_senders = atoi(optarg);
127                         break;
128                 case 'N':
129                         num_sockets_per_sender = atoi(optarg);
130                         break;
131                 case 'p':
132                         port = atoi(optarg);
133                         break;
134                 case 'o':
135                         do_listen = 0;
136                         break;
137                 case -1:
138                         return;       // end of argument list
139                 default:
140                         fprintf(stderr, "Invalid option\n");
141                         exit(1);
142                 }
143         }
144 }
145
146 struct sender {
147         int fd;
148         unsigned long long bytes_left;
149 };
150
151 void generate_new_sender(int ep_fd, struct sender *s)
152 {
153         int sock, one = 1;
154         unsigned src_num, dst_num;
155         unsigned long long num_bytes;
156         struct sockaddr_in sin;
157         struct epoll_event ev;
158         
159         sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
160         if (sock == -1) {
161                 perror("socket()");
162                 exit(1);
163         }
164
165         // find the right parameters
166         src_num = (unsigned)(num_sources * gen_uniform_random());
167         dst_num = (unsigned)(num_destinations * gen_uniform_random());
168         num_bytes = (unsigned)gen_pareto_random(1048576.0, 1.0);
169
170         // FIXME: bind to the right source
171
172         if (ioctl(sock, FIONBIO, &one) == -1) {
173                 perror("FIONBIO");
174                 exit(1);
175         }
176
177         sin.sin_family = AF_INET;
178         sin.sin_port = htons(port);
179         sin.sin_addr = destinations[dst_num];
180
181         // non-blocking connect (will be detected by epoll later)
182         if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1 && errno != EINPROGRESS) {
183                 perror("connect()");
184                 exit(1);
185         }
186         
187         // stick it in the epoll set (FIXME: make edge-triggered?)
188         ev.events = EPOLLOUT | EPOLLHUP | EPOLLERR;
189         ev.data.ptr = s;
190
191         s->fd = sock;
192         s->bytes_left = num_bytes;
193
194         if (epoll_ctl(ep_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
195                 perror("EPOLL_CTL_ADD");
196                 exit(1);
197         }
198 }
199
200 void *sender_worker(void *arg)
201 {
202         unsigned i;
203         char buf[65536];
204         unsigned long long bytes_sent = 0;
205         int ep_fd;
206         struct epoll_event *events;
207
208         ep_fd = epoll_create(num_sockets_per_sender);
209         if (ep_fd == -1) {
210                 perror("epoll_create");
211                 exit(1);
212         }
213
214         // malloc, since there might not be enough room on the stack
215         events = (struct epoll_event *)malloc(sizeof(struct epoll_event) * num_sockets_per_sender);
216         if (events == NULL) {
217                 perror("malloc");
218                 exit(1);
219         }
220
221         // fill the buffer with random junk
222         for (i = 0; i < 65536; ++i)
223                 buf[i] = rand() & 0xff;
224
225         // allocate all the senders
226         for (i = 0; i < num_sockets_per_sender; ++i) {
227                 struct sender *s = (struct sender *)malloc(sizeof(struct sender));
228                 if (s == NULL) {
229                         perror("malloc()");
230                         exit(1);
231                 }
232
233                 generate_new_sender(ep_fd, s);
234         }
235
236         for ( ;; ) {
237                 int num_active = epoll_wait(ep_fd, events, num_sockets_per_sender, -1);
238                 if (num_active == -1) {
239                         perror("epoll_wait");
240                         exit(1);
241                 }
242
243                 for (i = 0; i < num_active; ++i) {
244                         struct sender *s = (struct sender *)events[i].data.ptr;
245                         unsigned long long bytes_to_send = s->bytes_left;
246                         unsigned ret;
247
248                         if (bytes_to_send > 65536) {
249                                 bytes_to_send = 65536;  
250                         }
251
252                         ret = send(s->fd, buf, bytes_to_send, MSG_NOSIGNAL);
253                         if (ret == -1) {
254                                 if (errno == EAGAIN)
255                                         continue;
256
257                                 perror("send()");
258                                 exit(1);
259                         }
260
261                         s->bytes_left -= ret;
262                         bytes_sent += ret;
263
264                         // update the central counter after every 1MB (8ms
265                         // at gigabit speeds, should be enough) of sent data
266                         if (bytes_sent > 1048576) {
267                                 pthread_mutex_lock(&send_mutex);
268                                 total_bytes_sent += bytes_sent;
269                                 pthread_mutex_unlock(&send_mutex);
270
271                                 bytes_sent = 0;
272                         }
273                         
274                         if (s->bytes_left == 0) {
275                                 if (epoll_ctl(ep_fd, EPOLL_CTL_DEL, s->fd, NULL) == -1) {
276                                         perror("EPOLL_CTL_ADD");
277                                         exit(1);
278                                 }
279                                 close(s->fd);
280                                 generate_new_sender(ep_fd, s);
281                         }
282                 }
283         }
284
285         pthread_mutex_lock(&send_mutex);
286         total_bytes_sent += bytes_sent;
287         pthread_mutex_unlock(&send_mutex);
288
289         free(events);
290         close(ep_fd);
291
292         pthread_exit(0);
293 }
294
295 void *receiver_worker(void *arg)
296 {
297         int sock = (int)arg;
298         char buf[65536];
299         unsigned long long bytes_received = 0;
300
301         for ( ;; ) {
302                 int ret = read(sock, buf, 65536);
303                 if (ret == 0)
304                         break;
305
306                 bytes_received += ret;
307
308                 // update the central counter after every 1MB (8ms
309                 // at gigabit speeds, should be enough) of received data
310                 if (bytes_received > 1048576) {
311                         pthread_mutex_lock(&receive_mutex);
312                         total_bytes_received += bytes_received;
313                         pthread_mutex_unlock(&receive_mutex);
314
315                         bytes_received = 0;
316                 }
317         }
318         
319         if (close(sock) == -1) {
320                 perror("close()");
321                 exit(1);
322         }
323                         
324         pthread_mutex_lock(&receive_mutex);
325         total_bytes_received += bytes_received;
326         pthread_mutex_unlock(&receive_mutex);
327
328         pthread_exit(0);
329 }
330         
331 void *receiver_dispatcher(void *arg)
332 {
333         int server_sock = (int)arg;
334         pthread_attr_t attr;
335         
336         // FIXME: these do not really set errno
337         if (pthread_attr_init(&attr) != 0) {
338                 perror("pthread_attr_init()");
339                 exit(1);
340         }
341
342         if (pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 65536 + 0x4000) != 0) {
343                 perror("pthread_attr_setstacksize");
344                 exit(1);
345         }
346
347         if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
348                 perror("pthread_attr_setdetachstate");
349                 exit(1);
350         }
351
352         /*
353          * Listen for incoming connections, spawning off one receiver
354          * thread for each (which will just gobble up the data until
355          * we're done).
356          */
357         for ( ;; ) {
358                 struct sockaddr_in addr;
359                 socklen_t addr_len = sizeof(addr);
360                 pthread_t thread;
361
362                 int sock = accept(server_sock, (struct sockaddr *)&addr, &addr_len);
363                 if (sock == -1) {
364                         perror("accept()");
365                         exit(1);
366                 }
367
368                 if (pthread_create(&thread, &attr, receiver_worker, (void *)sock) != 0) {
369                         perror("pthread_create()");
370                         exit(1);
371                 }
372         }
373 }
374
375 int get_server_socket(unsigned short port)
376 {
377         int server_sock;
378         struct sockaddr_in sin;
379         unsigned one = 1;
380
381         server_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
382         if (server_sock == -1) {
383                 perror("socket()");
384                 exit(1);
385         }
386
387         if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
388                 perror("setsocket(SO_REUSEADDR)");
389                 exit(1);
390         }
391
392         sin.sin_family = AF_INET;
393         sin.sin_port = htons(port);
394         sin.sin_addr.s_addr = INADDR_ANY;
395
396         if (bind(server_sock, (struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) {
397                 perror("bind()");
398                 exit(1);
399         }
400
401         if (listen(server_sock, 255) == -1) {
402                 perror("listen()");
403                 exit(1);
404         }
405
406         return server_sock;
407 }
408
409 int main(int argc, char **argv)
410 {
411         int server_sock;
412         unsigned i;
413         pthread_attr_t attr;
414
415         parse_options(argc, argv);
416
417         if (destinations == NULL || sources == NULL) {
418                 fprintf(stderr, "Missing or empty source or destination host list. Aborting.\n");
419                 exit(1);
420         }
421
422         if (do_listen) {
423                 server_sock = get_server_socket(port);
424         }
425         
426         printf("Sending data on port %u from %u sources to %u destinations.\n\n",
427                 port, num_sources, num_destinations);
428                 
429         // FIXME: these do not really set errno
430         if (pthread_attr_init(&attr) != 0) {
431                 perror("pthread_attr_init()");
432                 exit(1);
433         }
434
435         if (pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 65536 + 0x4000) != 0) {
436                 perror("pthread_attr_setstacksize");
437                 exit(1);
438         }
439
440         if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
441                 perror("pthread_attr_setdetachstate");
442                 exit(1);
443         }
444                 
445         // Fire off the master receiver.
446         if (do_listen) {
447                 pthread_t thread;
448                 if (pthread_create(&thread, &attr, receiver_dispatcher, (void *)server_sock) != 0) {
449                         perror("pthread_create()");
450                         exit(1);
451                 }
452         }
453
454         printf("Waiting five seconds before starting senders...\n");
455         sleep(5);
456
457         // Fire off sender workers.
458         for (i = 0; i < num_senders; ++i) {
459                 pthread_t thread;
460                 
461                 if (pthread_create(&thread, &attr, sender_worker, NULL) != 0) {
462                         perror("pthread_create()");
463                         exit(1);
464                 }
465         }
466
467         // Just stay around collecting statistics until we're done.
468         for ( ;; ) {
469                 unsigned long long sent, received;
470                 static unsigned long long last_sent = 0, last_received = 0;
471                 double recv_rate, send_rate;
472
473                 pthread_mutex_lock(&send_mutex);
474                 sent = total_bytes_sent;
475                 pthread_mutex_unlock(&send_mutex);
476                 
477                 pthread_mutex_lock(&receive_mutex);
478                 received = total_bytes_received;
479                 pthread_mutex_unlock(&receive_mutex);
480
481                 send_rate = (sent - last_sent) * 8.0 / 1048576.0;       
482                 recv_rate = (received - last_received) * 8.0 / 1048576.0;       
483                 
484                 printf("%12llu %12llu  %5.0f Mbit/sec  %5.0f Mbit/sec\n", sent, received,
485                         send_rate, recv_rate);
486
487                 last_sent = sent;
488                 last_received = received;
489
490                 sleep(1);
491         }
492
493         exit(0);
494 }