3 #include <sys/socket.h>
4 #include <netinet/in.h>
19 #include <semaphore.h>
22 #include <fwp_proto.h>
25 #define MAX_STREAMS 10
26 #define MIN_GRANULARITY 100
28 unsigned opt_packet_size = 800;
29 int opt_send_buf_size = -1;
30 unsigned opt_period_usec = 10*MSEC_TO_USEC;
31 unsigned opt_jitter = 0;
32 char *opt_output = "delay_stats";
33 unsigned opt_count_sec = 0;
34 unsigned opt_def_bandwidth = 200;
35 unsigned opt_def_period_msec = 0;
36 int opt_granularity_usec = MIN_GRANULARITY;
37 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
39 bool some_queue_is_full = false;
40 struct timespec reset_timestamp;
42 /* Locked when some queue is full to prevent multiple resets of
44 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
46 int ac_sockfd[AC_NUM];
50 unsigned received, last_received;
57 /* maximal traffic delay in ms - 10 s*/
58 #define MAX_DELAY_US 10000000
61 unsigned csc; /* Client-server-client delay divided by 2 */
62 unsigned cs; /* Client-server delay */
63 unsigned sc; /* Server-client delay */
66 struct delay_stat delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
67 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
69 /*struct ac_stats[AC_NUM] {
70 unsigned long int min_trans_time;
71 unsigned long int sum_trans_time;
72 struct timespec recv_timestamp;
73 struct timespec send_timestamp;
77 /* Input parameters */
79 int bandwidth_bps; /* bits per second */
80 int jitter; /* percent */
81 /* Mulualy exclusive input parameters */
83 long period_usec; /* all time units are in microseconds */
87 struct sockaddr_in rem_addr;
93 pthread_mutex_t mutex;
94 unsigned long long sent, really_sent, received;
98 struct send_endpoint sepoint[] = {
99 { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
100 { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps = 480*Kbit },
101 { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps = 300*Kbit },
102 { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps = 300*Kbit },
103 // { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps = 675*Kbit },
107 struct stream streams[MAX_STREAMS];
109 unsigned int nr_streams = 0;
111 sem_t sem_thread_finished;
113 bool exit_flag = false;
116 #define negotiate_contract_for_stream(s) negotiate_contract_for_stream_fwp(s)
117 #define create_stream_endpoint(s) create_stream_endpoint_fwp(s)
118 #define send_packet(s, b) send_packet_fwp(s, b)
120 #define negotiate_contract_for_stream(s) 0
121 #define create_stream_endpoint(s) create_stream_endpoint_native(s)
122 #define send_packet(s, b) send_packet_native(s, b)
130 /* Interrupt all receivers */
131 for (i=0; i < AC_NUM; i++) {
132 pthread_kill(receivers[i].thread, SIGUSR1);
136 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
142 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
143 bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
144 stream->sent, stream->sent*SEC_TO_USEC/useconds,
145 stream->received, stream->received*SEC_TO_USEC/useconds);
150 snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
151 stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
152 stream->packet_size, usec_to_text(buf[1], stream->period_usec),
153 usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
154 (int)(SEC_TO_USEC/stream->period_usec), real);
157 void save_results(int argc, char *argv[], int useconds)
160 const int mini = 3000/opt_granularity_usec;
162 unsigned send_count[AC_NUM];
164 fprintf(stderr, "Writing data to %s... ", logfname);
167 fprintf(logfd, "# Invoked as: ");
168 for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
169 fprintf(logfd, "\n");
171 if (useconds/SEC_TO_USEC != opt_count_sec) {
173 usec_to_text(buf, useconds);
174 fprintf(logfd, "# Data gathered for %s.\n", buf);
177 for (i = 0; i < nr_streams; i++) {
178 char stream_desc[200];
179 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
180 fprintf(logfd, "# Stream %s\n", stream_desc);
183 /* Find maximal delay */
185 for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
186 for (ac = 0; ac < AC_NUM; ac++) {
187 if ((delay_stats[ac][maxi].csc != 0) ||
188 (delay_stats[ac][maxi].cs != 0) ||
189 (delay_stats[ac][maxi].sc != 0))
192 if (!allzeros) break;
195 if (maxi < mini) maxi = mini;
197 /* Calculate total number of sent packets per AC */
198 memset(send_count, 0, sizeof(send_count));
199 for (i = 0; i < nr_streams; i++) {
201 send_count[ac] += streams[i].sent;
206 for ( i = 0 ; i < maxi; i++) {
207 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
208 for (ac = 0; ac < AC_NUM; ac++) {
210 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
211 else val = -1; /* Don't display this ac */
212 fprintf(logfd," %lf", val);
216 fprintf(logfd,"\n\n");
219 fprintf(logfd,"## Format: msec csc%% cs%% sc%%\n");
222 for (ac = 0; ac < AC_NUM; ac++) {
223 struct delay_stat integral = {0,0,0}, last = {-1,-1,-1};
225 fprintf(logfd,"%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);
227 if (send_count[ac] != 0) {
229 while ((delay_stats[ac][i].csc == 0) &&
230 (delay_stats[ac][i].cs == 0) &&
231 (delay_stats[ac][i].sc == 0)) i++;
233 for (i++; i < maxi+1; i++) {
234 if (memcmp(&last, &integral, sizeof(last))) {
235 fprintf(logfd,"%f %f %f %f\n", i*opt_granularity_usec/1000.0,
236 (double)integral.csc*100.0 / send_count[ac],
237 (double)integral.cs *100.0 / send_count[ac],
238 (double)integral.sc *100.0 / send_count[ac]
243 integral.csc += delay_stats[ac][i-1].csc;
244 integral.sc += delay_stats[ac][i-1].sc;
245 integral.cs += delay_stats[ac][i-1].cs;
249 fprintf(logfd,"\n\n");
252 fprintf(stderr, "finished.\n");
259 void timespec_add (struct timespec *sum, const struct timespec *left,
260 const struct timespec *right)
262 sum->tv_sec = left->tv_sec + right->tv_sec;
263 sum->tv_nsec = left->tv_nsec + right->tv_nsec;
265 if (sum->tv_nsec >= 1000000000){
267 sum->tv_nsec -= 1000000000;
272 void timespec_sub (struct timespec *diff, const struct timespec *left,
273 const struct timespec *right)
275 diff->tv_sec = left->tv_sec - right->tv_sec;
276 diff->tv_nsec = left->tv_nsec - right->tv_nsec;
278 if (diff->tv_nsec < 0){
280 diff->tv_nsec += 1000000000;
284 static inline long long timespec_sub_usec(const struct timespec *left,
285 const struct timespec *right)
287 struct timespec result;
288 timespec_sub(&result, left, right);
289 return (long long)result.tv_sec * SEC_TO_USEC +
290 result.tv_nsec / USEC_TO_NSEC;
293 static inline long long timespec2usec(const struct timespec *ts)
295 return ts->tv_sec * SEC_TO_USEC + ts->tv_nsec / USEC_TO_NSEC;
299 int create_ac_socket(unsigned int ac)
302 unsigned int yes=1, tos;
305 if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
307 perror("Unable to open socket");
310 if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
311 perror("set non-blocking socket");
314 if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
315 perror("Unable to set socket");
319 if (opt_send_buf_size >= 0) {
320 if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&opt_send_buf_size,sizeof(opt_send_buf_size)) == -1) {
321 perror("Unable to set socket buffer size");
327 //tos = ((AC_NUM - ac) *2 - 1)*32;
329 if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
330 perror("Unable to set TOS");
342 void reset_statistics()
345 for (i = 0; i < nr_streams; i++) {
346 pthread_mutex_lock(&streams[i].mutex);
348 streams[i].really_sent = 0;
349 streams[i].received = 0;
350 pthread_mutex_unlock(&streams[i].mutex);
352 pthread_mutex_lock(&delay_stats_mutex);
353 clock_gettime(CLOCK_REALTIME, &reset_timestamp);
354 memset(delay_stats, 0, sizeof(delay_stats));
355 pthread_mutex_unlock(&delay_stats_mutex);
358 void* receiver(void* queue)
361 struct sockaddr_in rem_addr;
363 unsigned int ac, rem_addr_length;
364 long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
365 long long int min_trans_time;
366 struct timespec send_timestamp, server_timestamp, recv_timestamp;
375 rem_addr_length = sizeof(rem_addr);
378 FD_SET(ac_sockfd[ac], &fdset);
379 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
381 if (errno == EINTR) continue;
382 perror("receiver select");
385 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,
386 (struct sockaddr*)&rem_addr, &rem_addr_length);
388 perror("Chyba pri prijimani pozadavku");
391 clock_gettime(CLOCK_REALTIME,&recv_timestamp);
392 send_timestamp = msg.send_timestamp;
393 server_timestamp = msg.sendback_timestamp;
395 /* Check whether this message was sent after reset_statistics() */
397 if ((ret = timespec_sub_usec(&send_timestamp, &reset_timestamp)) < 0) {
398 continue; /* If so, don't count it */
401 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp) / 2;
402 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
403 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
405 pthread_mutex_lock(&delay_stats_mutex);
406 if (trans_time_usec < MAX_DELAY_US) {
407 delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
409 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
410 delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
412 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
413 delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
415 pthread_mutex_unlock(&delay_stats_mutex);
417 receivers[ac].received++;
419 pthread_mutex_lock(&streams[msg.stream].mutex);
420 streams[msg.stream].received++;
421 pthread_mutex_unlock(&streams[msg.stream].mutex);
423 /*if (trans_time_nsec < min_trans_time)
424 min_trans_time = trans_time_nsec;*/
425 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
426 "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
427 msg.seqn, msg.tos, send_timestamp.tv_sec,\
428 send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
429 recv_timestamp.tv_nsec, trans_time_msec); */
432 sem_post(&sem_thread_finished);
439 * @return -1 in case of error, 1 in case of sucessfull send and 0
440 * when all buffers are full.
444 send_packet_native(struct stream* stream, union msg_buff* buff)
447 while (sendto(ac_sockfd[stream->ac], buff, stream->packet_size, 0,
448 (struct sockaddr*)&stream->rem_addr, sizeof(stream->rem_addr)) < 0) {
449 if (errno == EINTR) continue;
450 if (errno == EAGAIN) {
451 if (opt_wait_for_queue_is_full &&
452 !some_queue_is_full &&
453 /* We use mutex as atomic test and set */
454 (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
455 some_queue_is_full = true;
461 perror("Error while sending");
470 send_packet_fwp(struct stream* stream, union msg_buff* buff)
473 /* while (sendto(ac_sockfd[stream->ac], buff, stream->packet_size, 0, */
474 /* (struct sockaddr*)&stream->rem_addr, sizeof(stream->rem_addr)) < 0) { */
475 /* if (errno == EINTR) continue; */
476 /* if (errno == EAGAIN) { */
477 /* if (opt_wait_for_queue_is_full && */
478 /* !some_queue_is_full && */
479 /* /\* We use mutex as atomic test and set *\/ */
480 /* (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) { */
481 /* some_queue_is_full = true; */
482 /* reset_statistics(); */
487 /* perror("Error while sending"); */
497 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
499 struct timespec time_to_wait, current_time, period, interval;
500 unsigned period_usec = stream->period_usec;
502 /* |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
503 /* |-------------| nominal period*/
504 if (stream->jitter) {
505 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
506 + rand() % (2*period_usec*stream->jitter/100));
508 period.tv_nsec = USEC_TO_NSEC*(period_usec);
512 timespec_add(&time_to_wait, last_send_time, &period);
513 clock_gettime(CLOCK_REALTIME,¤t_time);
514 timespec_sub(&interval,&time_to_wait,¤t_time);
515 nanosleep(&interval,NULL);
519 void* sender(void* arg)
522 unsigned long int seqn;
523 struct stream* stream = (struct stream*) arg;
524 char stream_desc[100];
527 stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
528 printf("%s\n", stream_desc);
530 if (stream->bandwidth_bps == 0)
536 set_rt_prio(90-stream->ac);
540 /* buff.msg.seqn = seqn++; */
541 /* buff.msg.tos = ac_to_tos[stream->ac]; */
542 buff.msg.stream = stream-streams;
544 clock_gettime(CLOCK_REALTIME,&buff.msg.send_timestamp);
546 ret = send_packet(stream, &buff);
551 pthread_mutex_lock(&stream->mutex);
554 stream->really_sent++;
555 pthread_mutex_unlock(&stream->mutex);
558 printf("%d", stream->ac);
562 wait_for_next_send(stream, &buff.msg.send_timestamp);
565 sem_post(&sem_thread_finished);
570 static int negotiate_contract_for_stream_fwp(struct stream *stream)
572 struct fwp_contract contract;
576 contract.budget = stream->packet_size;
577 contract.period_usec = stream->period_usec;
578 ret = fwp_contract_negotiate(&contract, &vres_id);
580 if (contract.status == FWP_CNT_NEGOTIATED) {
581 stream->vres_id = vres_id;
583 stream->vres_id = -1;
591 static void create_stream_endpoint_fwp(struct stream *stream)
593 /* TODO: How to create an enpoint? */
596 static void create_stream_endpoint_native(struct stream *stream)
600 memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
602 stream->rem_addr.sin_family = AF_INET;
603 ph = gethostbyname(server_addr);
605 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
607 perror("Unknown server");
610 stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
615 calc_stream_params(struct stream *stream)
618 unsigned period_usec;
622 /* If some parameters are not set explicitely, use default values. */
623 if (stream->bandwidth_bps < 0) stream->bandwidth_bps = opt_def_bandwidth * Kbit;
624 if (stream->packet_size < 0) stream->packet_size = opt_packet_size;
625 if (stream->period_usec < 0) stream->period_usec = opt_def_period_msec * MSEC_TO_USEC;
627 bandwidth = stream->bandwidth_bps;
629 /* Avoid arithmetic exception. Server thread will exit if
630 stream->bandwidth_bps == 0. */
631 if (bandwidth == 0) bandwidth = 1;
633 if (stream->packet_size) {
634 packet_size = stream->packet_size;
635 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
636 if (period_usec == 0) period_usec = 1;
637 } else if (stream->period_usec) {
638 period_usec = stream->period_usec;
639 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
642 stream_to_text(buf, sizeof(buf), stream, 0);
643 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
647 if (packet_size < sizeof(struct msg_t)) {
648 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
652 stream->packet_size = packet_size;
653 stream->period_usec = period_usec;
654 stream->jitter = opt_jitter;
656 ret = negotiate_contract_for_stream(stream);
658 create_stream_endpoint(stream);
661 stream_to_text(buf, sizeof(buf), stream, 0);
662 fprintf(stderr, "Contract hasn't been accepted: %s\n", buf);
663 stream->bandwidth_bps = 0;
668 * Parse -b parameter.
670 * @param params String to parse
672 * @return NULL in case of success, pointer to a problematic character
675 char* parse_bandwidths(char *params)
677 struct stream *sp = &streams[nr_streams];
679 while (*params && nr_streams < MAX_STREAMS) {
680 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
684 if (strlen(params) < 2)
686 for (i=0; i<AC_NUM; i++) {
687 if (strncmp(params, ac_ids[i], 2) == 0) {
689 params+=strlen(ac_ids[i]);
697 if (*params == ':') {
700 bw = strtol(params, &next_char, 10);
701 if (next_char == params)
707 sp->bandwidth_bps = bw*Kbit;
710 long packet_size = 0;
711 if (*params == '@') {
713 period = strtol(params, &next_char, 10);
719 if (*params == '/') {
721 packet_size = strtol(params, &next_char, 10);
722 if (packet_size == 0)
730 sp->period_usec = period*MSEC_TO_USEC;
731 sp->packet_size = packet_size;
735 if (*params != '\0' && *params != ',')
745 int main(int argc, char *argv[])
747 int ac, i, rc, seconds;
753 while ((opt = getopt(argc, argv, "B:b:c:g:j:o:qQ:s:T:")) != -1) {
756 opt_def_bandwidth = atoi(optarg);
760 error = parse_bandwidths(optarg);
763 fprintf(stderr, "Bandwidth parse error - string to short\n");
765 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
771 opt_count_sec = atoi(optarg);
774 opt_granularity_usec = atoi(optarg);
775 if (opt_granularity_usec < MIN_GRANULARITY) {
776 fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
781 opt_jitter = atoi(optarg);
787 opt_send_buf_size = atoi(optarg);
790 opt_wait_for_queue_is_full = true;
793 opt_packet_size = atoi(optarg);
796 opt_def_period_msec = atoi(optarg);
799 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
800 fprintf(stderr, "Options:\n");
801 fprintf(stderr, " -B default bandwidth for -b option [kbit]\n");
802 fprintf(stderr, " -b bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
803 fprintf(stderr, " -c count (number of seconds to run)\n");
804 fprintf(stderr, " -g histogram granularity [usec]\n");
805 fprintf(stderr, " -j send jitter (0-100) [%%]\n");
806 fprintf(stderr, " -o output filename (.dat will be appended)\n");
807 fprintf(stderr, " -q gather statistics only after some queue becomes full\n");
808 fprintf(stderr, " -Q <bytes> set size for socket send buffers\n");
809 fprintf(stderr, " -s size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
810 fprintf(stderr, " -T default period for -b option [msec]\n");
814 if (opt_packet_size && opt_def_period_msec) {
815 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
820 server_addr = argv[optind];
822 fprintf(stderr, "Expected server address argument\n");
827 parse_bandwidths("BE");
829 pthread_attr_init(&attr);
831 snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
833 if ((logfd = fopen(logfname,"w+")) == NULL) {
834 fprintf(stderr,"Can not open %s\n", logfname);
837 if (signal(SIGTERM, stopper) == SIG_ERR) {
838 perror("Error in signal registration");
842 if (signal(SIGINT, stopper) == SIG_ERR) {
843 perror("Signal handler registration error");
848 sa.sa_handler = empty_handler;
849 sa.sa_flags = 0; /* don't restart syscalls */
851 if (sigaction(SIGUSR1, &sa, NULL) < 0) {
852 perror("sigaction error");
856 sem_init(&sem_thread_finished, 0, 0);
860 /* create four receivers each per AC */
861 for (ac = AC_NUM - 1; ac >= 0; ac--) {
862 ac_sockfd[ac] = create_ac_socket(ac);
863 if (ac_sockfd[ac] < 0) {
866 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
868 fprintf(stderr, "Error while creating receiver %d\n",rc);
873 /* create sendpoints */
874 for (i = 0; i < nr_streams; i++) {
875 struct stream *s = &streams[i];
876 pthread_mutex_init(&s->mutex, NULL);
877 calc_stream_params(s);
878 rc = pthread_create(&thread, &attr, sender, (void*) s);
880 fprintf(stderr, "Error while creating sender %d\n",rc);
889 fprintf(stderr, "\r%3ds", seconds);
890 for (ac = 0; ac < AC_NUM; ac++) {
891 int delta = receivers[ac].received - receivers[ac].last_received;
892 receivers[ac].last_received = receivers[ac].received;
893 fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
896 if (seconds == opt_count_sec)
900 fprintf(stderr, "\nWaiting for threads to finish\n");
901 /* Wait for all threads to finish */
902 for (i=0; i < nr_streams + AC_NUM; i++) {
903 sem_wait(&sem_thread_finished);
905 struct timespec end_timestamp, measure_length;
906 clock_gettime(CLOCK_REALTIME,&end_timestamp);
907 timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
909 save_results(argc, argv, timespec2usec(&measure_length));