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