]> rtime.felk.cvut.cz Git - frescor/fwp.git/blob - wme_test/wclient.c
Added -q switch to reset statistics when some queue becomes full.
[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
21 #define MAX_STREAMS  10 
22 #define MIN_GRANULARITY 100
23
24 unsigned opt_packet_size = 800;
25 unsigned opt_period_usec = 10*MSEC_TO_USEC;
26 unsigned opt_jitter = 0;
27 char    *opt_output = "delay_stats";
28 unsigned opt_count_sec = 0;
29 unsigned opt_def_bandwidth = 200;
30 unsigned opt_def_period_msec = 0;
31 int opt_granularity_usec = MIN_GRANULARITY;
32 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
33
34 bool some_queue_is_full = false;
35
36 /* Locked when some queue is full to prevent multiple resets of
37    statstics. */
38 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
39
40 int ac_sockfd[AC_NUM];
41
42 struct receiver {
43         pthread_t thread;
44         unsigned received, last_received;
45 } receivers[AC_NUM];
46
47 FILE* logfd;
48 char* server_addr; 
49 char logfname[100];
50
51 /* maximal traffic delay in ms - 10 s*/
52 #define MAX_DELAY_US 10000000
53
54 unsigned delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
55
56 /*struct ac_stats[AC_NUM] {
57    unsigned long int min_trans_time;
58    unsigned long int sum_trans_time;
59    struct timespec   recv_timestamp;
60    struct timespec   send_timestamp; 
61 };*/
62
63 struct stream {
64         /* Input parameters */
65         enum ac ac;             /*  */
66         int bandwidth_bps;      /* bits per second */
67         int jitter;             /* percent */
68         /* Mulualy exclusive input parameters */
69         int packet_size;
70         long period_usec;       /* all time units are in microseconds */
71
72         /* Statistics */
73         unsigned long long sent, received;
74 };
75
76 /*
77 struct send_endpoint sepoint[] = {
78         { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
79         { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps =  480*Kbit },
80         { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
81         { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
82 //      { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps =  675*Kbit },
83 };
84 */
85
86 struct stream streams[MAX_STREAMS];
87
88 unsigned int nr_streams = 0;
89
90 sem_t sem_thread_finished;
91
92 bool exit_flag = false;
93
94 void stopper()
95 {
96         int i;
97         exit_flag = true;
98
99         /* Interrupt all receivers */
100         for (i=0; i < AC_NUM; i++) {
101                 pthread_kill(receivers[i].thread, SIGUSR1);
102         }
103 }
104
105 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, int seconds)
106 {
107         char buf[3][12];
108         char real[100];
109
110         if (seconds) {
111                 snprintf(real, sizeof(real), "; real: sent %lld (%lld/s), received %lld (%lld/s)",
112                          stream->sent, stream->sent/seconds,
113                          stream->received, stream->received/seconds);
114         }
115         
116         snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
117                  stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
118                  stream->packet_size, usec_to_text(buf[1], stream->period_usec),
119                  usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
120                  (int)(SEC_TO_USEC/stream->period_usec), real);
121 }
122
123 void save_results(int argc, char *argv[], int seconds)
124 {
125         int ac, i, maxi;
126         const int mini = 3000/opt_granularity_usec;
127         bool allzeros;
128         unsigned sum[AC_NUM];
129         double val;
130
131         fprintf(stderr, "Writing data to %s... ", logfname);
132         fflush(stderr);
133
134         fprintf(logfd, "# Invoked as: ");
135         for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
136         fprintf(logfd, "\n");
137
138         if (seconds != opt_count_sec) {
139                 fprintf(logfd, "# Data gathered for %d seconds.\n", seconds);
140         }
141                 
142         for (i = 0; i < nr_streams; i++) {
143                 char stream_desc[120];
144                 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], seconds);
145                 fprintf(logfd, "# Stream %s\n", stream_desc);
146         }
147
148         /* Find maximal delay */
149         allzeros = true;
150         for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
151                 for (ac = 0; ac < AC_NUM; ac++) {
152                         if (delay_stats[ac][maxi] != 0) allzeros = false;
153                 }
154                 if (!allzeros) break;
155         }
156         maxi++;
157         if (maxi < mini) maxi = mini;
158
159         /* Calculate total number of sent packets per AC */
160         for (ac = 0; ac < AC_NUM; ac++) sum[ac] = 0;
161         for (i = 0; i < nr_streams; i++) {
162                 ac = streams[i].ac;
163                 sum[ac] += streams[i].sent;
164         }
165
166 #if 0
167         /* Write pdf */
168         for ( i = 0 ; i < maxi; i++) {
169                 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
170                 for (ac = 0; ac < AC_NUM; ac++) { 
171                         if (sum[ac])
172                                 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
173                         else val = -1; /* Don't display this ac */
174                         fprintf(logfd," %lf", val);
175                 }
176         }
177         
178         fprintf(logfd,"\n\n");
179 #endif
180         
181         /* Write PDF */
182         for (ac = 0; ac < AC_NUM; ac++) {
183                 unsigned long long integral = 0, last = -1;
184
185                 fprintf(logfd,"%f %f\n", 0.0, 0.0);
186
187                 if (sum[ac] != 0) {
188                         i=0;
189                         while (delay_stats[ac][i] == 0) i++;
190                 
191                         for (i++; i < maxi+1; i++) {
192                                 if (last != integral) {
193                                         val = (double)integral*100.0 / sum[ac];
194                                         fprintf(logfd,"%f %f\n", i*opt_granularity_usec/1000.0, val);
195                                         last = integral;
196                                 }
197                                 if (i>0)
198                                         integral += delay_stats[ac][i-1];
199                         }
200                 }
201                 fprintf(logfd,"\n\n");
202         }
203         
204         fprintf(stderr, "finished.\n");
205         fclose(logfd);
206
207         exit(0);
208 }
209
210 static inline 
211 void timespec_add (struct timespec *sum, const struct timespec *left,
212               const struct timespec *right)
213 {
214         sum->tv_sec = left->tv_sec + right->tv_sec;
215         sum->tv_nsec = left->tv_nsec + right->tv_nsec;
216
217         if (sum->tv_nsec >= 1000000000){
218                 ++sum->tv_sec;
219                 sum->tv_nsec -= 1000000000;
220         }
221 }
222
223 static inline 
224 void timespec_sub (struct timespec *diff, const struct timespec *left,
225               const struct timespec *right)
226 {
227         diff->tv_sec = left->tv_sec - right->tv_sec;
228         diff->tv_nsec = left->tv_nsec - right->tv_nsec;
229
230         if (diff->tv_nsec < 0){
231                   --diff->tv_sec;
232                   diff->tv_nsec += 1000000000;
233         }
234 }
235
236 int create_ac_socket(unsigned int ac) 
237 {
238         int sockfd;
239         unsigned int yes=1, tos;
240
241
242         if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
243         {
244                 perror("Unable to open socket");
245                 return -1;
246         }
247         if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
248                 perror("set non-blocking socket");
249                 return -1;
250         }
251         if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
252                 perror("Unable to set socket");
253                 return -1;
254         }
255
256         
257         //tos = ((AC_NUM - ac) *2 - 1)*32;
258         tos = ac_to_tos[ac];
259         if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
260                 perror("Unable to set TOS");
261                 close(sockfd);
262                 return -1;
263         }
264
265         return sockfd;
266 }
267
268 void empty_handler()
269 {
270 }
271
272 void reset_statistics()
273 {
274         int i;
275         /* Mutexes??? */
276         printf("Reseting\n");
277         for (i = 0; i < nr_streams; i++) {
278                 streams[i].sent = 0;
279                 streams[i].received = 0;
280         }
281         memset(delay_stats, 0, sizeof(delay_stats));
282 }
283
284 void* receiver(void* queue)
285 {
286         struct msg_t    msg;
287         struct  sockaddr_in rem_addr;
288         int     mlen, ret;
289         unsigned int ac, rem_addr_length; 
290         unsigned long int trans_time_usec;
291         unsigned long int min_trans_time;
292         struct timespec   send_timestamp,recv_timestamp, trans_time;
293         fd_set fdset;
294         
295         min_trans_time = ~0;
296         
297         block_signals();
298         set_rt_prio(99);
299
300         ac = (int)queue;
301         rem_addr_length = sizeof(rem_addr);
302         FD_ZERO(&fdset);
303         while (!exit_flag) {
304                 FD_SET(ac_sockfd[ac], &fdset);
305                 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
306                 if (ret < 0) {
307                         if (errno == EINTR) continue;
308                         perror("receiver select");
309                         goto out;
310                 }
311                 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,    \
312                                 (struct sockaddr*)&rem_addr, &rem_addr_length);
313                 if (mlen < 0) {
314                         perror("Chyba pri prijimani pozadavku");
315                         goto out;
316                 }       
317                 clock_gettime(CLOCK_MONOTONIC,&recv_timestamp);
318                 send_timestamp = msg.send_timestamp;
319                 
320                 timespec_sub(&trans_time,&recv_timestamp ,&send_timestamp);
321                 trans_time_usec = (trans_time.tv_sec * SEC_TO_USEC + \
322                                          trans_time.tv_nsec / USEC_TO_NSEC) /2;
323           
324                 if (trans_time_usec < MAX_DELAY_US)
325                         delay_stats[ac][trans_time_usec/opt_granularity_usec]++;
326
327                 receivers[ac].received++;
328                 streams[msg.stream].received++;
329         
330                 /*if (trans_time_nsec < min_trans_time) 
331                         min_trans_time = trans_time_nsec;*/
332                 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
333                          "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
334                          msg.seqn, msg.tos, send_timestamp.tv_sec,\
335                          send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
336                          recv_timestamp.tv_nsec, trans_time_msec); */
337         }
338 out:
339         sem_post(&sem_thread_finished);
340         return NULL;
341 }
342
343 void* sender(void* arg)
344 {
345         struct sockaddr_in rem_addr;
346         union msg_buff buff;
347         unsigned long int seqn;
348         struct timespec time_to_wait, current_time, period, interval;
349         struct hostent* ph;
350         struct stream* stream = (struct stream*) arg;
351         int packet_size;
352         unsigned period_usec;
353         char stream_desc[100];
354
355         if (stream->bandwidth_bps == 0)
356                 goto out;
357
358         set_rt_prio(90-stream->ac);
359
360         if (stream->packet_size) {
361                 packet_size = stream->packet_size;
362                 period_usec = SEC_TO_USEC*packet_size*8/stream->bandwidth_bps;
363         } else if (stream->period_usec) {
364                 period_usec = stream->period_usec;
365                 packet_size = (long long)stream->bandwidth_bps/8 * period_usec/SEC_TO_USEC;
366         } else {
367                 char buf[200];
368                 stream_to_text(buf, sizeof(buf), stream, 0);
369                 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
370                 exit(1);
371         }
372         stream->packet_size = packet_size;
373         stream->period_usec = period_usec;
374         stream->jitter = opt_jitter;
375
376
377         stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
378
379         printf("%s\n", stream_desc);
380
381         if (packet_size < sizeof(struct msg_t)) {
382                 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
383                 exit(1);
384         }
385
386         
387         memset(&rem_addr,0, sizeof(rem_addr));
388                 
389         rem_addr.sin_family = AF_INET;
390         ph = gethostbyname(server_addr);
391         if (ph) 
392                 rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
393         else {
394                 perror("Unknown server");
395                 exit(1);
396         }
397         rem_addr.sin_port = htons(BASE_PORT + stream->ac);
398         seqn = 0;
399         
400         block_signals();
401
402         while (!exit_flag) {
403
404                 buff.msg.seqn = seqn;
405                 buff.msg.tos = ac_to_tos[stream->ac];
406                 buff.msg.stream = stream-streams;
407                 
408                 clock_gettime(CLOCK_MONOTONIC,&buff.msg.send_timestamp);
409
410                 while (sendto(ac_sockfd[stream->ac], &buff, packet_size, 0,\
411                                 (struct sockaddr*)&rem_addr, sizeof(rem_addr)) < 0) {
412                                 if (errno == EINTR) continue;
413                                 if (errno == EAGAIN) {
414                                         if (!some_queue_is_full && (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
415                                                 some_queue_is_full = true;
416                                                 reset_statistics();
417                                         }
418
419                                         break;
420                                 } else {
421                                         perror("Error while sending");
422                                         goto out;
423                                 }
424                 }
425
426 #ifdef DEBUG
427                 printf("%d", ac);
428                 fflush(stdout);
429 #endif
430                 seqn++;
431                 stream->sent++;
432
433                 /*           |~~~+~~~| jitter interval (width = 2*opt_jitter percentage from period)*/
434                 /* |-------------|     nominal period*/
435                 if (opt_jitter) {
436                         period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-opt_jitter)/100
437                                                  + rand() % (2*period_usec*opt_jitter/100));
438                 } else {
439                         period.tv_nsec = USEC_TO_NSEC*(period_usec);
440                 }
441                 period.tv_sec = 0;
442
443                 timespec_add(&time_to_wait,&buff.msg.send_timestamp,&period);
444                 clock_gettime(CLOCK_MONOTONIC,&current_time);
445                 timespec_sub(&interval,&time_to_wait,&current_time);
446                 nanosleep(&interval,NULL);
447         }
448 out:
449         sem_post(&sem_thread_finished);
450         return NULL;
451 }
452
453 char* parse_bandwidths(char *params)
454 {
455         struct stream *sp = &streams[nr_streams];
456
457         while (*params && nr_streams < MAX_STREAMS) {
458                 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
459                 int i;
460                 char *next_char;
461
462                 if (strlen(params) < 2)
463                         return params;
464                 for (i=0; i<AC_NUM; i++) {
465                         if (strncmp(params, ac_ids[i], 2) == 0) {
466                                 sp->ac = i;
467                                 params+=strlen(ac_ids[i]);
468                                 break;
469                         }
470                 }
471                 if (i==AC_NUM)
472                         return params;
473
474                 long bw;
475                 if (*params == ':') {
476                         params++;
477
478                         bw = strtol(params, &next_char, 10);
479                         if (next_char == params)
480                                 return params;
481                         params = next_char;
482                 } else
483                         bw = opt_def_bandwidth;
484                 
485                 sp->bandwidth_bps = bw*Kbit;
486
487                 long period = 0;
488                 long packet_size = 0;
489                 if (*params == '@') {
490                         params++;
491                         period = strtol(params, &next_char, 10);
492                         if (period == 0)
493                                 return params;
494                         params = next_char;
495                 }
496                 else {
497                         if (*params == '/') {
498                                 params++;
499                                 packet_size = strtol(params, &next_char, 10);
500                                 if (packet_size == 0)
501                                         return params;
502                                 params = next_char;
503                         } else {
504                                 packet_size = opt_packet_size;
505                                 period = opt_def_period_msec;
506                         }
507                 }
508                 sp->period_usec = period*MSEC_TO_USEC;
509                 sp->packet_size = packet_size;
510
511                 
512
513                 if (*params != '\0' && *params != ',')
514                         return params;
515                 nr_streams++;
516                 sp++;
517                 if (*params == ',')
518                         params++;
519         }
520         return NULL;
521 }
522
523 int main(int argc, char *argv[])
524 {
525         int ac, i, rc, seconds, seconds_start;
526         pthread_attr_t attr;
527         pthread_t thread;
528         char opt;
529
530
531         while ((opt = getopt(argc, argv, "B:b:c:g:j:o:qs:T:")) != -1) {
532                 switch (opt) {
533                         case 'B':
534                                 opt_def_bandwidth = atoi(optarg);
535                                 break;
536                         case 'b': {
537                                 char *error;
538                                 error = parse_bandwidths(optarg);
539                                 if (error != NULL) {
540                                         if (*error == '\0')
541                                                 fprintf(stderr, "Bandwidth parse error - string to short\n");
542                                         else
543                                                 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
544                                         exit(1);
545                                 }
546                                 break;
547                         }
548                         case 'c':
549                                 opt_count_sec = atoi(optarg);
550                                 break;
551                         case 'g':
552                                 opt_granularity_usec = atoi(optarg);
553                                 if (opt_granularity_usec < MIN_GRANULARITY) {
554                                         fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
555                                         exit(1);
556                                 }
557                                 break;
558                         case 'j':
559                                 opt_jitter = atoi(optarg);
560                                 break;
561                         case 'o':
562                                 opt_output = optarg;
563                                 break;
564                         case 'q':
565                                 opt_wait_for_queue_is_full = true;
566                                 break;
567                         case 's':
568                                 opt_packet_size = atoi(optarg);
569                                 break;
570                         case 'T':
571                                 opt_def_period_msec = atoi(optarg);
572                                 break;
573                         default:
574                                 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
575                                 fprintf(stderr, "Options:\n");
576                                 fprintf(stderr, "    -B  default bandwidth for -b option [kbit]\n");
577                                 fprintf(stderr, "    -b  bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
578                                 fprintf(stderr, "    -c  count (number of seconds to run)\n");
579                                 fprintf(stderr, "    -g  histogram granularity [usec]\n");
580                                 fprintf(stderr, "    -j  send jitter (0-100) [%%]\n");
581                                 fprintf(stderr, "    -o  output filename (.dat will be appended)\n");
582                                 fprintf(stderr, "    -q  gather statistics only after some queue becomes full\n");
583                                 fprintf(stderr, "    -s  size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
584                                 fprintf(stderr, "    -T  default period for -b option [msec]\n");
585                                 exit(1);
586                 }
587         }
588         if (opt_packet_size && opt_def_period_msec) {
589                 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
590                 exit(1);
591         }
592
593         if (optind < argc) {
594                 server_addr = argv[optind];
595         } else {
596                 fprintf(stderr, "Expected server address argument\n");
597                 exit(1);
598         }
599
600
601         if (nr_streams == 0)
602                 parse_bandwidths("BE");
603                 
604         memset(delay_stats,0, sizeof(delay_stats));     
605         pthread_attr_init(&attr);
606
607         snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
608
609         if ((logfd = fopen(logfname,"w+")) == NULL) {
610                 fprintf(stderr,"Can not open %s\n", logfname);
611                 exit(1);
612         }
613         if (signal(SIGTERM, stopper) == SIG_ERR) {
614                 perror("Error in signal registration");
615                 exit(1);
616         }
617                 
618         if (signal(SIGINT, stopper) == SIG_ERR) {
619                 perror("Signal handler registration error");
620                 exit(1);
621         }
622
623         struct sigaction sa;
624         sa.sa_handler = empty_handler;
625         sa.sa_flags = 0;        /* don't restart syscalls */
626
627         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
628                 perror("sigaction error");
629                 exit(1);
630         }
631
632         sem_init(&sem_thread_finished, 0, 0);
633
634         /* create four receivers each per AC */
635         for (ac = AC_NUM - 1; ac >= 0; ac--) {
636                 ac_sockfd[ac] = create_ac_socket(ac);
637                 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
638                 if (rc) {
639                         fprintf(stderr, "Error while creating receiver %d\n",rc);
640                         return 1;
641                 }
642         }               
643                         
644         /* create sendpoints */
645         for (i = 0; i < nr_streams; i++) {
646                 rc = pthread_create(&thread, &attr, sender, (void*) &streams[i]);
647                 if (rc) {
648                         fprintf(stderr, "Error while creating sender %d\n",rc);
649                         return 1;
650                 }
651         }
652         
653         seconds = 0;
654         seconds_start = -1;
655         while (!exit_flag) {
656                 sleep(1);
657                 seconds++;
658                 if (opt_wait_for_queue_is_full) {
659                         if (some_queue_is_full && seconds_start == -1) {
660                                 printf("\nSome queue is full\n");
661                                 seconds_start = seconds;
662                         }
663                 }
664                 fprintf(stderr, "\r%3ds", seconds);
665                 for (ac = 0; ac < AC_NUM; ac++) {
666                         int delta = receivers[ac].received - receivers[ac].last_received;
667                         receivers[ac].last_received = receivers[ac].received;
668                         fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
669                 }
670                 fflush(stderr);
671                 if (seconds == opt_count_sec)
672                         stopper();
673         }
674
675         fprintf(stderr, "\nWaiting for threads to finish\n");
676         /* Wait for all threads to finish */
677         for (i=0; i < nr_streams + AC_NUM; i++) {
678                 sem_wait(&sem_thread_finished);
679         }
680
681         if (seconds_start == -1) seconds_start=0;
682         save_results(argc, argv, seconds-seconds_start);
683
684         return 0;
685 }