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