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