social: API changes for application connections: store/load app subscriptions to...
[oweals/gnunet.git] / src / transport / gnunet-transport-profiler.c
1 /*
2  This file is part of GNUnet.
3  Copyright (C) 2011-2015 Christian Grothoff (and other contributing authors)
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  * Task scheduled for cleanup / termination of the process.
150  */
151 static struct GNUNET_SCHEDULER_Task * end;
152
153 /**
154  * Selected level of verbosity.
155  */
156 static int verbosity;
157
158
159 /**
160  * Task run in monitor mode when the user presses CTRL-C to abort.
161  * Stops monitoring activity.
162  *
163  * @param cls NULL
164  * @param tc scheduler context
165  */
166 static void
167 shutdown_task (void *cls,
168                const struct GNUNET_SCHEDULER_TaskContext *tc)
169 {
170   struct Iteration *icur;
171   struct Iteration *inext;
172
173   unsigned int iterations;
174
175   unsigned long long avg_duration;
176   float avg_rate;
177   float stddev_rate;
178   float stddev_duration;
179
180   if (NULL != ats_sh)
181   {
182     GNUNET_ATS_connectivity_suggest_cancel (ats_sh);
183     ats_sh = NULL;
184   }
185   if (NULL != th)
186   {
187     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
188     th = NULL;
189   }
190   if (NULL != bl_handle )
191   {
192     GNUNET_TRANSPORT_blacklist_cancel (bl_handle);
193     bl_handle = NULL;
194   }
195   if (NULL != ats)
196   {
197     GNUNET_ATS_connectivity_done (ats);
198     ats = NULL;
199   }
200   if (NULL != handle)
201   {
202     GNUNET_TRANSPORT_disconnect (handle);
203     handle = NULL;
204   }
205
206   if (verbosity > 0)
207     FPRINTF (stdout, "\n");
208
209   /* Output format:
210    * All time values in ms
211    * Rate in KB/s
212    * #messages;#messagesize;#avg_dur;#avg_rate;#duration_i0;#duration_i0;... */
213
214   if (benchmark_send)
215   {
216     /* First iteration to calculcate avg and stddev */
217     iterations = 0;
218     avg_duration = 0;
219     avg_rate = 0.0;
220
221     inext = ihead;
222     while (NULL != (icur = inext))
223     {
224       inext = icur->next;
225       icur->rate = ((benchmark_count * benchmark_size) / 1024) /
226           ((float) icur->dur.rel_value_us / (1000 * 1000));
227       if (verbosity > 0)
228         FPRINTF (stdout, _("%llu B in %llu ms == %.2f KB/s!\n"),
229             ((long long unsigned int) benchmark_count * benchmark_size),
230             ((long long unsigned int) icur->dur.rel_value_us / 1000),
231             (float) icur->rate);
232
233       avg_duration += icur->dur.rel_value_us / (1000);
234       avg_rate  += icur->rate;
235       iterations ++;
236     }
237
238     /* Calculate average rate */
239     avg_rate /= iterations;
240     /* Calculate average duration */
241     avg_duration /= iterations;
242
243     stddev_rate = 0;
244     stddev_duration = 0;
245     inext = ihead;
246     while (NULL != (icur = inext))
247     {
248       inext = icur->next;
249       stddev_rate += ((icur->rate-avg_rate) *
250           (icur->rate-avg_rate));
251       stddev_duration += (((icur->dur.rel_value_us / 1000) - avg_duration) *
252           ((icur->dur.rel_value_us / 1000) - avg_duration));
253
254     }
255     /* Calculate standard deviation rate */
256     stddev_rate = stddev_rate / iterations;
257     stddev_rate = sqrtf(stddev_rate);
258
259     /* Calculate standard deviation duration */
260     stddev_duration = stddev_duration / iterations;
261     stddev_duration = sqrtf(stddev_duration);
262
263     /* Output */
264     FPRINTF (stdout, _("%u;%u;%llu;%llu;%.2f;%.2f"),benchmark_count, benchmark_size,
265         avg_duration, (unsigned long long) stddev_duration, avg_rate, stddev_rate);
266
267     inext = ihead;
268     while (NULL != (icur = inext))
269     {
270       inext = icur->next;
271       GNUNET_CONTAINER_DLL_remove (ihead, itail, icur);
272
273       FPRINTF (stdout, _(";%llu;%.2f"),
274           (long long unsigned int) (icur->dur.rel_value_us / 1000), icur->rate);
275
276       GNUNET_free (icur);
277     }
278   }
279 #if 0
280   if (benchmark_receive)
281   {
282     duration = GNUNET_TIME_absolute_get_duration (start_time);
283     FPRINTF (stdout,
284              _("Received %llu bytes/s (%llu bytes in %s)\n"),
285              1000LL * 1000LL * traffic_received / (1 + duration.rel_value_us),
286              traffic_received,
287              GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
288   }
289 #endif
290   FPRINTF (stdout, _("\n"));
291 }
292
293 static void
294 iteration_done ();
295
296
297 /**
298  * Function called to notify a client about the socket
299  * begin ready to queue more data.  @a buf will be
300  * NULL and @a size zero if the socket was closed for
301  * writing in the meantime.
302  *
303  * @param cls closure
304  * @param size number of bytes available in @a buf
305  * @param buf where the callee should write the message
306  * @return number of bytes written to @a buf
307  */
308 static size_t
309 transmit_data (void *cls,
310                size_t size,
311                void *buf)
312 {
313   struct GNUNET_MessageHeader *m = buf;
314
315   th = NULL;
316   if ((NULL == buf) || (0 == size))
317   {
318     th = NULL;
319     return 0;
320   }
321
322   itail->msgs_sent ++;
323
324   GNUNET_assert(size >= sizeof(struct GNUNET_MessageHeader));
325   GNUNET_assert(size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
326   m->size = ntohs (size);
327   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
328   memset (&m[1], 52, size - sizeof(struct GNUNET_MessageHeader));
329
330   if (itail->msgs_sent < benchmark_count)
331   {
332     th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, benchmark_size,
333         GNUNET_TIME_UNIT_FOREVER_REL, &transmit_data, NULL );
334   }
335   else
336   {
337
338     iteration_done();
339     return size;
340   }
341   if (verbosity > 0)
342     if (itail->msgs_sent % 10 == 0 )
343     FPRINTF (stdout, _("."));
344   return size;
345 }
346
347
348 static void
349 iteration_start ()
350 {
351   struct Iteration *icur;
352   ret = 0;
353
354   if (benchmark_send)
355   {
356     benchmark_running = GNUNET_YES;
357     icur = GNUNET_new (struct Iteration);
358     GNUNET_CONTAINER_DLL_insert_tail (ihead, itail, icur);
359     icur->start = GNUNET_TIME_absolute_get();
360
361     if (verbosity > 0)
362       FPRINTF (stdout,
363           _("\nStarting benchmark to `%s', starting to send %u messages in %u byte blocks\n"),
364           GNUNET_i2s (&pid), benchmark_count, benchmark_size);
365     if (NULL == th)
366       th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, benchmark_size,
367           GNUNET_TIME_UNIT_FOREVER_REL, &transmit_data, NULL );
368     else
369       GNUNET_break(0);
370     return;
371   }
372 }
373
374
375 static void
376 iteration_done ()
377 {
378   static int it_count = 0;
379   it_count ++;
380
381   itail->dur = GNUNET_TIME_absolute_get_duration (itail->start);
382   if (it_count == benchmark_iterations)
383   {
384     benchmark_running = GNUNET_NO;
385     if (NULL != end)
386       GNUNET_SCHEDULER_cancel (end);
387     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
388     return;
389   }
390   else
391   {
392     iteration_start ();
393   }
394 }
395
396
397 /**
398  * Function called to notify transport users that another
399  * peer connected to us.
400  *
401  * @param cls closure
402  * @param peer the peer that connected
403  */
404 static void
405 notify_connect (void *cls,
406                 const struct GNUNET_PeerIdentity *peer)
407 {
408   if (0 != memcmp (&pid,
409                    peer,
410                    sizeof(struct GNUNET_PeerIdentity)))
411   {
412     FPRINTF (stdout,
413              _("Connected to different peer `%s'\n"),
414              GNUNET_i2s (&pid));
415     return;
416   }
417
418   if (verbosity > 0)
419     FPRINTF (stdout,
420         _("Successfully connected to `%s'\n"),
421         GNUNET_i2s (&pid));
422   iteration_start ();
423 }
424
425
426 /**
427  * Function called to notify transport users that another
428  * peer disconnected from us.
429  *
430  * @param cls closure
431  * @param peer the peer that disconnected
432  */
433 static void
434 notify_disconnect (void *cls,
435                    const struct GNUNET_PeerIdentity *peer)
436 {
437   if (0 != memcmp (&pid, peer, sizeof(struct GNUNET_PeerIdentity)))
438     return;
439   if (GNUNET_YES == benchmark_running)
440   {
441     FPRINTF (stdout, _("Disconnected from peer `%s' while benchmarking\n"),
442         GNUNET_i2s (&pid));
443     return;
444   }
445 }
446
447
448 /**
449  * Function called by the transport for each received message.
450  *
451  * @param cls closure
452  * @param peer (claimed) identity of the other peer
453  * @param message the message
454  */
455 static void
456 notify_receive (void *cls,
457                 const struct GNUNET_PeerIdentity *peer,
458                 const struct GNUNET_MessageHeader *message)
459 {
460   if (benchmark_receive)
461   {
462     if (GNUNET_MESSAGE_TYPE_DUMMY != ntohs (message->type))
463       return;
464     if (verbosity > 0)
465       FPRINTF (stdout,
466                _("Received %u bytes from %s\n"),
467                (unsigned int) ntohs (message->size),
468                GNUNET_i2s (peer));
469     return;
470   }
471 }
472
473
474 static int
475 blacklist_cb (void *cls,
476               const struct GNUNET_PeerIdentity *peer)
477 {
478   if (0 != memcmp (&pid, peer, sizeof(struct GNUNET_PeerIdentity)))
479   {
480     if (verbosity > 0)
481       FPRINTF (stdout,
482                _("Denying connection to `%s'\n"),
483                GNUNET_i2s (peer));
484     return GNUNET_SYSERR;
485   }
486
487   return GNUNET_OK;
488 }
489
490
491
492 /**
493  * Function called with the result of the check if the 'transport'
494  * service is running.
495  *
496  * @param cls closure with our configuration
497  * @param result #GNUNET_YES if transport is running
498  */
499 static void
500 testservice_task (void *cls, int result)
501 {
502   ret = 1;
503
504   if (GNUNET_YES != result)
505   {
506     FPRINTF (stderr, _("Service `%s' is not running\n"), "transport");
507     return;
508   }
509
510   if (GNUNET_SERVER_MAX_MESSAGE_SIZE <= benchmark_size)
511   {
512     FPRINTF (stderr, _("Message size too big!\n"));
513     return;
514   }
515
516   if (NULL == cpid)
517   {
518     FPRINTF (stderr, _("No peer identity given\n"));
519     return;
520   }
521   if ((GNUNET_OK !=
522        GNUNET_CRYPTO_eddsa_public_key_from_string (cpid, strlen (cpid),
523                                                    &pid.public_key)))
524   {
525     FPRINTF (stderr, _("Failed to parse peer identity `%s'\n"), cpid);
526     return;
527   }
528
529   if (1 == benchmark_send)
530   {
531     if (verbosity > 0)
532       FPRINTF (stderr,
533         _("Trying to send %u messages with size %u to peer `%s'\n"),
534           benchmark_count, benchmark_size, GNUNET_i2s (&pid));
535   }
536   else if (1 == benchmark_receive)
537   {
538     FPRINTF (stderr,
539         _("Trying to receive messages from peer `%s'\n"),
540         GNUNET_i2s (&pid));
541   }
542   else
543   {
544     FPRINTF (stderr, _("No operation given\n"));
545     return;
546   }
547
548   ats = GNUNET_ATS_connectivity_init (cfg);
549   if (NULL == ats)
550   {
551     FPRINTF (stderr, "%s", _("Failed to connect to ATS service\n"));
552     ret = 1;
553     return;
554   }
555
556   handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL,
557                                      &notify_receive,
558                                      &notify_connect,
559                                      &notify_disconnect);
560   if (NULL == handle)
561   {
562     FPRINTF (stderr, "%s", _("Failed to connect to transport service\n"));
563     GNUNET_ATS_connectivity_done (ats);
564     ats = NULL;
565     ret = 1;
566     return;
567   }
568
569   bl_handle = GNUNET_TRANSPORT_blacklist (cfg,
570                                           &blacklist_cb,
571                                           NULL);
572   ats_sh = GNUNET_ATS_connectivity_suggest (ats,
573                                             &pid,
574                                             1);
575   end = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
576                                       &shutdown_task,
577                                       NULL);
578 }
579
580
581 /**
582  * Main function that will be run by the scheduler.
583  *
584  * @param cls closure
585  * @param args remaining command-line arguments
586  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
587  * @param mycfg configuration
588  */
589 static void
590 run (void *cls,
591      char * const *args,
592      const char *cfgfile,
593      const struct GNUNET_CONFIGURATION_Handle *mycfg)
594 {
595   cfg = (struct GNUNET_CONFIGURATION_Handle *) mycfg;
596   GNUNET_CLIENT_service_test ("transport", cfg, GNUNET_TIME_UNIT_SECONDS,
597       &testservice_task, (void *) cfg);
598 }
599
600
601 int
602 main (int argc, char * const *argv)
603 {
604   int res;
605   benchmark_count = DEFAULT_MESSAGE_COUNT;
606   benchmark_size = DEFAULT_MESSAGE_SIZE;
607   benchmark_iterations = DEFAULT_ITERATION_COUNT;
608   benchmark_running = GNUNET_NO;
609
610   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
611
612     { 's', "send", NULL,
613       gettext_noop ("send data to peer"),
614       0, &GNUNET_GETOPT_set_one, &benchmark_send},
615     { 'r', "receive", NULL, gettext_noop
616       ("receive data from peer"), 0,
617       &GNUNET_GETOPT_set_one, &benchmark_receive},
618     { 'i', "iterations", NULL, gettext_noop
619       ("iterations"), 1,
620       &GNUNET_GETOPT_set_uint, &benchmark_iterations},
621     { 'n', "number", NULL, gettext_noop
622       ("number of messages to send"), 1,
623       &GNUNET_GETOPT_set_uint, &benchmark_count},
624     { 'm', "messagesize", NULL, gettext_noop
625       ("message size to use"), 1,
626       &GNUNET_GETOPT_set_uint, &benchmark_size},
627     { 'p', "peer", "PEER",
628       gettext_noop ("peer identity"), 1, &GNUNET_GETOPT_set_string,
629       &cpid },
630     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
631     GNUNET_GETOPT_OPTION_END
632   };
633
634   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
635     return 2;
636
637   res = GNUNET_PROGRAM_run (argc, argv,
638                             "gnunet-transport",
639                             gettext_noop ("Direct access to transport service."),
640                             options,
641                             &run, NULL);
642   GNUNET_free((void *) argv);
643   if (GNUNET_OK == res)
644     return ret;
645   return 1;
646 }
647
648 /* end of gnunet-transport-profiler.c */