- fix coverity
[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     if (0 == iterations)
231       iterations = 1; /* avoid division by zero */
232     /* Calculate average rate */
233     avg_rate /= iterations;
234     /* Calculate average duration */
235     avg_duration /= iterations;
236
237     stddev_rate = 0;
238     stddev_duration = 0;
239     inext = ihead;
240     while (NULL != (icur = inext))
241     {
242       inext = icur->next;
243       stddev_rate += ((icur->rate-avg_rate) *
244           (icur->rate-avg_rate));
245       stddev_duration += (((icur->dur.rel_value_us / 1000) - avg_duration) *
246           ((icur->dur.rel_value_us / 1000) - avg_duration));
247
248     }
249     /* Calculate standard deviation rate */
250     stddev_rate = stddev_rate / iterations;
251     stddev_rate = sqrtf(stddev_rate);
252
253     /* Calculate standard deviation duration */
254     stddev_duration = stddev_duration / iterations;
255     stddev_duration = sqrtf(stddev_duration);
256
257     /* Output */
258     FPRINTF (stdout,
259              "%u;%u;%llu;%llu;%.2f;%.2f",
260              benchmark_count,
261              benchmark_size,
262              avg_duration,
263              (unsigned long long) stddev_duration,
264              avg_rate,
265              stddev_rate);
266
267     inext = ihead;
268     while (NULL != (icur = inext))
269     {
270       inext = icur->next;
271       GNUNET_CONTAINER_DLL_remove (ihead,
272                                    itail,
273                                    icur);
274
275       FPRINTF (stdout,
276                ";%llu;%.2f",
277                (long long unsigned int) (icur->dur.rel_value_us / 1000),
278                icur->rate);
279
280       GNUNET_free (icur);
281     }
282   }
283 #if 0
284   if (benchmark_receive)
285   {
286     duration = GNUNET_TIME_absolute_get_duration (start_time);
287     FPRINTF (stdout,
288              "Received %llu bytes/s (%llu bytes in %s)\n",
289              1000LL * 1000LL * traffic_received / (1 + duration.rel_value_us),
290              traffic_received,
291              GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
292   }
293 #endif
294   FPRINTF (stdout, "\n");
295 }
296
297 static void
298 iteration_done ();
299
300
301 /**
302  * Function called to notify a client about the socket
303  * begin ready to queue more data.  @a buf will be
304  * NULL and @a size zero if the socket was closed for
305  * writing in the meantime.
306  *
307  * @param cls closure
308  * @param size number of bytes available in @a buf
309  * @param buf where the callee should write the message
310  * @return number of bytes written to @a buf
311  */
312 static size_t
313 transmit_data (void *cls,
314                size_t size,
315                void *buf)
316 {
317   struct GNUNET_MessageHeader *m = buf;
318
319   th = NULL;
320   if ((NULL == buf) || (0 == size))
321   {
322     th = NULL;
323     return 0;
324   }
325
326   itail->msgs_sent ++;
327
328   GNUNET_assert(size >= sizeof(struct GNUNET_MessageHeader));
329   GNUNET_assert(size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
330   m->size = ntohs (size);
331   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
332   memset (&m[1], 52, size - sizeof(struct GNUNET_MessageHeader));
333
334   if (itail->msgs_sent < benchmark_count)
335   {
336     th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, benchmark_size,
337         GNUNET_TIME_UNIT_FOREVER_REL, &transmit_data, NULL );
338   }
339   else
340   {
341
342     iteration_done();
343     return size;
344   }
345   if (verbosity > 0)
346     if (itail->msgs_sent % 10 == 0 )
347     FPRINTF (stdout, ".");
348   return size;
349 }
350
351
352 static void
353 iteration_start ()
354 {
355   struct Iteration *icur;
356   ret = 0;
357
358   if (benchmark_send)
359   {
360     benchmark_running = GNUNET_YES;
361     icur = GNUNET_new (struct Iteration);
362     GNUNET_CONTAINER_DLL_insert_tail (ihead, itail, icur);
363     icur->start = GNUNET_TIME_absolute_get();
364
365     if (verbosity > 0)
366       FPRINTF (stdout,
367                "\nStarting benchmark to `%s', starting to send %u messages in %u byte blocks\n",
368                GNUNET_i2s (&pid),
369                benchmark_count,
370                benchmark_size);
371     if (NULL == th)
372       th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, benchmark_size,
373           GNUNET_TIME_UNIT_FOREVER_REL, &transmit_data, NULL );
374     else
375       GNUNET_break(0);
376     return;
377   }
378 }
379
380
381 static void
382 iteration_done ()
383 {
384   static int it_count = 0;
385   it_count ++;
386
387   itail->dur = GNUNET_TIME_absolute_get_duration (itail->start);
388   if (it_count == benchmark_iterations)
389   {
390     benchmark_running = GNUNET_NO;
391     GNUNET_SCHEDULER_shutdown ();
392     return;
393   }
394   else
395   {
396     iteration_start ();
397   }
398 }
399
400
401 /**
402  * Function called to notify transport users that another
403  * peer connected to us.
404  *
405  * @param cls closure
406  * @param peer the peer that connected
407  */
408 static void
409 notify_connect (void *cls,
410                 const struct GNUNET_PeerIdentity *peer)
411 {
412   if (0 != memcmp (&pid,
413                    peer,
414                    sizeof(struct GNUNET_PeerIdentity)))
415   {
416     FPRINTF (stdout,
417              "Connected to different peer `%s'\n",
418              GNUNET_i2s (&pid));
419     return;
420   }
421
422   if (verbosity > 0)
423     FPRINTF (stdout,
424              "Successfully connected to `%s'\n",
425              GNUNET_i2s (&pid));
426   iteration_start ();
427 }
428
429
430 /**
431  * Function called to notify transport users that another
432  * peer disconnected from us.
433  *
434  * @param cls closure
435  * @param peer the peer that disconnected
436  */
437 static void
438 notify_disconnect (void *cls,
439                    const struct GNUNET_PeerIdentity *peer)
440 {
441   if (0 != memcmp (&pid, peer, sizeof(struct GNUNET_PeerIdentity)))
442     return;
443   if (GNUNET_YES == benchmark_running)
444   {
445     FPRINTF (stdout,
446              "Disconnected from peer `%s' while benchmarking\n",
447         GNUNET_i2s (&pid));
448     return;
449   }
450 }
451
452
453 /**
454  * Function called by the transport for each received message.
455  *
456  * @param cls closure
457  * @param peer (claimed) identity of the other peer
458  * @param message the message
459  */
460 static void
461 notify_receive (void *cls,
462                 const struct GNUNET_PeerIdentity *peer,
463                 const struct GNUNET_MessageHeader *message)
464 {
465   if (benchmark_receive)
466   {
467     if (GNUNET_MESSAGE_TYPE_DUMMY != ntohs (message->type))
468       return;
469     if (verbosity > 0)
470       FPRINTF (stdout,
471                "Received %u bytes from %s\n",
472                (unsigned int) ntohs (message->size),
473                GNUNET_i2s (peer));
474     return;
475   }
476 }
477
478
479 static int
480 blacklist_cb (void *cls,
481               const struct GNUNET_PeerIdentity *peer)
482 {
483   if (0 != memcmp (&pid, peer, sizeof(struct GNUNET_PeerIdentity)))
484   {
485     if (verbosity > 0)
486       FPRINTF (stdout,
487                "Denying connection to `%s'\n",
488                GNUNET_i2s (peer));
489     return GNUNET_SYSERR;
490   }
491
492   return GNUNET_OK;
493 }
494
495
496
497 /**
498  * Function called with the result of the check if the 'transport'
499  * service is running.
500  *
501  * @param cls closure with our configuration
502  * @param result #GNUNET_YES if transport is running
503  */
504 static void
505 testservice_task (void *cls, int result)
506 {
507   ret = 1;
508
509   if (GNUNET_YES != result)
510   {
511     FPRINTF (stderr,
512              "TRANSPORT service is not running\n");
513     return;
514   }
515
516   if (GNUNET_SERVER_MAX_MESSAGE_SIZE <= benchmark_size)
517   {
518     FPRINTF (stderr,
519              "Message size too big!\n");
520     return;
521   }
522
523   if (NULL == cpid)
524   {
525     FPRINTF (stderr,
526              "No peer identity given\n");
527     return;
528   }
529   if ((GNUNET_OK !=
530        GNUNET_CRYPTO_eddsa_public_key_from_string (cpid, strlen (cpid),
531                                                    &pid.public_key)))
532   {
533     FPRINTF (stderr,
534              "Failed to parse peer identity `%s'\n",
535              cpid);
536     return;
537   }
538
539   if (1 == benchmark_send)
540   {
541     if (verbosity > 0)
542       FPRINTF (stderr,
543                "Trying to send %u messages with size %u to peer `%s'\n",
544                benchmark_count, benchmark_size,
545                GNUNET_i2s (&pid));
546   }
547   else if (1 == benchmark_receive)
548   {
549     FPRINTF (stderr,
550              "Trying to receive messages from peer `%s'\n",
551              GNUNET_i2s (&pid));
552   }
553   else
554   {
555     FPRINTF (stderr,
556              "No operation given\n");
557     return;
558   }
559
560   ats = GNUNET_ATS_connectivity_init (cfg);
561   if (NULL == ats)
562   {
563     FPRINTF (stderr,
564              "Failed to connect to ATS service\n");
565     ret = 1;
566     return;
567   }
568
569   handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL,
570                                      &notify_receive,
571                                      &notify_connect,
572                                      &notify_disconnect);
573   if (NULL == handle)
574   {
575     FPRINTF (stderr,
576              "Failed to connect to transport service\n");
577     GNUNET_ATS_connectivity_done (ats);
578     ats = NULL;
579     ret = 1;
580     return;
581   }
582
583   bl_handle = GNUNET_TRANSPORT_blacklist (cfg,
584                                           &blacklist_cb,
585                                           NULL);
586   ats_sh = GNUNET_ATS_connectivity_suggest (ats,
587                                             &pid,
588                                             1);
589   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
590                                  NULL);
591 }
592
593
594 /**
595  * Main function that will be run by the scheduler.
596  *
597  * @param cls closure
598  * @param args remaining command-line arguments
599  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
600  * @param mycfg configuration
601  */
602 static void
603 run (void *cls,
604      char * const *args,
605      const char *cfgfile,
606      const struct GNUNET_CONFIGURATION_Handle *mycfg)
607 {
608   cfg = (struct GNUNET_CONFIGURATION_Handle *) mycfg;
609   GNUNET_CLIENT_service_test ("transport",
610                               cfg,
611                               GNUNET_TIME_UNIT_SECONDS,
612                               &testservice_task,
613                               (void *) cfg);
614 }
615
616
617 int
618 main (int argc, char * const *argv)
619 {
620   int res;
621   benchmark_count = DEFAULT_MESSAGE_COUNT;
622   benchmark_size = DEFAULT_MESSAGE_SIZE;
623   benchmark_iterations = DEFAULT_ITERATION_COUNT;
624   benchmark_running = GNUNET_NO;
625
626   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
627
628     { 's', "send", NULL,
629       gettext_noop ("send data to peer"),
630       0, &GNUNET_GETOPT_set_one, &benchmark_send},
631     { 'r', "receive", NULL, gettext_noop
632       ("receive data from peer"), 0,
633       &GNUNET_GETOPT_set_one, &benchmark_receive},
634     { 'i', "iterations", NULL, gettext_noop
635       ("iterations"), 1,
636       &GNUNET_GETOPT_set_uint, &benchmark_iterations},
637     { 'n', "number", NULL, gettext_noop
638       ("number of messages to send"), 1,
639       &GNUNET_GETOPT_set_uint, &benchmark_count},
640     { 'm', "messagesize", NULL, gettext_noop
641       ("message size to use"), 1,
642       &GNUNET_GETOPT_set_uint, &benchmark_size},
643     { 'p', "peer", "PEER",
644       gettext_noop ("peer identity"), 1, &GNUNET_GETOPT_set_string,
645       &cpid },
646     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
647     GNUNET_GETOPT_OPTION_END
648   };
649
650   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
651     return 2;
652
653   res = GNUNET_PROGRAM_run (argc, argv,
654                             "gnunet-transport",
655                             gettext_noop ("Direct access to transport service."),
656                             options,
657                             &run, NULL);
658   GNUNET_free((void *) argv);
659   if (GNUNET_OK == res)
660     return ret;
661   return 1;
662 }
663
664 /* end of gnunet-transport-profiler.c */