]> git.sesse.net Git - jam/blob - jam.c
Proper error handling for epoll, and some cleanup.
[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: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 void generate_new_sender(int ep_fd)
147 {
148         int sock, one = 1;
149         unsigned src_num, dst_num;
150         unsigned long long num_bytes;
151         struct sockaddr_in sin;
152         struct epoll_event ev;
153
154         sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
155         if (sock == -1) {
156                 perror("socket()");
157                 exit(1);
158         }
159
160         // find the right parameters
161         src_num = (unsigned)(num_sources * gen_uniform_random());
162         dst_num = (unsigned)(num_destinations * gen_uniform_random());
163         num_bytes = (unsigned)gen_pareto_random(1048576.0, 1.0);
164
165         // FIXME: bind to the right source
166
167         if (ioctl(sock, FIONBIO, &one) == -1) {
168                 perror("FIONBIO");
169                 exit(1);
170         }
171
172         sin.sin_family = AF_INET;
173         sin.sin_port = htons(port);
174         sin.sin_addr = destinations[dst_num];
175
176         // non-blocking connect (will be detected by epoll later)
177         if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1 && errno != EINPROGRESS) {
178                 perror("connect()");
179                 exit(1);
180         }
181         
182         // stick it in the epoll set (FIXME: make edge-triggered?)
183         ev.events = EPOLLOUT | EPOLLHUP | EPOLLERR;
184         ev.data.fd = sock;
185         ev.data.u64 = num_bytes;
186
187         if (epoll_ctl(ep_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
188                 perror("EPOLL_CTL_ADD");
189                 exit(1);
190         }
191 }
192
193 void *sender_worker(void *arg)
194 {
195         unsigned i;
196         char buf[65536];
197         unsigned long long bytes_sent = 0;
198         int ep_fd;
199         struct epoll_event *events;
200
201         ep_fd = epoll_create(num_sockets_per_sender);
202         if (ep_fd == -1) {
203                 perror("epoll_create");
204                 exit(1);
205         }
206
207         // malloc, since there might not be enough room on the stack
208         events = (struct epoll_event *)malloc(sizeof(struct epoll_event) * num_sockets_per_sender);
209         if (events == NULL) {
210                 perror("malloc");
211                 exit(1);
212         }
213
214         // fill the buffer with random junk
215         for (i = 0; i < 65536; ++i)
216                 buf[i] = rand() & 0xff;
217
218         // allocate all the senders
219         for (i = 0; i < num_sockets_per_sender; ++i)
220                 generate_new_sender(ep_fd);
221
222         for ( ;; ) {
223                 int num_active = epoll_wait(ep_fd, events, num_sockets_per_sender, -1);
224                 if (num_active == -1) {
225                         perror("epoll_wait");
226                         exit(1);
227                 }
228
229                 for (i = 0; i < num_active; ++i) {
230                         unsigned bytes_to_send = events[i].data.u64;
231                         unsigned ret;
232
233                         if (bytes_to_send > 65536) {
234                                 bytes_to_send = 65536;  
235                         }
236
237                         ret = send(events[i].data.fd, buf, bytes_to_send, MSG_NOSIGNAL);
238                         if (ret == -1) {
239                                 perror("send()");
240                                 exit(1);
241                         }
242
243                         events[i].data.u64 -= ret;
244                         bytes_sent += ret;
245
246                         // update the central counter after every 1MB (8ms
247                         // at gigabit speeds, should be enough) of sent data
248                         if (bytes_sent > 1048576) {
249                                 pthread_mutex_lock(&send_mutex);
250                                 total_bytes_sent += bytes_sent;
251                                 pthread_mutex_unlock(&send_mutex);
252
253                                 bytes_sent = 0;
254                         }
255                         
256                         if (events[i].data.u64 == 0) {
257                                 close(events[i].data.fd);
258                                 if (epoll_ctl(ep_fd, EPOLL_CTL_DEL, events[i].data.fd, NULL) == -1) {
259                                         perror("EPOLL_CTL_ADD");
260                                         exit(1);
261                                 }
262
263                                 generate_new_sender(ep_fd);
264                         }
265                 }
266         }
267
268         pthread_mutex_lock(&send_mutex);
269         total_bytes_sent += bytes_sent;
270         pthread_mutex_unlock(&send_mutex);
271
272         free(events);
273         close(ep_fd);
274
275         pthread_exit(0);
276 }
277
278 void *receiver_worker(void *arg)
279 {
280         int sock = (int)arg;
281         char buf[65536];
282         unsigned long long bytes_received = 0;
283
284         for ( ;; ) {
285                 int ret = read(sock, buf, 65536);
286                 if (ret == 0)
287                         break;
288
289                 bytes_received += ret;
290
291                 // update the central counter after every 1MB (8ms
292                 // at gigabit speeds, should be enough) of received data
293                 if (bytes_received > 1048576) {
294                         pthread_mutex_lock(&receive_mutex);
295                         total_bytes_received += bytes_received;
296                         pthread_mutex_unlock(&receive_mutex);
297
298                         bytes_received = 0;
299                 }
300         }
301         
302         if (close(sock) == -1) {
303                 perror("close()");
304                 exit(1);
305         }
306                         
307         pthread_mutex_lock(&receive_mutex);
308         total_bytes_received += bytes_received;
309         pthread_mutex_unlock(&receive_mutex);
310
311         pthread_exit(0);
312 }
313         
314 void *receiver_dispatcher(void *arg)
315 {
316         int server_sock = (int)arg;
317         pthread_attr_t attr;
318         
319         // FIXME: these do not really set errno
320         if (pthread_attr_init(&attr) != 0) {
321                 perror("pthread_attr_init()");
322                 exit(1);
323         }
324
325         if (pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 65536 + 0x4000) != 0) {
326                 perror("pthread_attr_setstacksize");
327                 exit(1);
328         }
329
330         if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
331                 perror("pthread_attr_setdetachstate");
332                 exit(1);
333         }
334
335         /*
336          * Listen for incoming connections, spawning off one receiver
337          * thread for each (which will just gobble up the data until
338          * we're done).
339          */
340         for ( ;; ) {
341                 struct sockaddr_in addr;
342                 socklen_t addr_len = sizeof(addr);
343                 pthread_t thread;
344
345                 int sock = accept(server_sock, (struct sockaddr *)&addr, &addr_len);
346                 if (sock == -1) {
347                         perror("accept()");
348                         exit(1);
349                 }
350
351                 if (pthread_create(&thread, &attr, receiver_worker, (void *)sock) != 0) {
352                         perror("pthread_create()");
353                         exit(1);
354                 }
355         }
356 }
357
358 int get_server_socket(unsigned short port)
359 {
360         int server_sock;
361         struct sockaddr_in sin;
362         unsigned one = 1;
363
364         server_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
365         if (server_sock == -1) {
366                 perror("socket()");
367                 exit(1);
368         }
369
370         if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
371                 perror("setsocket(SO_REUSEADDR)");
372                 exit(1);
373         }
374
375         sin.sin_family = AF_INET;
376         sin.sin_port = htons(port);
377         sin.sin_addr.s_addr = INADDR_ANY;
378
379         if (bind(server_sock, (struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) {
380                 perror("bind()");
381                 exit(1);
382         }
383
384         if (listen(server_sock, 255) == -1) {
385                 perror("listen()");
386                 exit(1);
387         }
388
389         return server_sock;
390 }
391
392 int main(int argc, char **argv)
393 {
394         int server_sock;
395         unsigned i;
396         pthread_attr_t attr;
397
398         parse_options(argc, argv);
399
400         if (destinations == NULL || sources == NULL) {
401                 fprintf(stderr, "Missing or empty source or destination host list. Aborting.\n");
402                 exit(1);
403         }
404
405         if (do_listen) {
406                 server_sock = get_server_socket(port);
407         }
408         
409         printf("Sending data on port %u from %u sources to %u destinations.\n\n",
410                 port, num_sources, num_destinations);
411                 
412         // FIXME: these do not really set errno
413         if (pthread_attr_init(&attr) != 0) {
414                 perror("pthread_attr_init()");
415                 exit(1);
416         }
417
418         if (pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 65536 + 0x4000) != 0) {
419                 perror("pthread_attr_setstacksize");
420                 exit(1);
421         }
422
423         if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
424                 perror("pthread_attr_setdetachstate");
425                 exit(1);
426         }
427                 
428         // Fire off the master receiver.
429         if (do_listen) {
430                 pthread_t thread;
431                 if (pthread_create(&thread, &attr, receiver_dispatcher, (void *)server_sock) != 0) {
432                         perror("pthread_create()");
433                         exit(1);
434                 }
435         }
436
437         printf("Waiting five seconds before starting senders...\n");
438         sleep(5);
439
440         // Fire off sender workers.
441         for (i = 0; i < num_senders; ++i) {
442                 pthread_t thread;
443                 
444                 if (pthread_create(&thread, &attr, sender_worker, NULL) != 0) {
445                         perror("pthread_create()");
446                         exit(1);
447                 }
448         }
449
450         // Just stay around collecting statistics until we're done.
451         for ( ;; ) {
452                 unsigned long long sent, received;
453                 static unsigned long long last_sent = 0, last_received = 0;
454                 double recv_rate, send_rate;
455
456                 pthread_mutex_lock(&send_mutex);
457                 sent = total_bytes_sent;
458                 pthread_mutex_unlock(&send_mutex);
459                 
460                 pthread_mutex_lock(&receive_mutex);
461                 received = total_bytes_received;
462                 pthread_mutex_unlock(&receive_mutex);
463
464                 send_rate = (sent - last_sent) * 8.0 / 1048576.0;       
465                 recv_rate = (received - last_received) * 8.0 / 1048576.0;       
466                 
467                 printf("%12llu %12llu  %5.0f Mbit/sec  %5.0f Mbit/sec\n", sent, received,
468                         send_rate, recv_rate);
469
470                 last_sent = sent;
471                 last_received = received;
472
473                 sleep(1);
474         }
475
476         exit(0);
477 }