]> rtime.felk.cvut.cz Git - frescor/fwp.git/blob - wme_test/wclient.c
wme_test: GUI may be enabled in both FRSH/non-FRSH version by -G switch
[frescor/fwp.git] / wme_test / wclient.c
1 #include <errno.h>
2 #include <error.h>
3 #include <sys/types.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <arpa/inet.h>
7 #include <netdb.h>
8 #include <signal.h>
9 #include <sys/wait.h>
10 #include <stdio.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <time.h>
14 #include <string.h>
15 #include <pthread.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include "common.h"
20 #include <semaphore.h>
21 #include <sys/ioctl.h>
22 #include <net/if.h>
23 #include <inttypes.h>
24 #include <ncurses.h>
25
26 #ifdef WITH_FWP
27 #include <frsh.h>
28 #include <fwp_res.h>
29
30 /* static UL_LOG_CUST(ulogd); */
31 /* static ul_log_domain_t ulogd = {UL_LOGL_MSG, "wclient"}; */
32 /* UL_LOGREG_SINGLE_DOMAIN_INIT_FUNCTION(init_ulogd_wclient, ulogd); */
33
34 #endif
35
36 #define MAX_STREAMS  10 
37 #define MIN_GRANULARITY 100
38
39 unsigned opt_packet_size = 800;
40 int opt_send_buf_size = -1;
41 unsigned opt_period_usec = 10*MSEC_TO_USEC;
42 char    *opt_interface;
43 unsigned opt_jitter = 0;
44 char    *opt_output = "delay_stats";
45 unsigned opt_count_sec = 0;
46 unsigned opt_def_bandwidth = 50;
47 unsigned opt_def_period_msec = 0;
48 int opt_granularity_usec = MIN_GRANULARITY;
49 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
50 char *opt_comment = NULL;
51 bool opt_gui = false;
52
53 bool some_queue_is_full = false;
54 uint64_t reset_timestamp; /* [nsec] */
55
56 bool some_contract_not_accepted = false;
57
58 /* Locked when some queue is full to prevent multiple resets of
59    statstics. */
60 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
61
62 int ac_sockfd[AC_NUM];
63
64 struct receiver {
65         bool valid;
66         pthread_t thread;
67         unsigned received, last_received;
68 };
69
70 struct receiver receivers[AC_NUM];
71
72 FILE* logfd;
73 char* server_addr; 
74 char logfname[100];
75
76 /* maximal traffic delay in ms - 10 s*/
77 #define MAX_DELAY_US 10000000
78
79 struct delay_stat {
80         unsigned csc;           /* Client-server-client delay divided by 2 */
81         unsigned cs;            /* Client-server delay */
82         unsigned sc;            /* Server-client delay */
83 };
84
85 struct delay_stat delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
86 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
87
88 /*struct ac_stats[AC_NUM] {
89    unsigned long int min_trans_time;
90    unsigned long int sum_trans_time;
91    struct timespec   recv_timestamp;
92    struct timespec   send_timestamp; 
93 };*/
94
95 struct stream {
96         /* Input parameters */
97         enum ac ac;             /*  */
98         int bandwidth_bps;      /* bits per second */
99         int jitter;             /* percent */
100         /* Mulualy exclusive input parameters */
101         int packet_size;
102         long period_usec;       /* all time units are in microseconds */
103
104         /* Internal fields */
105 #ifndef WITH_FWP
106         struct sockaddr_in rem_addr;
107 #else
108         frsh_send_endpoint_t endpoint;
109         frsh_receive_endpoint_t resp_endpoint;
110         frsh_vres_id_t vres, vres_rcv;
111         uint16_t resp_port;
112         struct receiver receiver;
113 #endif
114
115         /* Statistics */
116         pthread_mutex_t mutex;
117         unsigned long long sent, really_sent, received;
118         long wc_delay;          /* worst-case delay  */
119 };
120
121 static struct cmsg_ipi {
122         struct cmsghdr cm;
123         struct in_pktinfo ipi;
124 } cmsg = { {sizeof(struct cmsg_ipi), SOL_IP, IP_PKTINFO},
125            {0, }};
126 int cmsg_len = 0;
127
128 /*
129 struct send_endpoint sepoint[] = {
130         { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
131         { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps =  480*Kbit },
132         { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
133         { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
134 //      { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps =  675*Kbit },
135 };
136 */
137
138 struct stream streams[MAX_STREAMS];
139
140 unsigned int nr_streams = 0;
141
142 sem_t sem_thread_finished;
143
144 bool exit_flag = false;
145
146 #ifdef WITH_FWP
147 #define negotiate_contract_for_stream(s) negotiate_contract_for_stream_fwp(s)
148 #define create_stream_endpoint(s) create_stream_endpoint_fwp(s)
149 #define send_packet(s, b) send_packet_fwp(s, b)
150 #define recv_packet(s, b) recv_packet_fwp(s, b)
151 #define wait_for_all_threads_to_finish() wait_for_all_threads_to_finish_fwp()
152 #else
153 #define negotiate_contract_for_stream(s) 0
154 #define create_stream_endpoint(s) create_stream_endpoint_native(s)
155 #define send_packet(s, b) send_packet_native(s, b)
156 #define recv_packet(s, b) recv_packet_native(s, b)
157 #define wait_for_all_threads_to_finish() wait_for_all_threads_to_finish_native()
158 #endif
159
160 void stopper()
161 {
162         int i;
163         exit_flag = true;
164
165         /* Interrupt all receivers */
166 #ifdef WITH_FWP
167         for (i=0; i < nr_streams; i++) {
168                 if (streams[i].receiver.valid) pthread_kill(streams[i].receiver.thread, SIGUSR1);
169         }
170 #else
171         for (i=0; i < AC_NUM; i++) {
172                 pthread_kill(receivers[i].thread, SIGUSR1);
173         }       
174 #endif
175 }
176
177 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
178 {
179         char buf[3][12];
180         char real[100];
181
182         if (useconds) {
183                 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
184                          bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
185                          stream->sent, stream->sent*SEC_TO_USEC/useconds,
186                          stream->received, stream->received*SEC_TO_USEC/useconds);
187         } else {
188                 real[0]=0;
189         }
190         
191         snprintf(stream_desc, n, "%"PRIdPTR": %s %s (%d bytes per %s +-%s, %d packets/s)%s",
192                  stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
193                  stream->packet_size, usec_to_text(buf[1], stream->period_usec),
194                  usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
195                  (int)(SEC_TO_USEC/stream->period_usec), real);
196 }
197
198 void save_results(int argc, char *argv[], int useconds)
199 {
200         int ac, i, maxi;
201         const int mini = 3000/opt_granularity_usec;
202         bool allzeros;
203         unsigned send_count[AC_NUM];
204
205         fprintf(stderr, "Writing data to %s... ", logfname);
206         fflush(stderr);
207
208         fprintf(logfd, "# Invoked as: ");
209         for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
210         if (opt_comment) {
211                 fprintf(logfd, "(%s)", opt_comment);
212         }
213         fprintf(logfd, "\n");
214
215         if (useconds/SEC_TO_USEC != opt_count_sec) {
216                 char buf[20];
217                 usec_to_text(buf, useconds);
218                 fprintf(logfd, "# Data gathered for %s.\n", buf);
219         }
220                 
221         for (i = 0; i < nr_streams; i++) {
222                 char stream_desc[200];
223                 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
224                 fprintf(logfd, "# Stream %s\n", stream_desc);
225         }
226
227         /* Find maximal delay */
228         allzeros = true;
229         for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
230                 for (ac = 0; ac < AC_NUM; ac++) {
231                         if ((delay_stats[ac][maxi].csc != 0) ||
232                             (delay_stats[ac][maxi].cs != 0) ||
233                             (delay_stats[ac][maxi].sc != 0))
234                                 allzeros = false;
235                 }
236                 if (!allzeros) break;
237         }
238         maxi++;
239         if (maxi < mini) maxi = mini;
240
241         /* Calculate total number of sent packets per AC */
242         memset(send_count, 0, sizeof(send_count));
243         for (i = 0; i < nr_streams; i++) {
244                 ac = streams[i].ac;
245                 send_count[ac] += streams[i].sent;
246         }
247
248 #if 0
249         /* Write pdf */
250         for ( i = 0 ; i < maxi; i++) {
251                 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
252                 for (ac = 0; ac < AC_NUM; ac++) { 
253                         if (sum[ac])
254                                 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
255                         else val = -1; /* Don't display this ac */
256                         fprintf(logfd," %lf", val);
257                 }
258         }
259         
260         fprintf(logfd,"\n\n");
261 #endif
262         
263         fprintf(logfd,"## Format: msec csc%% cs%% sc%%\n");
264
265         /* Write PDF */
266         for (ac = 0; ac < AC_NUM; ac++) {
267                 struct delay_stat integral = {0,0,0}, last = {-1,-1,-1};
268
269                 fprintf(logfd,"%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);
270
271                 if (send_count[ac] != 0) {
272                         i=0;
273                         while ((delay_stats[ac][i].csc == 0) &&
274                                (delay_stats[ac][i].cs == 0) &&
275                                (delay_stats[ac][i].sc == 0)) i++;
276                 
277                         for (i++; i < maxi+1; i++) {
278                                 if (memcmp(&last, &integral, sizeof(last))) {
279                                         char buf[3][20];
280                                         snprintf(buf[0], sizeof(buf[0]), "%f", (double)integral.csc*100.0 / send_count[ac]);
281                                         snprintf(buf[1], sizeof(buf[1]), "%f", (double)integral.cs *100.0 / send_count[ac]);
282                                         snprintf(buf[2], sizeof(buf[2]), "%f", (double)integral.sc *100.0 / send_count[ac]);
283                                                  
284                                         fprintf(logfd,"%f %s %s %s\n", i*opt_granularity_usec/1000.0,
285                                                 integral.csc != last.csc ? buf[0] : "-",
286                                                 integral.cs  != last.cs  ? buf[1] : "-",
287                                                 integral.sc  != last.sc  ? buf[2] : "-"
288                                                 );
289                                         last = integral;
290                                 }
291                                 if (i>0) {
292                                         integral.csc += delay_stats[ac][i-1].csc;
293                                         integral.sc  += delay_stats[ac][i-1].sc;
294                                         integral.cs  += delay_stats[ac][i-1].cs;
295                                 }
296                         }
297                 }
298                 fprintf(logfd,"\n\n");
299         }
300         
301         fprintf(stderr, "finished.\n");
302         fclose(logfd);
303
304         exit(0);
305 }
306
307 int create_ac_socket(intptr_t ac) 
308 {
309         int sockfd;
310         unsigned int yes=1, tos;
311
312
313         if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
314         {
315                 error(0, errno, "Unable to open socket");
316                 return -1;
317         }
318         if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
319                 error(0, errno, "set non-blocking socket");
320                 return -1;
321         }
322         if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
323                 error(0, errno, "Unable to set socket");
324                 return -1;
325         }
326
327         if (opt_send_buf_size >= 0) {
328                 if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&opt_send_buf_size,sizeof(opt_send_buf_size)) == -1) {
329                         error(0, errno, "Unable to set socket buffer size");
330                         return -1;
331                 }
332         }
333
334         
335         //tos = ((AC_NUM - ac) *2 - 1)*32;
336         tos = ac_to_tos[ac];
337         if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
338                 error(0, errno, "Unable to set TOS");
339                 close(sockfd);
340                 return -1;
341         }
342
343         return sockfd;
344 }
345
346 void empty_handler()
347 {
348 }
349
350 void reset_statistics()
351 {
352         int i;
353         struct timespec ts;
354         for (i = 0; i < nr_streams; i++) {
355                 pthread_mutex_lock(&streams[i].mutex);
356                 streams[i].sent = 0;
357                 streams[i].really_sent = 0;
358                 streams[i].received = 0;
359                 pthread_mutex_unlock(&streams[i].mutex);
360         }
361         pthread_mutex_lock(&delay_stats_mutex);
362         clock_gettime(CLOCK_REALTIME, &ts);
363         reset_timestamp = ts.tv_sec*1000000000LL + ts.tv_nsec;
364         memset(delay_stats, 0, sizeof(delay_stats));
365         pthread_mutex_unlock(&delay_stats_mutex);
366 }
367
368 #ifndef WITH_FWP
369 int recv_packet_native(intptr_t ac, struct msg_t *msg)
370 {
371         int     mlen, ret;
372         fd_set fdset;
373         struct  sockaddr_in rem_addr;
374         unsigned int rem_addr_length; 
375
376         FD_ZERO(&fdset);
377         FD_SET(ac_sockfd[ac], &fdset);
378         rem_addr_length = sizeof(rem_addr);
379         mlen = -1;
380         while (!exit_flag) {
381                 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
382                 if (ret < 0) {
383                         if (errno == EINTR) continue;
384                         error(0, errno, "receiver select");
385                         return -1;
386                 }
387                 mlen = recvfrom(ac_sockfd[ac], msg, sizeof(*msg), 0,
388                                 (struct sockaddr*)&rem_addr, &rem_addr_length);
389                 break;
390         }
391         return mlen;
392 }
393 #else
394 int recv_packet_fwp(struct stream *stream, struct msg_t *msg)
395 {
396         size_t mlen;
397
398         mlen = frsh_receive_sync(stream->resp_endpoint, msg, sizeof(*msg), &mlen, NULL);
399         return mlen;
400 }
401 #endif
402
403 void* receiver(void* arg)
404 {
405         struct msg_t    msg;
406         long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
407         long long int min_trans_time;
408         struct timespec ts;
409         uint64_t send_timestamp, server_timestamp, recv_timestamp;
410         int     mlen;
411         intptr_t ac;
412         
413         min_trans_time = ~0;
414         
415         block_signals();
416         set_rt_prio(99);
417
418         while (!exit_flag) {
419 #ifdef WITH_FWP
420                 struct stream *stream = arg;
421                 ac = stream->ac;
422                 mlen = recv_packet_fwp(stream, &msg);
423 #else
424                 ac = (intptr_t)arg;
425                 mlen = recv_packet_native(ac, &msg);
426 #endif
427                 if (mlen < 0) {
428                         if (errno != EINTR)
429                                 error(0, errno, "receive_packet error");
430                         goto out;
431                 }       
432                 clock_gettime(CLOCK_REALTIME,&ts);
433                 recv_timestamp = ts.tv_sec*1000000000LL + ts.tv_nsec;
434                 send_timestamp = msg.send_timestamp;
435                 server_timestamp = msg.sendback_timestamp;
436
437                 /* Check whether this message was sent after reset_statistics() */
438
439                 if (send_timestamp < reset_timestamp) {
440                         continue; /* If so, don't count it */
441                 }
442
443                 trans_time_usec = (recv_timestamp - send_timestamp) / 2 / 1000;
444                 client_to_server_usec = (server_timestamp - send_timestamp) / 1000;
445                 server_to_client_usec = (recv_timestamp - server_timestamp) / 1000;
446
447                 pthread_mutex_lock(&delay_stats_mutex);
448                 if (trans_time_usec < MAX_DELAY_US && trans_time_usec >= 0) {
449                         delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
450                 }
451                 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
452                         delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
453                 }
454                 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
455                         delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
456                 }
457                 pthread_mutex_unlock(&delay_stats_mutex);
458
459                 if (trans_time_usec > streams[msg.stream].wc_delay) {
460                         streams[msg.stream].wc_delay = trans_time_usec;
461                 }
462                 receivers[ac].received++;
463                 
464                 pthread_mutex_lock(&streams[msg.stream].mutex);
465                 streams[msg.stream].received++;
466                 pthread_mutex_unlock(&streams[msg.stream].mutex);
467         
468                 /*if (trans_time_nsec < min_trans_time) 
469                         min_trans_time = trans_time_nsec;*/
470                 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
471                          "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
472                          msg.seqn, msg.tos, send_timestamp.tv_sec,\
473                          send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
474                          recv_timestamp.tv_nsec, trans_time_msec); */
475         }
476 out:
477         sem_post(&sem_thread_finished);
478         return NULL;
479 }
480
481 /** 
482  * Send a packet.
483  * 
484  * @return -1 in case of error, 1 in case of sucessfull send and 0
485  *         when all buffers are full.
486  */
487 #ifndef WITH_FWP
488 static inline int 
489 send_packet_native(struct stream* stream, union msg_buff* buff)
490 {
491         struct iovec  iov;
492         struct msghdr msg;
493
494         iov.iov_base = buff;
495         iov.iov_len = stream->packet_size;
496         msg.msg_name = (void*)&stream->rem_addr;
497         msg.msg_namelen = sizeof(stream->rem_addr);
498         msg.msg_iov = &iov;
499         msg.msg_iovlen = 1;
500         msg.msg_flags = 0;
501         msg.msg_control = &cmsg;
502         msg.msg_controllen = cmsg_len;
503
504         int ret = 1;
505         
506         while (sendmsg(ac_sockfd[stream->ac], &msg, 0) < 0) {
507                 if (errno == EINTR) continue;
508                 if (errno == EAGAIN) {
509                         if (opt_wait_for_queue_is_full && 
510                             !some_queue_is_full && 
511                             /* We use mutex as atomic test and set */
512                             (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
513                                 some_queue_is_full = true;
514                                 reset_statistics();
515                         }
516                         ret = 0;
517                         break;
518                 } else {
519                         error(0, errno, "Error while sending");
520                         ret = -1;
521                         break;
522                 }
523         }
524         return ret;
525 }
526 #else
527 static inline int 
528 send_packet_fwp(struct stream* stream, union msg_buff* buff)
529 {
530         int ret = 0;
531
532         buff->msg.resp_port = htons(stream->resp_port);
533         ret = frsh_send_sync(stream->endpoint, buff, stream->packet_size);
534         return (ret == 0) ? 0 : -1;
535 }
536 #endif
537
538 static inline void
539 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
540 {
541         struct timespec time_to_wait, current_time, period, interval;
542         unsigned period_usec = stream->period_usec;
543
544         /*           |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
545         /* |-------------|     nominal period*/
546         if (stream->jitter) {
547                 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
548                                                + rand() % (2*period_usec*stream->jitter/100));
549         } else {
550                 period.tv_nsec = USEC_TO_NSEC*(period_usec);
551         }
552         period.tv_sec = 0;
553         
554         timespec_add(&time_to_wait, last_send_time, &period);
555         clock_gettime(CLOCK_REALTIME,&current_time);
556         timespec_sub(&interval,&time_to_wait,&current_time);
557         nanosleep(&interval,NULL);
558 }
559
560
561 void* sender(void* arg)
562 {
563         union msg_buff buff;
564         unsigned long int seqn;
565         struct stream* stream = (struct stream*) arg;
566         struct timespec ts;
567         int ret;
568
569         if (!opt_gui) {
570                 char stream_desc[100];
571                 stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
572                 printf("%s\n", stream_desc);
573         }
574         if (stream->bandwidth_bps == 0)
575                 goto out;
576
577         seqn = 0;
578         
579         block_signals();
580         set_rt_prio(90-stream->ac);
581
582         while (!exit_flag) {
583
584 /*              buff.msg.seqn = seqn++; */
585 /*              buff.msg.tos = ac_to_tos[stream->ac]; */
586                 buff.msg.stream = stream-streams;
587                 
588                 clock_gettime(CLOCK_REALTIME,&ts);
589                 buff.msg.send_timestamp = ts.tv_sec*1000000000LL + ts.tv_nsec;
590
591                 ret = send_packet(stream, &buff);
592                 if (ret < 0) {
593                         goto out;
594                 }
595
596                 pthread_mutex_lock(&stream->mutex);
597                 stream->sent++;
598                 if (ret > 0)
599                         stream->really_sent++;
600                 pthread_mutex_unlock(&stream->mutex);
601
602 #ifdef DEBUG
603                 printf("%d", stream->ac);
604                 fflush(stdout);
605 #endif
606
607                 wait_for_next_send(stream, &ts);
608         }
609 out:
610         sem_post(&sem_thread_finished);
611         return NULL;
612 }
613
614 #ifdef WITH_FWP
615 static int negotiate_contract_for_stream_fwp(struct stream *stream)
616 {
617         frsh_contract_t contract;
618         int ret;
619         frsh_rel_time_t budget, period, deadline;
620         frsh_signal_info_t si;
621
622         /* Contract for client->server stream */
623         frsh_contract_init(&contract);
624         frsh_contract_set_resource_and_label(&contract, FRSH_RT_NETWORK, FRSH_NETPF_FWP, NULL);
625         frsh_network_bytes_to_budget(FRSH_NETPF_FWP, stream->packet_size, &budget);
626         period = frsh_usec_to_rel_time(stream->period_usec);
627         frsh_contract_set_basic_params(&contract, &budget, &period, FRSH_WT_BOUNDED, FRSH_CT_REGULAR);
628         deadline = frsh_usec_to_rel_time(3*stream->period_usec);
629         frsh_contract_set_timing_reqs(&contract, false, &deadline, 0, si, 0, si);
630         
631         ret = frsh_contract_negotiate(&contract, &stream->vres);
632         frsh_contract_destroy(&contract);
633         if (ret != 0) {
634                 stream->vres = NULL;
635                 fprintf(stderr, "Send contract was not accepted\n");
636                 return ret;
637         }
638
639         /* Contract for server->client stream */
640         /* TODO: Use group negotiation for these two contracts */
641         frsh_contract_init(&contract);
642         frsh_contract_set_resource_and_label(&contract, FRSH_RT_NETWORK, FRSH_NETPF_FWP, NULL);
643         frsh_network_bytes_to_budget(FRSH_NETPF_FWP, stream->packet_size, &budget);
644         period = frsh_usec_to_rel_time(stream->period_usec);
645         frsh_contract_set_basic_params(&contract, &budget, &period, FRSH_WT_BOUNDED, FRSH_CT_DUMMY);
646         deadline = frsh_usec_to_rel_time(3*stream->period_usec);
647         frsh_contract_set_timing_reqs(&contract, false, &deadline, 0, si, 0, si);
648
649         ret = frsh_contract_negotiate(&contract, &stream->vres_rcv);
650         frsh_contract_destroy(&contract);
651         if (ret != 0) {
652                 fprintf(stderr, "Receive contract was not accepted\n");
653                 return ret;
654         }
655
656         /* We don't use the vres at server, since the server doesn't
657          * know the parameters. Instread, server uses plain
658          * sockets. */
659         
660         return ret;
661 }
662 #endif
663
664 #ifdef WITH_FWP
665 static void create_stream_endpoint_fwp(struct stream *stream)
666 {
667 /*      fwp_endpoint_attr_t  attr; */
668         int ret;
669         struct hostent* ph;
670         frsh_contract_t c;
671         fres_block_fwp_sched *fwp_sched;
672
673         frsh_vres_get_contract(stream->vres, &c);
674         fwp_sched = fres_contract_get_fwp_sched(c);
675
676         stream->ac = fwp_sched->ac_id;
677
678 /*      fwp_endpoint_attr_init(&attr); */
679 /*      fwp_endpoint_attr_setreliability(&attr, FWP_EPOINT_BESTEFFORT); */
680
681         ph = gethostbyname(server_addr);
682         if (ph && ph->h_addr_list[0]) {
683                 struct in_addr *a = (struct in_addr *)(ph->h_addr_list[0]);
684                 frsh_send_endpoint_protocol_info_t    spi = { NULL, 0 };
685                 frsh_receive_endpoint_protocol_info_t rpi = { NULL, 0 };
686                 frsh_endpoint_queueing_info_t qi = { .queue_size=0, .queue_policy=FRSH_QRP_OLDEST };
687                 ret = frsh_send_endpoint_create(FRSH_NETPF_FWP, a->s_addr, BASE_PORT + stream->ac, 
688                                                 spi, &stream->endpoint);
689                 if (ret < 0) error(1, errno, "frsh_send_endpoint_create()");
690                 
691                 ret = frsh_send_endpoint_bind(stream->vres, stream->endpoint);
692                 if (ret != 0) error(1, errno, "frsh_send_endpoint_bind");
693
694                 ret = frsh_receive_endpoint_create(FRSH_NETPF_FWP, 0, qi, rpi,
695                                                    &stream->resp_endpoint);
696                 if (ret != 0) error(1, errno, "fwp_receive_endpoint_create");
697                 
698                 unsigned int port;
699                 frsh_receive_endpoint_get_params(stream->resp_endpoint, NULL, &port, NULL, NULL);
700                 stream->resp_port = port;
701
702                 ret = pthread_create(&stream->receiver.thread, NULL, receiver, (void*)stream);
703                 if (ret) error(1, ret, "Error while creating receiver");
704                 
705                 stream->receiver.valid = true;
706         }
707         else {
708                 error(1, errno, "gethostbyname(%s)", server_addr);
709         }
710
711 }
712 #else
713 static void create_stream_endpoint_native(struct stream *stream)
714 {
715         struct hostent* ph;
716
717         memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
718
719         stream->rem_addr.sin_family = AF_INET;
720         ph = gethostbyname(server_addr);
721         if (ph)
722                 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
723         else {
724                 error(1, errno, "gethostbyname(%s)", server_addr);
725         }
726         stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
727 }
728 #endif
729
730 static inline void
731 calc_stream_params(struct stream *stream)
732 {
733         int packet_size;
734         unsigned period_usec;
735         int bandwidth;
736         int ret;
737
738         /* If some parameters are not set explicitely, use default values. */
739         if (stream->bandwidth_bps < 0) stream->bandwidth_bps = opt_def_bandwidth * Kbit;
740         if (stream->packet_size < 0) stream->packet_size = opt_packet_size;
741         if (stream->period_usec < 0) stream->period_usec = opt_def_period_msec * MSEC_TO_USEC;
742
743         bandwidth = stream->bandwidth_bps;
744
745         /* Avoid arithmetic exception. Server thread will exit if
746            stream->bandwidth_bps == 0. */
747         if (bandwidth == 0) bandwidth = 1;
748
749         if (stream->packet_size) {
750                 packet_size = stream->packet_size;
751                 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
752                 if (period_usec == 0) period_usec = 1;
753         } else if (stream->period_usec) {
754                 period_usec = stream->period_usec;
755                 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
756         } else {
757                 char buf[200];
758                 stream_to_text(buf, sizeof(buf), stream, 0);
759                 error(1, 0, "Neither packet size nor period was specified for a stream %s", buf);
760         }
761
762         if (packet_size < sizeof(struct msg_t)) {
763                 error(1, 0, "Packet size too small (min %zd)", sizeof(struct msg_t));
764         }
765
766         stream->packet_size = packet_size;
767         stream->period_usec = period_usec;
768         stream->jitter = opt_jitter;
769
770         ret = negotiate_contract_for_stream(stream);
771         if (ret == 0) {
772                 create_stream_endpoint(stream);
773         } else {
774                 char buf[200];
775                 stream_to_text(buf, sizeof(buf), stream, 0);
776                 fprintf(stderr, "Contract hasn't been accepted:\n%s\n", buf);
777                 stream->bandwidth_bps = 0;
778                 some_contract_not_accepted = true;
779         }
780 }
781
782 /** 
783  * Parse -b parameter.
784  * 
785  * @param params String to parse
786  * 
787  * @return NULL in case of success, pointer to a problematic character
788  *         on error.
789  */
790 char* parse_bandwidths(char *params)
791 {
792         struct stream *sp = &streams[nr_streams];
793
794         while (*params && nr_streams < MAX_STREAMS) {
795                 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
796                 int i;
797                 char *next_char;
798
799                 if (strlen(params) < 2)
800                         return params;
801                 for (i=0; i<AC_NUM; i++) {
802                         if (strncmp(params, ac_ids[i], 2) == 0) {
803                                 sp->ac = i;
804                                 params+=strlen(ac_ids[i]);
805                                 break;
806                         }
807                 }
808                 if (i==AC_NUM)
809                         return params;
810
811                 long bw;
812                 if (*params == ':') {
813                         params++;
814
815                         bw = strtol(params, &next_char, 10);
816                         if (next_char == params)
817                                 return params;
818                         params = next_char;
819                 } else
820                         bw = -1;
821                 
822                 sp->bandwidth_bps = bw*Kbit;
823
824                 long period = 0;
825                 long packet_size = 0;
826                 if (*params == '@') {
827                         params++;
828                         period = strtol(params, &next_char, 10);
829                         if (period == 0)
830                                 return params;
831                         params = next_char;
832                 }
833                 else {
834                         if (*params == '/') {
835                                 params++;
836                                 packet_size = strtol(params, &next_char, 10);
837                                 if (packet_size == 0)
838                                         return params;
839                                 params = next_char;
840                         } else {
841                                 packet_size = -1; 
842                                 period = -1;
843                         }
844                 }
845                 sp->period_usec = period*MSEC_TO_USEC;
846                 sp->packet_size = packet_size;
847
848                 
849
850                 if (*params != '\0' && *params != ',')
851                         return params;
852                 nr_streams++;
853                 sp++;
854                 if (*params == ',')
855                         params++;
856         }
857         return NULL;
858 }
859
860 #ifdef WITH_FWP
861 void wait_for_all_threads_to_finish_fwp(void)
862 {
863         int i;
864         /* wait for all threads to finish */
865         for (i=0; i < 2*nr_streams; i++) {
866                 sem_wait(&sem_thread_finished);
867         }
868 }
869 #else
870 void wait_for_all_threads_to_finish_native(void)
871 {
872         int i;
873         /* Wait for all threads to finish */
874         for (i=0; i < nr_streams + AC_NUM; i++) {
875                 sem_wait(&sem_thread_finished);
876         }
877 }
878 #endif
879
880 WINDOW *logwin;
881
882 #if 0
883 struct log_params {
884         ul_log_domain_t *domain;
885         int level;
886         const char *format;
887         va_list ap;
888 };
889
890
891 int locked_log(WINDOW *logwin, void *arg)
892 {
893         struct log_params *p = arg;
894         if(!(p->level&UL_LOGL_CONT)) {
895                 p->level&=UL_LOGL_MASK;
896                 if(p->level)
897                         wprintw(logwin,"<%d>", p->level);
898                 if(p->domain && p->domain->name)
899                         wprintw(logwin,"%s: ",p->domain->name);
900         }
901         vwprintw(logwin, p->format, p->ap);
902         wnoutrefresh(logwin);
903         return 0;
904 }
905
906 void
907 wclient_log_fnc(ul_log_domain_t *domain, int level,
908                 const char *format, va_list ap)
909 {
910         struct log_params p = {
911                 .domain = domain,
912                 .level = level,
913                 .format = format,
914         };
915         va_copy(p.ap, ap);
916         va_end(ap);
917
918         use_window(logwin, locked_log, (void*)&p);
919 }
920 #endif
921
922
923 void init_gui()
924 {
925         if (opt_gui) {
926                 initscr();
927                 cbreak();
928                 noecho();
929 /*              nonl(); */
930 /*              intrflush(stdscr, FALSE); */
931 /*              keypad(stdscr, TRUE); */
932
933                 logwin = newwin(0, 0, LINES/2, 0);
934                 if (logwin) {
935                         scrollok(logwin, TRUE);
936 /*              ul_log_redir(wclient_log_fnc, 0); */
937                 }
938         }
939 }
940
941 void end_gui()
942 {
943         if (opt_gui) {
944                 endwin();
945                 if (logwin) {
946 /*              ul_log_redir(NULL, 0); */
947                 }
948         }
949 }
950
951
952 #define addfield(title, format, ...)                                    \
953         move(y, x);                                                     \
954         x+=strlen(title)+1;                                             \
955         if (i == 0) addstr(title);                                      \
956         else {                                                          \
957                 snprintf(str, sizeof(str), format, __VA_ARGS__);        \
958                 addstr(str);                                            \
959         }
960
961 void print_status_gui(int seconds)
962 {
963         int i;
964         char str[200], s1[20];
965         int x = 0, y;
966         struct stream *s = NULL;
967         
968         for (i = 0; i <= nr_streams; i++) {
969                 if (i>0) s = &streams[i-1];
970                 y=i;
971                 x=0;
972                 addfield("Stream", "%d", i);
973                 addfield("Bandwidth", "%s", bandwidth_to_text(s1, s->bandwidth_bps));
974                 addfield("Packet size", "%d bytes", s->packet_size);
975                 addfield("Period   ", "%s", usec_to_text(s1, s->period_usec));
976                 addfield("AC   ", "%s", ac_to_text[s->ac]);
977                 addfield("Worst-case delay", "%s", usec_to_text(s1, s->wc_delay));
978                 addfield("Received responses", "%lld", s->received);
979         }
980         wnoutrefresh(stdscr);
981         doupdate();
982 }
983
984 void print_status_nogui(int seconds)
985 {
986         int ac;
987         fprintf(stderr, "\r%3ds", seconds);
988         for (ac = 0; ac < AC_NUM; ac++) {
989                 int delta = receivers[ac].received - receivers[ac].last_received;
990                 receivers[ac].last_received = receivers[ac].received;
991                 fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
992         }
993         fflush(stderr);
994 }
995
996 int main(int argc, char *argv[])
997 {
998         int i, rc, frames, seconds;
999         pthread_attr_t attr;
1000         pthread_t thread;
1001         char opt;
1002
1003
1004         while ((opt = getopt(argc, argv, "B:b:C:c:Gg:I:j:o:qQ:s:T:")) != -1) {
1005                 switch (opt) {
1006                         case 'B':
1007                                 opt_def_bandwidth = atoi(optarg);
1008                                 break;
1009                         case 'b': {
1010                                 char *errpos;
1011                                 errpos = parse_bandwidths(optarg);
1012                                 if (errpos != NULL) {
1013                                         if (*errpos == '\0')
1014                                                 error(1, 0, "Bandwidth parse error - string to short");
1015                                         else
1016                                                 error(1, 0, "Bandwidth parse error at '%s'", errpos);
1017                                 }
1018                                 break;
1019                         }
1020                         case 'C':
1021                                 opt_comment = optarg;
1022                                 break;
1023                         case 'c':
1024                                 opt_count_sec = atoi(optarg);
1025                                 break;
1026                         case 'G':
1027                                 opt_gui = true;
1028                                 break;
1029                         case 'g':
1030                                 opt_granularity_usec = atoi(optarg);
1031                                 if (opt_granularity_usec < MIN_GRANULARITY) {
1032                                         error(1, 0, "Granulatiry too small (min %d)", MIN_GRANULARITY);
1033                                 }
1034                                 break;
1035                         case 'I':
1036                                 opt_interface = optarg;
1037                                 break;
1038                         case 'j':
1039                                 #ifdef WITH_FWP
1040                                 error(1, 0, "-j is not allowd when compiled with FWP");
1041                                 #else
1042                                 opt_jitter = atoi(optarg);
1043                                 #endif
1044                                 break;
1045                         case 'o':
1046                                 opt_output = optarg;
1047                                 break;
1048                         case 'Q':
1049                                 opt_send_buf_size = atoi(optarg);
1050                                 break;
1051                         case 'q':
1052                                 opt_wait_for_queue_is_full = true;
1053                                 break;
1054                         case 's':
1055                                 opt_packet_size = atoi(optarg);
1056                                 break;
1057                         case 'T':
1058                                 opt_def_period_msec = atoi(optarg);
1059                                 break;
1060                         default:
1061                                 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
1062                                 fprintf(stderr, "Options:\n");
1063                                 fprintf(stderr, "    -B  default bandwidth for -b option [kbit]\n");
1064                                 fprintf(stderr, "    -b  bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
1065                                 fprintf(stderr, "    -C  comment (added to header)\n");
1066                                 fprintf(stderr, "    -c  count (number of seconds to run)\n");
1067                                 fprintf(stderr, "    -g  histogram granularity [usec]\n");
1068                                 fprintf(stderr, "    -I  <interface> send packets from this interface\n");
1069                                 fprintf(stderr, "    -j  send jitter (0-100) [%%]\n");
1070                                 fprintf(stderr, "    -o  output filename (.dat will be appended)\n");
1071                                 fprintf(stderr, "    -q  gather statistics only after some queue becomes full\n");
1072                                 fprintf(stderr, "    -Q  <bytes> set size for socket send buffers\n");
1073                                 fprintf(stderr, "    -s  size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
1074                                 fprintf(stderr, "    -T  default period for -b option [msec]\n");
1075                                 exit(1);
1076                 }
1077         }
1078         if (opt_packet_size && opt_def_period_msec) {
1079                 error(1, 0, "Error: Nonzero -T and -s can't be used together!");
1080         }
1081
1082         if (optind < argc) {
1083                 server_addr = argv[optind];
1084         } else {
1085                 error(1, 0, "Expected server address argument");
1086         }
1087
1088         if (nr_streams == 0)
1089                 parse_bandwidths("BE");
1090                 
1091         pthread_attr_init(&attr);
1092
1093         snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
1094
1095         if ((logfd = fopen(logfname,"w+")) == NULL) {
1096                 error(1, errno ,"Can not open %s", logfname);
1097         }
1098         if (signal(SIGTERM, stopper) == SIG_ERR) {
1099                 error(1, errno, "Error in signal registration");
1100         }
1101                 
1102         if (signal(SIGINT, stopper) == SIG_ERR) {
1103                 error(1, errno, "Signal handler registration error");
1104         }
1105
1106         struct sigaction sa;
1107         sa.sa_handler = empty_handler;
1108         sa.sa_flags = 0;        /* don't restart syscalls */
1109
1110         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
1111                 error(1, errno, "sigaction error");
1112         }
1113
1114         sem_init(&sem_thread_finished, 0, 0);
1115
1116         reset_statistics();
1117
1118 #ifdef WITH_FWP
1119         //ul_log_domain_arg2levels("6");
1120         rc = frsh_init();
1121         if (rc != 0) {
1122                 error(1, errno, "FWP initialization failed");
1123         }
1124 #else
1125         intptr_t ac;
1126         /* create four receivers each per AC */
1127         for (ac = AC_NUM - 1; ac >= 0; ac--) {
1128                 ac_sockfd[ac] = create_ac_socket(ac);
1129                 if (ac_sockfd[ac] < 0) {
1130                         return 1;
1131                 }
1132                 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
1133                 if (rc) {
1134                         error(1, rc, "Error while creating receiver");
1135                 }
1136                 receivers[ac].valid = true;
1137         }               
1138 #endif
1139
1140                         
1141         if (opt_interface) {
1142                 struct ifreq ifr;
1143
1144                 memset(&ifr, 0, sizeof(ifr));
1145                 strncpy(ifr.ifr_name, opt_interface, IFNAMSIZ-1);
1146                 if (ioctl(ac_sockfd[AC_VO], SIOCGIFINDEX, &ifr) < 0) {
1147                         error(1, 0, "unknown iface %s", opt_interface);
1148                 }
1149                 cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
1150                 cmsg_len = sizeof(cmsg);
1151         }
1152         /* create sendpoints */
1153         for (i = 0; i < nr_streams; i++) {
1154                 struct stream *s = &streams[i];
1155                 pthread_mutex_init(&s->mutex, NULL);
1156                 calc_stream_params(s);
1157                 rc = pthread_create(&thread, &attr, sender, (void*) s);
1158                 if (rc) error(1, rc, "Error while creating sender");
1159         }
1160
1161         if (some_contract_not_accepted) {
1162                 stopper();
1163         } else {
1164                 init_gui();
1165
1166                 seconds = 1;
1167                 frames=0;
1168                 while (!exit_flag) {
1169                         if (opt_gui) {
1170                                 usleep(40000);
1171                                 frames++;
1172                                 if (frames>=25) {
1173                                         seconds++;
1174                                         frames = 0;
1175                                 }
1176                                 print_status_gui(seconds);
1177                         } else {
1178                                 sleep(1);
1179                                 seconds++;
1180                                 print_status_nogui(seconds);
1181                         }
1182
1183                         if (seconds == opt_count_sec)
1184                                 stopper();
1185                 }
1186         }
1187
1188         end_gui();
1189 #ifdef WITH_FWP
1190         for (i=0; i < nr_streams; i++) {
1191                 if (streams[i].vres)
1192                         frsh_contract_cancel(streams[i].vres);
1193                 if (streams[i].vres_rcv)
1194                         frsh_contract_cancel(streams[i].vres_rcv);
1195         }
1196 #endif
1197
1198         fprintf(stderr, "\nWaiting for threads to finish\n");
1199         wait_for_all_threads_to_finish();
1200
1201         struct timespec ts;
1202         uint64_t end_timestamp, measure_length;
1203         clock_gettime(CLOCK_REALTIME,&ts);
1204         end_timestamp = ts.tv_sec*1000000000LL+ts.tv_nsec;
1205         measure_length = end_timestamp - reset_timestamp;
1206
1207         save_results(argc, argv, measure_length/1000);
1208
1209         return 0;
1210 }