]> rtime.felk.cvut.cz Git - frescor/fwp.git/blob - wme_test/wclient.c
Fixed bug in generated data files.
[frescor/fwp.git] / wme_test / wclient.c
1 #include <errno.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <netdb.h>
7 #include <signal.h>
8 #include <sys/wait.h>
9 #include <stdio.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <time.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <stdbool.h>
18 #include "common.h"
19 #include <semaphore.h>
20 #include <sys/ioctl.h>
21 #include <net/if.h>
22
23 #ifdef WITH_FWP
24 #include <fwp_proto.h>
25 #endif
26
27 #define MAX_STREAMS  10 
28 #define MIN_GRANULARITY 100
29
30 unsigned opt_packet_size = 800;
31 int opt_send_buf_size = -1;
32 unsigned opt_period_usec = 10*MSEC_TO_USEC;
33 char    *opt_interface;
34 unsigned opt_jitter = 0;
35 char    *opt_output = "delay_stats";
36 unsigned opt_count_sec = 0;
37 unsigned opt_def_bandwidth = 200;
38 unsigned opt_def_period_msec = 0;
39 int opt_granularity_usec = MIN_GRANULARITY;
40 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
41
42 bool some_queue_is_full = false;
43 struct timespec reset_timestamp;
44
45 /* Locked when some queue is full to prevent multiple resets of
46    statstics. */
47 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
48
49 int ac_sockfd[AC_NUM];
50
51 struct receiver {
52         pthread_t thread;
53         unsigned received, last_received;
54 } receivers[AC_NUM];
55
56 FILE* logfd;
57 char* server_addr; 
58 char logfname[100];
59
60 /* maximal traffic delay in ms - 10 s*/
61 #define MAX_DELAY_US 10000000
62
63 struct delay_stat {
64         unsigned csc;           /* Client-server-client delay divided by 2 */
65         unsigned cs;            /* Client-server delay */
66         unsigned sc;            /* Server-client delay */
67 };
68
69 struct delay_stat delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
70 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
71
72 /*struct ac_stats[AC_NUM] {
73    unsigned long int min_trans_time;
74    unsigned long int sum_trans_time;
75    struct timespec   recv_timestamp;
76    struct timespec   send_timestamp; 
77 };*/
78
79 struct stream {
80         /* Input parameters */
81         enum ac ac;             /*  */
82         int bandwidth_bps;      /* bits per second */
83         int jitter;             /* percent */
84         /* Mulualy exclusive input parameters */
85         int packet_size;
86         long period_usec;       /* all time units are in microseconds */
87
88         /* Internal fields */
89 #ifndef WITH_FWP
90         struct sockaddr_in rem_addr;
91 #else
92         int vres_id;
93 #endif
94
95         /* Statistics */
96         pthread_mutex_t mutex;
97         unsigned long long sent, really_sent, received;
98 };
99
100 static struct cmsg_ipi {
101         struct cmsghdr cm;
102         struct in_pktinfo ipi;
103 } cmsg = { {sizeof(struct cmsg_ipi), SOL_IP, IP_PKTINFO},
104            {0, }};
105 int cmsg_len = 0;
106
107 /*
108 struct send_endpoint sepoint[] = {
109         { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
110         { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps =  480*Kbit },
111         { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
112         { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
113 //      { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps =  675*Kbit },
114 };
115 */
116
117 struct stream streams[MAX_STREAMS];
118
119 unsigned int nr_streams = 0;
120
121 sem_t sem_thread_finished;
122
123 bool exit_flag = false;
124
125 #ifdef WITH_FWP
126 #define negotiate_contract_for_stream(s) negotiate_contract_for_stream_fwp(s)
127 #define create_stream_endpoint(s) create_stream_endpoint_fwp(s)
128 #define send_packet(s, b) send_packet_fwp(s, b)
129 #else
130 #define negotiate_contract_for_stream(s) 0
131 #define create_stream_endpoint(s) create_stream_endpoint_native(s)
132 #define send_packet(s, b) send_packet_native(s, b)
133 #endif
134
135 void stopper()
136 {
137         int i;
138         exit_flag = true;
139
140         /* Interrupt all receivers */
141         for (i=0; i < AC_NUM; i++) {
142                 pthread_kill(receivers[i].thread, SIGUSR1);
143         }
144 }
145
146 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
147 {
148         char buf[3][12];
149         char real[100];
150
151         if (useconds) {
152                 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
153                          bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
154                          stream->sent, stream->sent*SEC_TO_USEC/useconds,
155                          stream->received, stream->received*SEC_TO_USEC/useconds);
156         } else {
157                 real[0]=0;
158         }
159         
160         snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
161                  stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
162                  stream->packet_size, usec_to_text(buf[1], stream->period_usec),
163                  usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
164                  (int)(SEC_TO_USEC/stream->period_usec), real);
165 }
166
167 void save_results(int argc, char *argv[], int useconds)
168 {
169         int ac, i, maxi;
170         const int mini = 3000/opt_granularity_usec;
171         bool allzeros;
172         unsigned send_count[AC_NUM];
173
174         fprintf(stderr, "Writing data to %s... ", logfname);
175         fflush(stderr);
176
177         fprintf(logfd, "# Invoked as: ");
178         for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
179         fprintf(logfd, "\n");
180
181         if (useconds/SEC_TO_USEC != opt_count_sec) {
182                 char buf[20];
183                 usec_to_text(buf, useconds);
184                 fprintf(logfd, "# Data gathered for %s.\n", buf);
185         }
186                 
187         for (i = 0; i < nr_streams; i++) {
188                 char stream_desc[200];
189                 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
190                 fprintf(logfd, "# Stream %s\n", stream_desc);
191         }
192
193         /* Find maximal delay */
194         allzeros = true;
195         for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
196                 for (ac = 0; ac < AC_NUM; ac++) {
197                         if ((delay_stats[ac][maxi].csc != 0) ||
198                             (delay_stats[ac][maxi].cs != 0) ||
199                             (delay_stats[ac][maxi].sc != 0))
200                                 allzeros = false;
201                 }
202                 if (!allzeros) break;
203         }
204         maxi++;
205         if (maxi < mini) maxi = mini;
206
207         /* Calculate total number of sent packets per AC */
208         memset(send_count, 0, sizeof(send_count));
209         for (i = 0; i < nr_streams; i++) {
210                 ac = streams[i].ac;
211                 send_count[ac] += streams[i].sent;
212         }
213
214 #if 0
215         /* Write pdf */
216         for ( i = 0 ; i < maxi; i++) {
217                 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
218                 for (ac = 0; ac < AC_NUM; ac++) { 
219                         if (sum[ac])
220                                 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
221                         else val = -1; /* Don't display this ac */
222                         fprintf(logfd," %lf", val);
223                 }
224         }
225         
226         fprintf(logfd,"\n\n");
227 #endif
228         
229         fprintf(logfd,"## Format: msec csc%% cs%% sc%%\n");
230
231         /* Write PDF */
232         for (ac = 0; ac < AC_NUM; ac++) {
233                 struct delay_stat integral = {0,0,0}, last = {-1,-1,-1};
234
235                 fprintf(logfd,"%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);
236
237                 if (send_count[ac] != 0) {
238                         i=0;
239                         while ((delay_stats[ac][i].csc == 0) &&
240                                (delay_stats[ac][i].cs == 0) &&
241                                (delay_stats[ac][i].sc == 0)) i++;
242                 
243                         for (i++; i < maxi+1; i++) {
244                                 if (memcmp(&last, &integral, sizeof(last))) {
245                                         char buf[3][20];
246                                         snprintf(buf[0], sizeof(buf[0]), "%f", (double)integral.csc*100.0 / send_count[ac]);
247                                         snprintf(buf[1], sizeof(buf[1]), "%f", (double)integral.cs *100.0 / send_count[ac]);
248                                         snprintf(buf[2], sizeof(buf[2]), "%f", (double)integral.sc *100.0 / send_count[ac]);
249                                                  
250                                         fprintf(logfd,"%f %s %s %s\n", i*opt_granularity_usec/1000.0,
251                                                 integral.csc != last.csc ? buf[0] : "-",
252                                                 integral.cs  != last.cs  ? buf[1] : "-",
253                                                 integral.sc  != last.sc  ? buf[2] : "-"
254                                                 );
255                                         last = integral;
256                                 }
257                                 if (i>0) {
258                                         integral.csc += delay_stats[ac][i-1].csc;
259                                         integral.sc  += delay_stats[ac][i-1].sc;
260                                         integral.cs  += delay_stats[ac][i-1].cs;
261                                 }
262                         }
263                 }
264                 fprintf(logfd,"\n\n");
265         }
266         
267         fprintf(stderr, "finished.\n");
268         fclose(logfd);
269
270         exit(0);
271 }
272
273 int create_ac_socket(unsigned int ac) 
274 {
275         int sockfd;
276         unsigned int yes=1, tos;
277
278
279         if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
280         {
281                 perror("Unable to open socket");
282                 return -1;
283         }
284         if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
285                 perror("set non-blocking socket");
286                 return -1;
287         }
288         if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
289                 perror("Unable to set socket");
290                 return -1;
291         }
292
293         if (opt_send_buf_size >= 0) {
294                 if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&opt_send_buf_size,sizeof(opt_send_buf_size)) == -1) {
295                         perror("Unable to set socket buffer size");
296                         return -1;
297                 }
298         }
299
300         
301         //tos = ((AC_NUM - ac) *2 - 1)*32;
302         tos = ac_to_tos[ac];
303         if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
304                 perror("Unable to set TOS");
305                 close(sockfd);
306                 return -1;
307         }
308
309         return sockfd;
310 }
311
312 void empty_handler()
313 {
314 }
315
316 void reset_statistics()
317 {
318         int i;
319         for (i = 0; i < nr_streams; i++) {
320                 pthread_mutex_lock(&streams[i].mutex);
321                 streams[i].sent = 0;
322                 streams[i].really_sent = 0;
323                 streams[i].received = 0;
324                 pthread_mutex_unlock(&streams[i].mutex);
325         }
326         pthread_mutex_lock(&delay_stats_mutex);
327         clock_gettime(CLOCK_REALTIME, &reset_timestamp);
328         memset(delay_stats, 0, sizeof(delay_stats));
329         pthread_mutex_unlock(&delay_stats_mutex);
330 }
331
332 void* receiver(void* queue)
333 {
334         struct msg_t    msg;
335         struct  sockaddr_in rem_addr;
336         int     mlen, ret;
337         unsigned int ac, rem_addr_length; 
338         long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
339         long long int min_trans_time;
340         struct timespec send_timestamp, server_timestamp, recv_timestamp;
341         fd_set fdset;
342         
343         min_trans_time = ~0;
344         
345         block_signals();
346         set_rt_prio(99);
347
348         ac = (int)queue;
349         rem_addr_length = sizeof(rem_addr);
350         FD_ZERO(&fdset);
351         while (!exit_flag) {
352                 FD_SET(ac_sockfd[ac], &fdset);
353                 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
354                 if (ret < 0) {
355                         if (errno == EINTR) continue;
356                         perror("receiver select");
357                         goto out;
358                 }
359                 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,
360                                 (struct sockaddr*)&rem_addr, &rem_addr_length);
361                 if (mlen < 0) {
362                         perror("Chyba pri prijimani pozadavku");
363                         goto out;
364                 }       
365                 clock_gettime(CLOCK_REALTIME,&recv_timestamp);
366                 send_timestamp = msg.send_timestamp;
367                 server_timestamp = msg.sendback_timestamp;
368
369                 /* Check whether this message was sent after reset_statistics() */
370
371                 if ((ret = timespec_sub_usec(&send_timestamp, &reset_timestamp)) < 0) {
372                         continue; /* If so, don't count it */
373                 }
374
375                 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp) / 2;
376                 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
377                 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
378
379                 pthread_mutex_lock(&delay_stats_mutex);
380                 if (trans_time_usec < MAX_DELAY_US && trans_time_usec >= 0) {
381                         delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
382                 }
383                 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
384                         delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
385                 }
386                 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
387                         delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
388                 }
389                 pthread_mutex_unlock(&delay_stats_mutex);
390                 
391                 receivers[ac].received++;
392                 
393                 pthread_mutex_lock(&streams[msg.stream].mutex);
394                 streams[msg.stream].received++;
395                 pthread_mutex_unlock(&streams[msg.stream].mutex);
396         
397                 /*if (trans_time_nsec < min_trans_time) 
398                         min_trans_time = trans_time_nsec;*/
399                 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
400                          "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
401                          msg.seqn, msg.tos, send_timestamp.tv_sec,\
402                          send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
403                          recv_timestamp.tv_nsec, trans_time_msec); */
404         }
405 out:
406         sem_post(&sem_thread_finished);
407         return NULL;
408 }
409
410 /** 
411  * Send a packet.
412  * 
413  * @return -1 in case of error, 1 in case of sucessfull send and 0
414  *         when all buffers are full.
415  */
416 #ifndef WITH_FWP
417 static inline int 
418 send_packet_native(struct stream* stream, union msg_buff* buff)
419 {
420         struct iovec  iov;
421         struct msghdr msg;
422
423         iov.iov_base = buff;
424         iov.iov_len = stream->packet_size;
425         msg.msg_name = (void*)&stream->rem_addr;
426         msg.msg_namelen = sizeof(stream->rem_addr);
427         msg.msg_iov = &iov;
428         msg.msg_iovlen = 1;
429         msg.msg_flags = 0;
430         msg.msg_control = &cmsg;
431         msg.msg_controllen = cmsg_len;
432
433         int ret = 1;
434         
435         while (sendmsg(ac_sockfd[stream->ac], &msg, 0) < 0) {
436                 if (errno == EINTR) continue;
437                 if (errno == EAGAIN) {
438                         if (opt_wait_for_queue_is_full && 
439                             !some_queue_is_full && 
440                             /* We use mutex as atomic test and set */
441                             (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
442                                 some_queue_is_full = true;
443                                 reset_statistics();
444                         }
445                         ret = 0;
446                         break;
447                 } else {
448                         perror("Error while sending");
449                         ret = -1;
450                         break;
451                 }
452         }
453         return ret;
454 }
455 #else
456 static inline int 
457 send_packet_fwp(struct stream* stream, union msg_buff* buff)
458 {
459         int ret = 1;
460 /*      while (sendto(ac_sockfd[stream->ac], buff, stream->packet_size, 0, */
461 /*                    (struct sockaddr*)&stream->rem_addr, sizeof(stream->rem_addr)) < 0) { */
462 /*              if (errno == EINTR) continue; */
463 /*              if (errno == EAGAIN) { */
464 /*                      if (opt_wait_for_queue_is_full &&  */
465 /*                          !some_queue_is_full &&  */
466 /*                          /\* We use mutex as atomic test and set *\/ */
467 /*                          (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) { */
468 /*                              some_queue_is_full = true; */
469 /*                              reset_statistics(); */
470 /*                      } */
471 /*                      ret = 0; */
472 /*                      break; */
473 /*              } else { */
474 /*                      perror("Error while sending"); */
475 /*                      ret = -1; */
476 /*                      break; */
477 /*              } */
478 /*      } */
479         return ret;
480 }
481 #endif
482
483 static inline void
484 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
485 {
486         struct timespec time_to_wait, current_time, period, interval;
487         unsigned period_usec = stream->period_usec;
488
489         /*           |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
490         /* |-------------|     nominal period*/
491         if (stream->jitter) {
492                 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
493                                                + rand() % (2*period_usec*stream->jitter/100));
494         } else {
495                 period.tv_nsec = USEC_TO_NSEC*(period_usec);
496         }
497         period.tv_sec = 0;
498         
499         timespec_add(&time_to_wait, last_send_time, &period);
500         clock_gettime(CLOCK_REALTIME,&current_time);
501         timespec_sub(&interval,&time_to_wait,&current_time);
502         nanosleep(&interval,NULL);
503 }
504
505
506 void* sender(void* arg)
507 {
508         union msg_buff buff;
509         unsigned long int seqn;
510         struct stream* stream = (struct stream*) arg;
511         char stream_desc[100];
512         int ret;
513
514         stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
515         printf("%s\n", stream_desc);
516
517         if (stream->bandwidth_bps == 0)
518                 goto out;
519
520         seqn = 0;
521         
522         block_signals();
523         set_rt_prio(90-stream->ac);
524
525         while (!exit_flag) {
526
527 /*              buff.msg.seqn = seqn++; */
528 /*              buff.msg.tos = ac_to_tos[stream->ac]; */
529                 buff.msg.stream = stream-streams;
530                 
531                 clock_gettime(CLOCK_REALTIME,&buff.msg.send_timestamp);
532
533                 ret = send_packet(stream, &buff);
534                 if (ret < 0) {
535                         goto out;
536                 }
537
538                 pthread_mutex_lock(&stream->mutex);
539                 stream->sent++;
540                 if (ret > 0)
541                         stream->really_sent++;
542                 pthread_mutex_unlock(&stream->mutex);
543
544 #ifdef DEBUG
545                 printf("%d", stream->ac);
546                 fflush(stdout);
547 #endif
548
549                 wait_for_next_send(stream, &buff.msg.send_timestamp);
550         }
551 out:
552         sem_post(&sem_thread_finished);
553         return NULL;
554 }
555
556 #ifdef WITH_FWP
557 static int negotiate_contract_for_stream_fwp(struct stream *stream)
558 {
559         struct fwp_contract contract;
560         int vres_id;
561         int ret;
562
563         contract.budget = stream->packet_size;
564         contract.period_usec = stream->period_usec;
565         ret = fwp_contract_negotiate(&contract, &vres_id);
566         if (ret == 0) {
567                 if (contract.status == FWP_CNT_NEGOTIATED) {
568                         stream->vres_id = vres_id;
569                 } else {
570                         stream->vres_id = -1;
571                 }
572         }
573         return ret;
574 }
575 #endif
576
577 #ifdef WITH_FWP
578 static void create_stream_endpoint_fwp(struct stream *stream)
579 {
580         /* TODO: How to create an enpoint? */
581 }
582 #else
583 static void create_stream_endpoint_native(struct stream *stream)
584 {
585         struct hostent* ph;
586
587         memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
588
589         stream->rem_addr.sin_family = AF_INET;
590         ph = gethostbyname(server_addr);
591         if (ph)
592                 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
593         else {
594                 perror("Unknown server");
595                 exit(1);
596         }
597         stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
598 }
599 #endif
600
601 static inline void
602 calc_stream_params(struct stream *stream)
603 {
604         int packet_size;
605         unsigned period_usec;
606         int bandwidth;
607         int ret;
608
609         /* If some parameters are not set explicitely, use default values. */
610         if (stream->bandwidth_bps < 0) stream->bandwidth_bps = opt_def_bandwidth * Kbit;
611         if (stream->packet_size < 0) stream->packet_size = opt_packet_size;
612         if (stream->period_usec < 0) stream->period_usec = opt_def_period_msec * MSEC_TO_USEC;
613
614         bandwidth = stream->bandwidth_bps;
615
616         /* Avoid arithmetic exception. Server thread will exit if
617            stream->bandwidth_bps == 0. */
618         if (bandwidth == 0) bandwidth = 1;
619
620         if (stream->packet_size) {
621                 packet_size = stream->packet_size;
622                 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
623                 if (period_usec == 0) period_usec = 1;
624         } else if (stream->period_usec) {
625                 period_usec = stream->period_usec;
626                 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
627         } else {
628                 char buf[200];
629                 stream_to_text(buf, sizeof(buf), stream, 0);
630                 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
631                 exit(1);
632         }
633
634         if (packet_size < sizeof(struct msg_t)) {
635                 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
636                 exit(1);
637         }
638
639         stream->packet_size = packet_size;
640         stream->period_usec = period_usec;
641         stream->jitter = opt_jitter;
642
643         ret = negotiate_contract_for_stream(stream);
644         if (ret == 0) {
645                 create_stream_endpoint(stream);
646         } else {
647                 char buf[200];
648                 stream_to_text(buf, sizeof(buf), stream, 0);
649                 fprintf(stderr, "Contract hasn't been accepted: %s\n", buf);
650                 stream->bandwidth_bps = 0;
651         }
652 }
653
654 /** 
655  * Parse -b parameter.
656  * 
657  * @param params String to parse
658  * 
659  * @return NULL in case of success, pointer to a problematic character
660  *         on error.
661  */
662 char* parse_bandwidths(char *params)
663 {
664         struct stream *sp = &streams[nr_streams];
665
666         while (*params && nr_streams < MAX_STREAMS) {
667                 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
668                 int i;
669                 char *next_char;
670
671                 if (strlen(params) < 2)
672                         return params;
673                 for (i=0; i<AC_NUM; i++) {
674                         if (strncmp(params, ac_ids[i], 2) == 0) {
675                                 sp->ac = i;
676                                 params+=strlen(ac_ids[i]);
677                                 break;
678                         }
679                 }
680                 if (i==AC_NUM)
681                         return params;
682
683                 long bw;
684                 if (*params == ':') {
685                         params++;
686
687                         bw = strtol(params, &next_char, 10);
688                         if (next_char == params)
689                                 return params;
690                         params = next_char;
691                 } else
692                         bw = -1;
693                 
694                 sp->bandwidth_bps = bw*Kbit;
695
696                 long period = 0;
697                 long packet_size = 0;
698                 if (*params == '@') {
699                         params++;
700                         period = strtol(params, &next_char, 10);
701                         if (period == 0)
702                                 return params;
703                         params = next_char;
704                 }
705                 else {
706                         if (*params == '/') {
707                                 params++;
708                                 packet_size = strtol(params, &next_char, 10);
709                                 if (packet_size == 0)
710                                         return params;
711                                 params = next_char;
712                         } else {
713                                 packet_size = -1; 
714                                 period = -1;
715                         }
716                 }
717                 sp->period_usec = period*MSEC_TO_USEC;
718                 sp->packet_size = packet_size;
719
720                 
721
722                 if (*params != '\0' && *params != ',')
723                         return params;
724                 nr_streams++;
725                 sp++;
726                 if (*params == ',')
727                         params++;
728         }
729         return NULL;
730 }
731
732 int main(int argc, char *argv[])
733 {
734         int ac, i, rc, seconds;
735         pthread_attr_t attr;
736         pthread_t thread;
737         char opt;
738
739
740         while ((opt = getopt(argc, argv, "B:b:c:g:I:j:o:qQ:s:T:")) != -1) {
741                 switch (opt) {
742                         case 'B':
743                                 opt_def_bandwidth = atoi(optarg);
744                                 break;
745                         case 'b': {
746                                 char *error;
747                                 error = parse_bandwidths(optarg);
748                                 if (error != NULL) {
749                                         if (*error == '\0')
750                                                 fprintf(stderr, "Bandwidth parse error - string to short\n");
751                                         else
752                                                 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
753                                         exit(1);
754                                 }
755                                 break;
756                         }
757                         case 'c':
758                                 opt_count_sec = atoi(optarg);
759                                 break;
760                         case 'g':
761                                 opt_granularity_usec = atoi(optarg);
762                                 if (opt_granularity_usec < MIN_GRANULARITY) {
763                                         fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
764                                         exit(1);
765                                 }
766                                 break;
767                         case 'I':
768                                 opt_interface = optarg;
769                                 break;
770                         case 'j':
771                                 opt_jitter = atoi(optarg);
772                                 break;
773                         case 'o':
774                                 opt_output = optarg;
775                                 break;
776                         case 'Q':
777                                 opt_send_buf_size = atoi(optarg);
778                                 break;
779                         case 'q':
780                                 opt_wait_for_queue_is_full = true;
781                                 break;
782                         case 's':
783                                 opt_packet_size = atoi(optarg);
784                                 break;
785                         case 'T':
786                                 opt_def_period_msec = atoi(optarg);
787                                 break;
788                         default:
789                                 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
790                                 fprintf(stderr, "Options:\n");
791                                 fprintf(stderr, "    -B  default bandwidth for -b option [kbit]\n");
792                                 fprintf(stderr, "    -b  bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
793                                 fprintf(stderr, "    -c  count (number of seconds to run)\n");
794                                 fprintf(stderr, "    -g  histogram granularity [usec]\n");
795                                 fprintf(stderr, "    -I  <interface> send packets from this interface");
796                                 fprintf(stderr, "    -j  send jitter (0-100) [%%]\n");
797                                 fprintf(stderr, "    -o  output filename (.dat will be appended)\n");
798                                 fprintf(stderr, "    -q  gather statistics only after some queue becomes full\n");
799                                 fprintf(stderr, "    -Q  <bytes> set size for socket send buffers\n");
800                                 fprintf(stderr, "    -s  size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
801                                 fprintf(stderr, "    -T  default period for -b option [msec]\n");
802                                 exit(1);
803                 }
804         }
805         if (opt_packet_size && opt_def_period_msec) {
806                 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
807                 exit(1);
808         }
809
810         if (optind < argc) {
811                 server_addr = argv[optind];
812         } else {
813                 fprintf(stderr, "Expected server address argument\n");
814                 exit(1);
815         }
816
817         if (nr_streams == 0)
818                 parse_bandwidths("BE");
819                 
820         pthread_attr_init(&attr);
821
822         snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
823
824         if ((logfd = fopen(logfname,"w+")) == NULL) {
825                 fprintf(stderr,"Can not open %s\n", logfname);
826                 exit(1);
827         }
828         if (signal(SIGTERM, stopper) == SIG_ERR) {
829                 perror("Error in signal registration");
830                 exit(1);
831         }
832                 
833         if (signal(SIGINT, stopper) == SIG_ERR) {
834                 perror("Signal handler registration error");
835                 exit(1);
836         }
837
838         struct sigaction sa;
839         sa.sa_handler = empty_handler;
840         sa.sa_flags = 0;        /* don't restart syscalls */
841
842         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
843                 perror("sigaction error");
844                 exit(1);
845         }
846
847         sem_init(&sem_thread_finished, 0, 0);
848
849         reset_statistics();
850
851         /* create four receivers each per AC */
852         for (ac = AC_NUM - 1; ac >= 0; ac--) {
853                 ac_sockfd[ac] = create_ac_socket(ac);
854                 if (ac_sockfd[ac] < 0) {
855                         return 1;
856                 }
857                 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
858                 if (rc) {
859                         fprintf(stderr, "Error while creating receiver %d\n",rc);
860                         return 1;
861                 }
862         }               
863                         
864         if (opt_interface) {
865                 struct ifreq ifr;
866
867                 memset(&ifr, 0, sizeof(ifr));
868                 strncpy(ifr.ifr_name, opt_interface, IFNAMSIZ-1);
869                 if (ioctl(ac_sockfd[AC_VO], SIOCGIFINDEX, &ifr) < 0) {
870                         fprintf(stderr, "unknown iface %s\n", opt_interface);
871                         exit(1);
872                 }
873                 cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
874                 cmsg_len = sizeof(cmsg);
875         }
876         /* create sendpoints */
877         for (i = 0; i < nr_streams; i++) {
878                 struct stream *s = &streams[i];
879                 pthread_mutex_init(&s->mutex, NULL);
880                 calc_stream_params(s);
881                 rc = pthread_create(&thread, &attr, sender, (void*) s);
882                 if (rc) {
883                         fprintf(stderr, "Error while creating sender %d\n",rc);
884                         return 1;
885                 }
886         }
887         
888         seconds = 0;
889         while (!exit_flag) {
890                 sleep(1);
891                 seconds++;
892                 fprintf(stderr, "\r%3ds", seconds);
893                 for (ac = 0; ac < AC_NUM; ac++) {
894                         int delta = receivers[ac].received - receivers[ac].last_received;
895                         receivers[ac].last_received = receivers[ac].received;
896                         fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
897                 }
898                 fflush(stderr);
899                 if (seconds == opt_count_sec)
900                         stopper();
901         }
902
903         fprintf(stderr, "\nWaiting for threads to finish\n");
904         /* Wait for all threads to finish */
905         for (i=0; i < nr_streams + AC_NUM; i++) {
906                 sem_wait(&sem_thread_finished);
907         }
908         struct timespec end_timestamp, measure_length;
909         clock_gettime(CLOCK_REALTIME,&end_timestamp);
910         timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
911
912         save_results(argc, argv, timespec2usec(&measure_length));
913
914         return 0;
915 }