glitch in the license text detected by hyazinthe, thank you!
[oweals/gnunet.git] / src / transport / gnunet-transport-profiler.c
1 /*
2  This file is part of GNUnet.
3  Copyright (C) 2011-2016 GNUnet e.V.
4
5  GNUnet is free software: you can redistribute it and/or modify it
6  under the terms of the GNU Affero General Public License as published
7  by the Free Software Foundation, either version 3 of the License,
8  or (at your option) any later version.
9
10  GNUnet is distributed in the hope that it will be useful, but
11  WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  Affero General Public License for more details.
14  */
15
16 /**
17  * @file src/transport/gnunet-transport-profiler.c
18  * @brief Tool to help benchmark the transport subsystem.
19  * @author Christian Grothoff
20  * @author Nathan Evans
21  *
22  * This utility can be used to benchmark a transport mechanism for
23  * GNUnet.
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_protocols.h"
28 #include "gnunet_ats_service.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet_transport_core_service.h"
31
32
33 struct Iteration
34 {
35   struct Iteration *next;
36   struct Iteration *prev;
37   struct GNUNET_TIME_Absolute start;
38   struct GNUNET_TIME_Absolute end;
39
40   struct GNUNET_TIME_Relative dur;
41
42   /* Transmission rate for this iteration in KB/s */
43   float rate;
44
45   unsigned int msgs_sent;
46 };
47
48
49 /**
50  * Timeout for a connections
51  */
52 #define CONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
53
54 /**
55  * Benchmarking block size in bye
56  */
57 #define DEFAULT_MESSAGE_SIZE 1024
58
59 /**
60  * Benchmarking message count
61  */
62 #define DEFAULT_MESSAGE_COUNT 1024
63
64 /**
65  * Benchmarking iteration count
66  */
67 #define DEFAULT_ITERATION_COUNT 1
68
69 /**
70  * Option -s.
71  */
72 static int benchmark_send;
73
74 /**
75  * Option -b.
76  */
77 static int benchmark_receive;
78
79 /**
80  * Option -n.
81  */
82 static unsigned int benchmark_count;
83
84 /**
85  * Option -i.
86  */
87 static unsigned int benchmark_iterations;
88
89 /**
90  * Option -m.
91  */
92 static unsigned int benchmark_size;
93
94 /**
95  * Benchmark running
96  */
97 static unsigned int benchmark_running;
98
99 /**
100  * Which peer should we connect to?
101  */
102 static char *cpid;
103
104 /**
105  * Handle to transport service.
106  */
107 static struct GNUNET_TRANSPORT_CoreHandle *handle;
108
109 /**
110  * Handle to ATS service.
111  */
112 static struct GNUNET_ATS_ConnectivityHandle *ats;
113
114 /**
115  * Configuration handle
116  */
117 static struct GNUNET_CONFIGURATION_Handle *cfg;
118
119 /**
120  * Try_connect handle
121  */
122 static struct GNUNET_ATS_ConnectivitySuggestHandle *ats_sh;
123
124 static struct Iteration *ihead;
125
126 static struct Iteration *itail;
127
128 /**
129  * Global return value (0 success).
130  */
131 static int ret;
132
133 /**
134  * Handle for transmissions.
135  */
136 static struct GNUNET_MQ_Handle *mq;
137
138 static struct GNUNET_TRANSPORT_Blacklist *bl_handle;
139
140 /**
141  * Identity of the peer we transmit to / connect to.
142  * (equivalent to 'cpid' string).
143  */
144 static struct GNUNET_PeerIdentity pid;
145
146 /**
147  * Selected level of verbosity.
148  */
149 static unsigned int verbosity;
150
151
152 /**
153  * Task run in monitor mode when the user presses CTRL-C to abort.
154  * Stops monitoring activity.
155  *
156  * @param cls NULL
157  */
158 static void
159 shutdown_task (void *cls)
160 {
161   struct Iteration *icur;
162   struct Iteration *inext;
163
164   unsigned int iterations;
165
166   unsigned long long avg_duration;
167   float avg_rate;
168   float stddev_rate;
169   float stddev_duration;
170
171   if (NULL != ats_sh)
172   {
173     GNUNET_ATS_connectivity_suggest_cancel (ats_sh);
174     ats_sh = NULL;
175   }
176   if (NULL != bl_handle)
177   {
178     GNUNET_TRANSPORT_blacklist_cancel (bl_handle);
179     bl_handle = NULL;
180   }
181   if (NULL != ats)
182   {
183     GNUNET_ATS_connectivity_done (ats);
184     ats = NULL;
185   }
186   if (NULL != handle)
187   {
188     GNUNET_TRANSPORT_core_disconnect (handle);
189     handle = NULL;
190   }
191
192   if (verbosity > 0)
193     FPRINTF (stdout, "\n");
194
195   /* Output format:
196    * All time values in ms
197    * Rate in KB/s
198    * #messages;#messagesize;#avg_dur;#avg_rate;#duration_i0;#duration_i0;... */
199
200   if (benchmark_send)
201   {
202     /* First iteration to calculcate avg and stddev */
203     iterations = 0;
204     avg_duration = 0;
205     avg_rate = 0.0;
206
207     inext = ihead;
208     while (NULL != (icur = inext))
209     {
210       inext = icur->next;
211       icur->rate = ((benchmark_count * benchmark_size) / 1024) /
212           ((float) icur->dur.rel_value_us / (1000 * 1000));
213       if (verbosity > 0)
214         FPRINTF (stdout, _("%llu B in %llu ms == %.2f KB/s!\n"),
215             ((long long unsigned int) benchmark_count * benchmark_size),
216             ((long long unsigned int) icur->dur.rel_value_us / 1000),
217             (float) icur->rate);
218
219       avg_duration += icur->dur.rel_value_us / (1000);
220       avg_rate  += icur->rate;
221       iterations++;
222     }
223     if (0 == iterations)
224       iterations = 1; /* avoid division by zero */
225     /* Calculate average rate */
226     avg_rate /= iterations;
227     /* Calculate average duration */
228     avg_duration /= iterations;
229
230     stddev_rate = 0;
231     stddev_duration = 0;
232     inext = ihead;
233     while (NULL != (icur = inext))
234     {
235       inext = icur->next;
236       stddev_rate += ((icur->rate-avg_rate) *
237           (icur->rate-avg_rate));
238       stddev_duration += (((icur->dur.rel_value_us / 1000) - avg_duration) *
239           ((icur->dur.rel_value_us / 1000) - avg_duration));
240
241     }
242     /* Calculate standard deviation rate */
243     stddev_rate = stddev_rate / iterations;
244     stddev_rate = sqrtf(stddev_rate);
245
246     /* Calculate standard deviation duration */
247     stddev_duration = stddev_duration / iterations;
248     stddev_duration = sqrtf(stddev_duration);
249
250     /* Output */
251     FPRINTF (stdout,
252              "%u;%u;%llu;%llu;%.2f;%.2f",
253              benchmark_count,
254              benchmark_size,
255              avg_duration,
256              (unsigned long long) stddev_duration,
257              avg_rate,
258              stddev_rate);
259
260     inext = ihead;
261     while (NULL != (icur = inext))
262     {
263       inext = icur->next;
264       GNUNET_CONTAINER_DLL_remove (ihead,
265                                    itail,
266                                    icur);
267
268       FPRINTF (stdout,
269                ";%llu;%.2f",
270                (long long unsigned int) (icur->dur.rel_value_us / 1000),
271                icur->rate);
272
273       GNUNET_free (icur);
274     }
275   }
276 #if 0
277   if (benchmark_receive)
278   {
279     duration = GNUNET_TIME_absolute_get_duration (start_time);
280     FPRINTF (stdout,
281              "Received %llu bytes/s (%llu bytes in %s)\n",
282              1000LL * 1000LL * traffic_received / (1 + duration.rel_value_us),
283              traffic_received,
284              GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
285   }
286 #endif
287   FPRINTF (stdout, "\n");
288 }
289
290
291 static void
292 iteration_done ();
293
294
295 /**
296  * Function called to notify a client about the socket
297  * begin ready to queue more data.  @a buf will be
298  * NULL and @a size zero if the socket was closed for
299  * writing in the meantime.
300  *
301  * @param cls closure
302  * @param size number of bytes available in @a buf
303  * @param buf where the callee should write the message
304  * @return number of bytes written to @a buf
305  */
306 static void
307 send_msg (void *cls)
308 {
309   struct GNUNET_MQ_Envelope *env;
310   struct GNUNET_MessageHeader *m;
311
312   if (NULL == mq)
313     return;
314   env = GNUNET_MQ_msg_extra (m,
315                              benchmark_size,
316                              GNUNET_MESSAGE_TYPE_DUMMY);
317   memset (&m[1],
318           52,
319           benchmark_size - sizeof(struct GNUNET_MessageHeader));
320   
321   if (itail->msgs_sent < benchmark_count)
322   {
323     GNUNET_MQ_notify_sent (env,
324                            &send_msg,
325                            NULL);
326   }
327   else
328   {
329     iteration_done ();
330   }
331   GNUNET_MQ_send (mq,
332                   env);
333   if ( (verbosity > 0) &&
334        (0 == itail->msgs_sent % 10) )
335     FPRINTF (stdout, ".");
336 }
337
338
339 static void
340 iteration_start ()
341 {
342   struct Iteration *icur;
343
344   ret = 0;
345   if (! benchmark_send)
346     return;
347   benchmark_running = GNUNET_YES;
348   icur = GNUNET_new (struct Iteration);
349   GNUNET_CONTAINER_DLL_insert_tail (ihead,
350                                     itail,
351                                     icur);
352   icur->start = GNUNET_TIME_absolute_get();
353   if (verbosity > 0)
354     FPRINTF (stdout,
355              "\nStarting benchmark, starting to send %u messages in %u byte blocks\n",
356              benchmark_count,
357              benchmark_size);
358   send_msg (NULL);
359 }
360
361
362 static void
363 iteration_done ()
364 {
365   static int it_count = 0;
366
367   it_count++;
368   itail->dur = GNUNET_TIME_absolute_get_duration (itail->start);
369   if (it_count == benchmark_iterations)
370   {
371     benchmark_running = GNUNET_NO;
372     GNUNET_SCHEDULER_shutdown ();
373     return;
374   }
375   iteration_start ();
376 }
377
378
379 /**
380  * Function called to notify transport users that another
381  * peer connected to us.
382  *
383  * @param cls closure
384  * @param peer the peer that connected
385  * @param m message queue for transmissions
386  * @return NULL
387  */
388 static void *
389 notify_connect (void *cls,
390                 const struct GNUNET_PeerIdentity *peer,
391                 struct GNUNET_MQ_Handle *m)
392 {
393   if (0 != memcmp (&pid,
394                    peer,
395                    sizeof(struct GNUNET_PeerIdentity)))
396   {
397     FPRINTF (stdout,
398              "Connected to different peer `%s'\n",
399              GNUNET_i2s (&pid));
400     return NULL;
401   }
402
403   if (verbosity > 0)
404     FPRINTF (stdout,
405              "Successfully connected to `%s'\n",
406              GNUNET_i2s (&pid));
407   mq = m;
408   iteration_start ();
409   return NULL;
410 }
411
412
413 /**
414  * Function called to notify transport users that another
415  * peer disconnected from us.
416  *
417  * @param cls closure
418  * @param peer the peer that disconnected
419  * @param internal_cls NULL
420  */
421 static void
422 notify_disconnect (void *cls,
423                    const struct GNUNET_PeerIdentity *peer,
424                    void *internal_cls)
425 {
426   if (0 != memcmp (&pid,
427                    peer,
428                    sizeof(struct GNUNET_PeerIdentity)))
429     return;
430   mq = NULL;
431   if (GNUNET_YES == benchmark_running)
432   {
433     FPRINTF (stdout,
434              "Disconnected from peer `%s' while benchmarking\n",
435              GNUNET_i2s (&pid));
436     return;
437   }
438 }
439
440
441 /**
442  * Function called by the transport for each received message.
443  *
444  * @param cls closure
445  * @param message the message
446  * @return #GNUNET_OK
447  */
448 static int
449 check_dummy (void *cls,
450              const struct GNUNET_MessageHeader *message)
451 {
452   return GNUNET_OK; /* all messages are fine */
453 }
454
455
456 /**
457  * Function called by the transport for each received message.
458  *
459  * @param cls closure
460  * @param message the message
461  */
462 static void
463 handle_dummy (void *cls,
464               const struct GNUNET_MessageHeader *message)
465 {
466   if (! benchmark_receive)
467     return;
468   if (verbosity > 0)
469     FPRINTF (stdout,
470              "Received %u bytes\n",
471              (unsigned int) ntohs (message->size));
472 }
473
474
475 static int
476 blacklist_cb (void *cls,
477               const struct GNUNET_PeerIdentity *peer)
478 {
479   if (0 != memcmp (&pid,
480                    peer,
481                    sizeof(struct GNUNET_PeerIdentity)))
482   {
483     if (verbosity > 0)
484       FPRINTF (stdout,
485                "Denying connection to `%s'\n",
486                GNUNET_i2s (peer));
487     return GNUNET_SYSERR;
488   }
489   return GNUNET_OK;
490 }
491
492
493 /**
494  * Main function that will be run by the scheduler.
495  *
496  * @param cls closure
497  * @param args remaining command-line arguments
498  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
499  * @param mycfg configuration
500  */
501 static void
502 run (void *cls,
503      char *const *args,
504      const char *cfgfile,
505      const struct GNUNET_CONFIGURATION_Handle *mycfg)
506 {
507   struct GNUNET_MQ_MessageHandler handlers[] = {
508     GNUNET_MQ_hd_var_size (dummy,
509                            GNUNET_MESSAGE_TYPE_DUMMY,
510                            struct GNUNET_MessageHeader,
511                            NULL),
512     GNUNET_MQ_handler_end ()
513   };
514   
515   cfg = (struct GNUNET_CONFIGURATION_Handle *) mycfg;
516
517   ret = 1;
518   if (GNUNET_MAX_MESSAGE_SIZE <= benchmark_size)
519   {
520     FPRINTF (stderr,
521              "Message size too big!\n");
522     return;
523   }
524
525   if (NULL == cpid)
526   {
527     FPRINTF (stderr,
528              "No peer identity given\n");
529     return;
530   }
531   if (GNUNET_OK !=
532       GNUNET_CRYPTO_eddsa_public_key_from_string (cpid,
533                                                   strlen (cpid),
534                                                   &pid.public_key))
535   {
536     FPRINTF (stderr,
537              "Failed to parse peer identity `%s'\n",
538              cpid);
539     return;
540   }
541   if (1 == benchmark_send)
542   {
543     if (verbosity > 0)
544       FPRINTF (stderr,
545                "Trying to send %u messages with size %u to peer `%s'\n",
546                benchmark_count, benchmark_size,
547                GNUNET_i2s (&pid));
548   }
549   else if (1 == benchmark_receive)
550   {
551     FPRINTF (stderr,
552              "Trying to receive messages from peer `%s'\n",
553              GNUNET_i2s (&pid));
554   }
555   else
556   {
557     FPRINTF (stderr,
558              "No operation given\n");
559     return;
560   }
561
562   ats = GNUNET_ATS_connectivity_init (cfg);
563   if (NULL == ats)
564   {
565     FPRINTF (stderr,
566              "Failed to connect to ATS service\n");
567     ret = 1;
568     return;
569   }
570
571   handle = GNUNET_TRANSPORT_core_connect (cfg,
572                                           NULL,
573                                           handlers,
574                                           NULL,
575                                           &notify_connect,
576                                           &notify_disconnect,
577                                           NULL);
578   if (NULL == handle)
579   {
580     FPRINTF (stderr,
581              "Failed to connect to transport service\n");
582     GNUNET_ATS_connectivity_done (ats);
583     ats = NULL;
584     ret = 1;
585     return;
586   }
587
588   bl_handle = GNUNET_TRANSPORT_blacklist (cfg,
589                                           &blacklist_cb,
590                                           NULL);
591   ats_sh = GNUNET_ATS_connectivity_suggest (ats,
592                                             &pid,
593                                             1);
594   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
595                                  NULL);
596 }
597
598
599 int
600 main (int argc, char * const *argv)
601 {
602   int res;
603   benchmark_count = DEFAULT_MESSAGE_COUNT;
604   benchmark_size = DEFAULT_MESSAGE_SIZE;
605   benchmark_iterations = DEFAULT_ITERATION_COUNT;
606   benchmark_running = GNUNET_NO;
607
608   struct GNUNET_GETOPT_CommandLineOption options[] = {
609
610     GNUNET_GETOPT_option_flag ('s',
611                                   "send",
612                                   gettext_noop ("send data to peer"),
613                                   &benchmark_send),
614     GNUNET_GETOPT_option_flag ('r',
615                                   "receive",
616                                   gettext_noop ("receive data from peer"),
617                                   &benchmark_receive),
618     GNUNET_GETOPT_option_uint ('i',
619                                    "iterations",
620                                    NULL,
621                                    gettext_noop ("iterations"),
622                                    &benchmark_iterations),
623     GNUNET_GETOPT_option_uint ('n',
624                                    "number",
625                                    NULL,
626                                    gettext_noop ("number of messages to send"),
627                                    &benchmark_count),
628     GNUNET_GETOPT_option_uint ('m',
629                                    "messagesize",
630                                    NULL,
631                                    gettext_noop ("message size to use"),
632                                    &benchmark_size),
633     GNUNET_GETOPT_option_string ('p',
634                                  "peer",
635                                  "PEER",
636                                  gettext_noop ("peer identity"),
637                                  &cpid),
638     GNUNET_GETOPT_option_verbose (&verbosity),
639     GNUNET_GETOPT_OPTION_END
640   };
641
642   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
643     return 2;
644
645   res = GNUNET_PROGRAM_run (argc, argv,
646                             "gnunet-transport",
647                             gettext_noop ("Direct access to transport service."),
648                             options,
649                             &run, NULL);
650   GNUNET_free((void *) argv);
651   if (GNUNET_OK == res)
652     return ret;
653   return 1;
654 }
655
656 /* end of gnunet-transport-profiler.c */