add -w option to gnunet-config
[oweals/gnunet.git] / src / dht / gnunet_dht_profiler.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2014 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 dht/gnunet_dht_profiler.c
23  * @brief Profiler for GNUnet DHT
24  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_testbed_service.h"
30 #include "gnunet_dht_service.h"
31
32 #define INFO(...)                                       \
33   GNUNET_log (GNUNET_ERROR_TYPE_INFO, __VA_ARGS__)
34
35 #define DEBUG(...)                                           \
36   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
37
38 /**
39  * Number of peers which should perform a PUT out of 100 peers
40  */
41 #define PUT_PROBABILITY 50
42
43 #if ENABLE_MALICIOUS
44 /**
45  * Number of peers which should act as malicious peers
46  */
47 #define MALICIOUS_PROBABILITY 20
48
49 /**
50  * Context for a peer which should act maliciously.
51  */
52 struct MaliciousContext;
53 #endif
54
55
56 /**
57  * Configuration
58  */
59 static struct GNUNET_CONFIGURATION_Handle *cfg;
60
61 /**
62  * Name of the file with the hosts to run the test over
63  */
64 static char *hosts_file;
65
66 /**
67  * Context for a peer which actively does DHT PUT/GET
68  */
69 struct ActiveContext;
70
71 /**
72  * Context to hold data of peer
73  */
74 struct Context
75 {
76   /**
77    * The testbed peer this context belongs to
78    */
79   struct GNUNET_TESTBED_Peer *peer;
80
81   /**
82    * Testbed operation acting on this peer
83    */
84   struct GNUNET_TESTBED_Operation *op;
85
86   /**
87    * Active context; NULL if this peer is not an active peer
88    */
89   struct ActiveContext *ac;
90
91 #if ENABLE_MALICIOUS
92   /**
93    * Malicious context; NULL if this peer is NOT malicious.
94    */
95   struct MaliciousContext *mc;
96 #endif
97 };
98
99
100 #if ENABLE_MALICIOUS
101 /**
102  * Context for a peer which should act maliciously.
103  */
104 struct MaliciousContext
105 {
106   /**
107    * The linked peer context
108    */
109   struct Context *ctx;
110
111   /**
112    * Handler to the DHT service
113    */
114   struct GNUNET_DHT_Handle *dht;
115
116   /**
117    * Handler to malicious api
118    */
119   struct GNUNET_DHT_ActMaliciousHandle *dht_malicious;
120 };
121
122 /**
123  * List of all the malicious peers contexts.
124  */
125 struct Context **malicious_peer_contexts = NULL;
126
127 /**
128  * Context for a peer which should act maliciously.
129  */
130 struct Malicious_Context
131 {
132   /**
133    * The linked peer context
134    */
135   struct Context *ctx;
136
137   /**
138    * Handler to the DHT service
139    */
140   struct GNUNET_DHT_Handle *dht;
141 };
142
143 /**
144  * Array of malicious peers.
145  */
146 static struct MaliciousContext *a_mc;
147
148 /**
149  * Number or malicious peers.
150  */
151 static unsigned int n_malicious;
152
153 #endif
154
155 /**
156  * Context for a peer which actively does DHT PUT/GET
157  */
158 struct ActiveContext
159 {
160   /**
161    * The linked peer context
162    */
163   struct Context *ctx;
164
165   /**
166    * Handler to the DHT service
167    */
168   struct GNUNET_DHT_Handle *dht;
169
170   /**
171    * The data used for do a PUT.  Will be NULL if a PUT hasn't been performed yet
172    */
173   void *put_data;
174
175   /**
176    * The active context used for our DHT GET
177    */
178   struct ActiveContext *get_ac;
179
180   /**
181    * The put handle
182    */
183   struct GNUNET_DHT_PutHandle *dht_put;
184
185   /**
186    * The get handle
187    */
188   struct GNUNET_DHT_GetHandle *dht_get;
189
190   /**
191    * The hash of the @e put_data
192    */
193   struct GNUNET_HashCode hash;
194
195   /**
196    * Delay task
197    */
198   struct GNUNET_SCHEDULER_Task * delay_task;
199
200   /**
201    * The size of the @e put_data
202    */
203   uint16_t put_data_size;
204
205   /**
206    * The number of peers currently doing GET on our data
207    */
208   uint16_t nrefs;
209 };
210
211
212 /**
213  * An array of contexts.  The size of this array should be equal to @a num_peers
214  */
215 static struct Context *a_ctx;
216
217 /**
218  * Array of active peers
219  */
220 static struct ActiveContext *a_ac;
221
222 /**
223  * The delay between rounds for collecting statistics
224  */
225 static struct GNUNET_TIME_Relative delay_stats;
226
227 /**
228  * The delay to start puts.
229  */
230 static struct GNUNET_TIME_Relative delay_put;
231
232 /**
233  * The delay to start puts.
234  */
235 static struct GNUNET_TIME_Relative delay_get;
236
237 /**
238  * The timeout for GET and PUT
239  */
240 static struct GNUNET_TIME_Relative timeout;
241
242 /**
243  * Number of peers
244  */
245 static unsigned int num_peers;
246
247 /**
248  * Number of active peers
249  */
250 static unsigned int n_active;
251
252 /**
253  * Number of DHT service connections we currently have
254  */
255 static unsigned int n_dht;
256
257 /**
258  * Number of DHT PUTs made
259  */
260 static unsigned int n_puts;
261
262 /**
263  * Number of DHT PUTs succeeded
264  */
265 static unsigned int n_puts_ok;
266
267 /**
268  * Number of DHT PUTs failed
269  */
270 static unsigned int n_puts_fail;
271
272 /**
273  * Number of DHT GETs made
274  */
275 static unsigned int n_gets;
276
277 /**
278  * Number of DHT GETs succeeded
279  */
280 static unsigned int n_gets_ok;
281
282 /**
283  * Number of DHT GETs succeeded
284  */
285 static unsigned int n_gets_fail;
286
287 /**
288  * Replication degree
289  */
290 static unsigned int replication;
291
292 /**
293  * Number of times we try to find the successor circle formation
294  */
295 static unsigned int max_searches;
296
297 /**
298  * Testbed Operation (to get stats).
299  */
300 static struct GNUNET_TESTBED_Operation *bandwidth_stats_op;
301
302 /**
303  * To get successor stats.
304  */
305 static struct GNUNET_TESTBED_Operation *successor_stats_op;
306
307 /**
308  * Testbed peer handles.
309  */
310 static struct GNUNET_TESTBED_Peer **testbed_handles;
311
312 /**
313  * Total number of messages sent by peer.
314  */
315 static uint64_t outgoing_bandwidth;
316
317 /**
318  * Total number of messages received by peer.
319  */
320 static uint64_t incoming_bandwidth;
321
322 /**
323  * Average number of hops taken to do put.
324  */
325 static double average_put_path_length;
326
327 /**
328  * Average number of hops taken to do get.
329  */
330 static double average_get_path_length;
331
332 /**
333  * Total put path length across all peers.
334  */
335 static unsigned int total_put_path_length;
336
337 /**
338  * Total get path length across all peers.
339  */
340 static unsigned int total_get_path_length;
341
342 /**
343  * Hashmap to store pair of peer and its corresponding successor.
344  */
345 static struct GNUNET_CONTAINER_MultiHashMap *successor_peer_hashmap;
346
347 /**
348  * Key to start the lookup on successor_peer_hashmap.
349  */
350 static struct GNUNET_HashCode *start_key;
351
352 /**
353  * Flag used to get the start_key.
354  */
355 static int flag = 0;
356
357 /**
358  * Task to collect peer and its current successor statistics.
359  */
360 static struct GNUNET_SCHEDULER_Task * successor_stats_task;
361
362 /**
363  * Closure for successor_stats_task.
364  */
365 struct Collect_Stat_Context
366 {
367   /**
368    * Current Peer Context.
369    */
370   struct Context *service_connect_ctx;
371
372   /**
373    * Testbed operation acting on this peer
374    */
375   struct GNUNET_TESTBED_Operation *op;
376 };
377
378 /**
379  * List of all the peers contexts.
380  */
381 struct Context **peer_contexts = NULL;
382
383 /**
384  * Counter to keep track of peers added to peer_context lists.
385  */
386 static int peers_started = 0;
387
388 /**
389  * Should we do a PUT (mode = 0) or GET (mode = 1);
390  */
391 static enum
392 {
393   MODE_PUT = 0,
394
395   MODE_GET = 1
396 } mode;
397
398
399 /**
400  * Are we shutting down
401  */
402 static int in_shutdown = 0;
403
404 /**
405  * Total number of times to check if circle is formed or not.
406  */
407 static unsigned int tries;
408
409
410 /**
411  * Task that collects successor statistics from all the peers.
412  *
413  * @param cls
414  */
415 static void
416 collect_stats (void *cls);
417
418
419 /**
420  * Connect to DHT services of active peers
421  */
422 static void
423 start_profiling (void);
424
425
426 /**
427  * Shutdown task.  Cleanup all resources and operations.
428  *
429  * @param cls NULL
430  */
431 static void
432 do_shutdown (void *cls)
433 {
434   struct ActiveContext *ac;
435   unsigned int cnt;
436
437   in_shutdown = GNUNET_YES;
438   if (NULL != a_ctx)
439   {
440     for (cnt=0; cnt < num_peers; cnt++)
441     {
442       /* Cleanup active context if this peer is an active peer */
443       ac = a_ctx[cnt].ac;
444       if (NULL != ac)
445       {
446         if (NULL != ac->delay_task)
447           GNUNET_SCHEDULER_cancel (ac->delay_task);
448         if (NULL != ac->put_data)
449           GNUNET_free (ac->put_data);
450         if (NULL != ac->dht_put)
451           GNUNET_DHT_put_cancel (ac->dht_put);
452         if (NULL != ac->dht_get)
453           GNUNET_DHT_get_stop (ac->dht_get);
454       }
455       /* Cleanup testbed operation handle at the last as this operation may
456          contain service connection to DHT */
457       if (NULL != a_ctx[cnt].op)
458         GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
459     }
460     GNUNET_free (a_ctx);
461     a_ctx = NULL;
462   }
463   //FIXME: Should we collect stats only for put/get not for other messages.
464   if (NULL != bandwidth_stats_op)
465   {
466     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
467     bandwidth_stats_op = NULL;
468   }
469   if (NULL != successor_stats_op)
470   {
471     GNUNET_TESTBED_operation_done (successor_stats_op);
472     successor_stats_op = NULL;
473   }
474   if (NULL != successor_stats_task)
475   {
476     GNUNET_SCHEDULER_cancel (successor_stats_task);
477     successor_stats_task = NULL;
478   }
479   GNUNET_free_non_null (a_ac);
480 }
481
482
483 /**
484  * Stats callback. Finish the stats testbed operation and when all stats have
485  * been iterated, shutdown the test.
486  *
487  * @param cls closure
488  * @param op the operation that has been finished
489  * @param emsg error message in case the operation has failed; will be NULL if
490  *          operation has executed successfully.
491  */
492 static void
493 bandwidth_stats_cont (void *cls,
494                       struct GNUNET_TESTBED_Operation *op,
495                       const char *emsg)
496 {
497   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
498   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
499   GNUNET_SCHEDULER_shutdown ();
500 }
501
502
503 /**
504  * Process statistic values.
505  *
506  * @param cls closure
507  * @param peer the peer the statistic belong to
508  * @param subsystem name of subsystem that created the statistic
509  * @param name the name of the datum
510  * @param value the current value
511  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
512  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
513  */
514 static int
515 bandwidth_stats_iterator (void *cls,
516                           const struct GNUNET_TESTBED_Peer *peer,
517                           const char *subsystem,
518                           const char *name,
519                           uint64_t value,
520                           int is_persistent)
521 {
522    static const char *s_sent = "# Bytes transmitted to other peers";
523    static const char *s_recv = "# Bytes received from other peers";
524
525    if (0 == strncmp (s_sent, name, strlen (s_sent)))
526      outgoing_bandwidth = outgoing_bandwidth + value;
527    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
528      incoming_bandwidth = incoming_bandwidth + value;
529
530     return GNUNET_OK;
531 }
532
533
534 static void
535 summarize ()
536 {
537   INFO ("# PUTS made: %u\n", n_puts);
538   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
539   INFO ("# PUTS failed: %u\n", n_puts_fail);
540   INFO ("# GETS made: %u\n", n_gets);
541   INFO ("# GETS succeeded: %u\n", n_gets_ok);
542   INFO ("# GETS failed: %u\n", n_gets_fail);
543   INFO ("# average_put_path_length: %f\n", average_put_path_length);
544   INFO ("# average_get_path_length: %f\n", average_get_path_length);
545
546   if (NULL == testbed_handles)
547   {
548     INFO ("No peers found\n");
549     return;
550   }
551   /* Collect Stats*/
552   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
553                                                       "dht", NULL,
554                                                        bandwidth_stats_iterator,
555                                                        bandwidth_stats_cont, NULL);
556 }
557
558
559 /**
560  * Task to cancel DHT GET.
561  *
562  * @param cls NULL
563  */
564 static void
565 cancel_get (void *cls)
566 {
567   struct ActiveContext *ac = cls;
568   struct Context *ctx = ac->ctx;
569
570   ac->delay_task = NULL;
571   GNUNET_assert (NULL != ac->dht_get);
572   GNUNET_DHT_get_stop (ac->dht_get);
573   ac->dht_get = NULL;
574   n_gets_fail++;
575   GNUNET_assert (NULL != ctx->op);
576   GNUNET_TESTBED_operation_done (ctx->op);
577   ctx->op = NULL;
578
579   /* If profiling is complete, summarize */
580   if (n_active == n_gets_fail + n_gets_ok)
581   {
582     average_put_path_length = (double)total_put_path_length/(double)n_active;
583     average_get_path_length = (double)total_get_path_length/(double )n_gets_ok;
584     summarize ();
585   }
586 }
587
588
589 /**
590  * Iterator called on each result obtained for a DHT
591  * operation that expects a reply
592  *
593  * @param cls closure
594  * @param exp when will this value expire
595  * @param key key of the result
596  * @param get_path peers on reply path (or NULL if not recorded)
597  *                 [0] = datastore's first neighbor, [length - 1] = local peer
598  * @param get_path_length number of entries in @a get_path
599  * @param put_path peers on the PUT path (or NULL if not recorded)
600  *                 [0] = origin, [length - 1] = datastore
601  * @param put_path_length number of entries in @a put_path
602  * @param type type of the result
603  * @param size number of bytes in @a data
604  * @param data pointer to the result data
605  */
606 static void
607 get_iter (void *cls,
608           struct GNUNET_TIME_Absolute exp,
609           const struct GNUNET_HashCode *key,
610           const struct GNUNET_PeerIdentity *get_path,
611           unsigned int get_path_length,
612           const struct GNUNET_PeerIdentity *put_path,
613           unsigned int put_path_length,
614           enum GNUNET_BLOCK_Type type,
615           size_t size, const void *data)
616 {
617   struct ActiveContext *ac = cls;
618   struct ActiveContext *get_ac = ac->get_ac;
619   struct Context *ctx = ac->ctx;
620
621   /* Check the keys of put and get match or not. */
622   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
623   /* we found the data we are looking for */
624   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok)); //FIXME: It always prints 1.
625   n_gets_ok++;
626   get_ac->nrefs--;
627   GNUNET_DHT_get_stop (ac->dht_get);
628   ac->dht_get = NULL;
629   if (ac->delay_task != NULL)
630     GNUNET_SCHEDULER_cancel (ac->delay_task);
631   ac->delay_task = NULL;
632   GNUNET_assert (NULL != ctx->op);
633   GNUNET_TESTBED_operation_done (ctx->op);
634   ctx->op = NULL;
635
636   total_put_path_length = total_put_path_length + (double)put_path_length;
637   total_get_path_length = total_get_path_length + (double)get_path_length;
638   DEBUG ("total_put_path_length = %f,put_path \n",total_put_path_length);
639   /* Summarize if profiling is complete */
640   if (n_active == n_gets_fail + n_gets_ok)
641   {
642     average_put_path_length = (double)total_put_path_length/(double)n_active;
643     average_get_path_length = (double)total_get_path_length/(double )n_gets_ok;
644     summarize ();
645   }
646 }
647
648
649 /**
650  * Task to do DHT GETs
651  *
652  * @param cls the active context
653  */
654 static void
655 delayed_get (void *cls)
656 {
657   struct ActiveContext *ac = cls;
658   struct ActiveContext *get_ac;
659   unsigned int r;
660
661   ac->delay_task = NULL;
662   get_ac = NULL;
663   while (1)
664   {
665     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
666     get_ac = &a_ac[r];
667     if (NULL != get_ac->put_data)
668       break;
669   }
670   get_ac->nrefs++;
671   ac->get_ac = get_ac;
672   DEBUG ("GET_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
673   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
674                                       GNUNET_BLOCK_TYPE_TEST,
675                                       &get_ac->hash,
676                                       1, /* replication level */
677                                       GNUNET_DHT_RO_NONE,
678                                       NULL, 0, /* extended query and size */
679                                       get_iter, ac); /* GET iterator and closure
680                                                         */
681   n_gets++;
682
683   /* schedule the timeout task for GET */
684   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
685 }
686
687
688 /**
689  * Task to teardown the dht connection.  We do it as a task because calling
690  * GNUNET_DHT_disconnect() from put_continutation_callback seems illegal (the
691  * put_continuation_callback() is getting called again synchronously).  Also,
692  * only free the operation when we are not shutting down; the shutdown task will
693  * clear the operation during shutdown.
694  *
695  * @param cls the context
696  */
697 static void
698 teardown_dht_connection (void *cls)
699 {
700   struct Context *ctx = cls;
701   struct GNUNET_TESTBED_Operation *op;
702
703   GNUNET_assert (NULL != ctx);
704   GNUNET_assert (NULL != (op = ctx->op));
705   ctx->op = NULL;
706   GNUNET_TESTBED_operation_done (op);
707 }
708
709
710 /**
711  * Queue up a delayed task for doing DHT GET
712  *
713  * @param cls the active context
714  * @param success #GNUNET_OK if the PUT was transmitted,
715  *                #GNUNET_NO on timeout,
716  *                #GNUNET_SYSERR on disconnect from service
717  *                after the PUT message was transmitted
718  *                (so we don't know if it was received or not)
719  */
720 static void
721 put_cont (void *cls, int success)
722 {
723   struct ActiveContext *ac = cls;
724   struct Context *ctx = ac->ctx;
725
726   ac->dht_put = NULL;
727   if (success)
728     n_puts_ok++;
729   else
730     n_puts_fail++;
731   GNUNET_assert (NULL != ctx);
732   (void) GNUNET_SCHEDULER_add_now (&teardown_dht_connection, ctx);
733 }
734
735
736 /**
737  * Task to do DHT PUTs
738  *
739  * @param cls the active context
740  */
741 static void
742 delayed_put (void *cls)
743 {
744   struct ActiveContext *ac = cls;
745
746   ac->delay_task = NULL;
747   /* Generate and DHT PUT some random data */
748   ac->put_data_size = 16;       /* minimum */
749   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
750                                                  (63*1024));
751   ac->put_data = GNUNET_malloc (ac->put_data_size);
752   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
753                               ac->put_data, ac->put_data_size);
754   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
755   DEBUG ("PUT_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
756   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
757                                 replication,
758                                 GNUNET_DHT_RO_RECORD_ROUTE,
759                                 GNUNET_BLOCK_TYPE_TEST,
760                                 ac->put_data_size,
761                                 ac->put_data,
762                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
763                                 timeout,                      /* PUT timeout */
764                                 put_cont, ac);                /* continuation and its closure */
765   n_puts++;
766 }
767
768
769 /**
770  * Connection to DHT has been established.  Call the delay task.
771  *
772  * @param cls the active context
773  * @param op the operation that has been finished
774  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
775  * @param emsg error message in case the operation has failed; will be NULL if
776  *          operation has executed successfully.
777  */
778 static void
779 dht_connected (void *cls,
780                struct GNUNET_TESTBED_Operation *op,
781                void *ca_result,
782                const char *emsg)
783 {
784   struct ActiveContext *ac = cls;
785   struct Context *ctx = ac->ctx;
786
787   GNUNET_assert (NULL != ctx); //FIXME: Fails
788   GNUNET_assert (NULL != ctx->op);
789   GNUNET_assert (ctx->op == op);
790   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
791   if (NULL != emsg)
792   {
793     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
794     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
795     ctx->op = NULL;
796     return;
797   }
798   switch (mode)
799   {
800   case MODE_PUT:
801   {
802     struct GNUNET_TIME_Relative peer_delay_put;
803     peer_delay_put.rel_value_us =
804       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
805                                 delay_put.rel_value_us);
806     ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_put, &delayed_put, ac);
807     break;
808   }
809   case MODE_GET:
810   {
811     struct GNUNET_TIME_Relative peer_delay_get;
812     peer_delay_get.rel_value_us =
813       delay_get.rel_value_us +
814       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
815                                 delay_get.rel_value_us);
816     ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_get, &delayed_get, ac);
817     break;
818   }
819   }
820 }
821
822
823 /**
824  * Connect to DHT service and return the DHT client handler
825  *
826  * @param cls the active context
827  * @param cfg configuration of the peer to connect to; will be available until
828  *          GNUNET_TESTBED_operation_done() is called on the operation returned
829  *          from GNUNET_TESTBED_service_connect()
830  * @return service handle to return in 'op_result', NULL on error
831  */
832 static void *
833 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
834 {
835   n_dht++;
836   return GNUNET_DHT_connect (cfg, 10);
837 }
838
839
840 /**
841  * Adapter function called to destroy a connection to
842  * a service.
843  *
844  * @param cls the active context
845  * @param op_result service handle returned from the connect adapter
846  */
847 static void
848 dht_disconnect (void *cls, void *op_result)
849 {
850   struct ActiveContext *ac = cls;
851
852   GNUNET_assert (NULL != ac->dht);
853   GNUNET_assert (ac->dht == op_result);
854   GNUNET_DHT_disconnect (ac->dht);
855   ac->dht = NULL;
856   n_dht--;
857   if (0 != n_dht)
858     return;
859   if (GNUNET_YES == in_shutdown)
860     return;
861   switch (mode)
862   {
863   case MODE_PUT:
864     if ((n_puts_ok + n_puts_fail) != n_active)
865       return;
866     /* Start GETs if all PUTs have been made */
867     mode = MODE_GET;
868     //(void) GNUNET_SCHEDULER_add_now (&call_start_profiling, NULL);
869     start_profiling ();
870     return;
871   case MODE_GET:
872     if ((n_gets_ok + n_gets_fail) != n_active)
873       return;
874     break;
875   }
876 }
877
878 /**
879  * Connect to DHT services of active peers
880  */
881 static void
882 start_profiling()
883 {
884   struct Context *ctx;
885   unsigned int i;
886
887   DEBUG("GNUNET_TESTBED_service_connect \n");
888   GNUNET_break (GNUNET_YES != in_shutdown);
889   for(i = 0; i < n_active; i++)
890   {
891     struct ActiveContext *ac = &a_ac[i];
892     GNUNET_assert (NULL != (ctx = ac->ctx));
893     GNUNET_assert (NULL == ctx->op);
894     ctx->op =
895         GNUNET_TESTBED_service_connect (ctx,
896                                         ctx->peer,
897                                         "dht",
898                                         &dht_connected, ac,
899                                         &dht_connect,
900                                         &dht_disconnect,
901                                         ac);
902   }
903 }
904
905 #if ENABLE_MALICIOUS
906 /**
907  * Count of total number of malicious peers.
908  */
909 static unsigned int count_malicious;
910
911 /**
912  * Continuation of GNUNET_DHT_act_malicious
913  * @param cls Malicious context
914   * @param success #GNUNET_OK if the ACT_MALICIOUS was transmitted,
915  *                 #GNUNET_NO on timeout,
916  *                 #GNUNET_SYSERR on disconnect from service
917  *                 after the ACT_MALICIOUS message was transmitted
918  *                 (so we don't know if it was received or not)
919  */
920 static void
921 act_malicious_cont (void *cls, int success)
922 {
923   struct MaliciousContext *mc = cls;
924   struct Context *ctx = mc->ctx;
925
926   GNUNET_TESTBED_operation_done (ctx->op);
927   ctx->op = NULL;
928   return;
929 }
930
931
932 /**
933  * Call malicious API for all the malicious peers.
934  * @param cls the malicious context.
935  * @param op the operation that has been finished
936  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
937  * @param emsg error message in case the operation has failed; will be NULL if
938  *          operation has executed successfully.
939  */
940 static void
941 dht_set_malicious(void *cls,
942                   struct GNUNET_TESTBED_Operation *op,
943                   void *ca_result,
944                   const char *emsg)
945 {
946   struct MaliciousContext *mc = cls;
947   struct Context *ctx = mc->ctx;
948
949   GNUNET_assert (NULL != ctx);
950   GNUNET_assert (NULL != ctx->op);
951   GNUNET_assert (ctx->op == op);
952   mc->dht = (struct GNUNET_DHT_Handle *) ca_result;
953   if (NULL != emsg)
954   {
955     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
956     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect_malicious() */
957     ctx->op = NULL;
958     return;
959   }
960   mc->dht_malicious = GNUNET_DHT_act_malicious(mc->dht, 1, act_malicious_cont, mc);
961 }
962
963
964 /**
965  * Adapter function called to destroy a connection to
966  * a service.
967  *
968  * @param cls the active context
969  * @param op_result service handle returned from the connect adapter
970  */
971 static void
972 dht_disconnect_malicious (void *cls, void *op_result)
973 {
974   struct MaliciousContext *mc = cls;
975   count_malicious++;
976   GNUNET_assert (NULL != mc->dht);
977   GNUNET_assert (mc->dht == op_result);
978   GNUNET_DHT_disconnect (mc->dht);
979   mc->dht = NULL;
980   mc->ctx->op = NULL;
981   n_dht--;
982
983   if (0 != n_dht)
984     return;
985
986   if(n_malicious == count_malicious)
987   {
988     DEBUG("\n Call start_profiling()");
989     start_profiling();
990   }
991 }
992
993
994 /**
995  * Set the malicious variable in peer malicious context.
996  */
997 static void
998 set_malicious()
999 {
1000   unsigned int i;
1001
1002   DEBUG ("Setting %u peers malicious",
1003          n_malicious);
1004   for(i = 0; i < n_malicious; i++)
1005   {
1006     struct MaliciousContext *mc = &a_mc[i];
1007     mc->ctx->op =
1008         GNUNET_TESTBED_service_connect (mc->ctx,
1009                                         mc->ctx->peer,
1010                                         "dht",
1011                                         &dht_set_malicious, mc,
1012                                         &dht_connect,
1013                                         &dht_disconnect_malicious,
1014                                         mc);
1015   }
1016 }
1017
1018 #endif
1019
1020
1021 /**
1022  * Start collecting relevant statistics. If ENABLE_MALICIOUS set, first
1023  * set the malicious peers. If not, then start with PUT operation on active
1024  * peers.
1025  */
1026 static void
1027 start_func()
1028 {
1029 #if ENABLE_MALICIOUS
1030   set_malicious();
1031 #else
1032   start_profiling();
1033 #endif
1034 }
1035
1036
1037 /**
1038  * Remove entry from successor peer hashmap.
1039  * @param cls closure
1040  * @param key current public key
1041  * @param value value in the hash map
1042  * @return #GNUNET_YES if we should continue to iterate,
1043  *         #GNUNET_NO if not.
1044  */
1045 static int
1046 hashmap_iterate_remove(void *cls,
1047                        const struct GNUNET_HashCode *key,
1048                        void *value)
1049 {
1050   GNUNET_assert (GNUNET_YES ==
1051                 GNUNET_CONTAINER_multihashmap_remove(successor_peer_hashmap, key, value));
1052   return GNUNET_YES;
1053 }
1054
1055
1056 /**
1057  * Stats callback. Iterate over the hashmap and check if all th peers form
1058  * a virtual ring topology.
1059  *
1060  * @param cls closure
1061  * @param op the operation that has been finished
1062  * @param emsg error message in case the operation has failed; will be NULL if
1063  *          operation has executed successfully.
1064  */
1065 static void
1066 successor_stats_cont (void *cls,
1067                       struct GNUNET_TESTBED_Operation *op,
1068                       const char *emsg)
1069 {
1070   struct GNUNET_HashCode *val;
1071   struct GNUNET_HashCode *start_val;
1072   struct GNUNET_HashCode *key;
1073   int count;
1074
1075   /* Don't schedule the task till we are looking for circle here. */
1076   successor_stats_task = NULL;
1077   GNUNET_TESTBED_operation_done (successor_stats_op);
1078   successor_stats_op = NULL;
1079   if (0 == max_searches)
1080   {
1081     start_func ();
1082     return;
1083   }
1084
1085   GNUNET_assert (NULL != start_key);
1086   start_val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
1087                                                  start_key);
1088   GNUNET_assert (NULL != start_val);
1089   val = start_val;
1090   for (count = 0; count < num_peers; count++)
1091   {
1092     key = val;
1093     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
1094                                              key);
1095     if (NULL == val)
1096       break;
1097     /* Remove the entry from hashmap. This is done to take care of loop. */
1098     if (GNUNET_NO ==
1099         GNUNET_CONTAINER_multihashmap_remove (successor_peer_hashmap,
1100                                               key, val))
1101     {
1102       DEBUG ("Failed to remove entry from hashmap\n");
1103       break;
1104     }
1105     /* If a peer has its own identity as its successor. */
1106     if (0 == memcmp(key, val, sizeof (struct GNUNET_HashCode)))
1107       break;
1108   }
1109
1110   GNUNET_assert (GNUNET_SYSERR !=
1111                  GNUNET_CONTAINER_multihashmap_iterate (successor_peer_hashmap,
1112                                                         &hashmap_iterate_remove,
1113                                                         NULL));
1114
1115   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers,
1116                                                                  GNUNET_NO);
1117   if ((start_val == val) && (count == num_peers))
1118   {
1119     DEBUG ("CIRCLE COMPLETED after %u tries", tries);
1120     if(NULL == successor_stats_task)
1121     {
1122       start_func();
1123     }
1124     return;
1125   }
1126   if (max_searches == ++tries)
1127   {
1128     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1129                 "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
1130                 " circle formation.  Exiting\n",
1131                 max_searches,tries);
1132     start_func();
1133     return;
1134   }
1135   flag = 0;
1136   successor_stats_task
1137     = GNUNET_SCHEDULER_add_delayed (delay_stats,
1138                                     &collect_stats,
1139                                     cls);
1140 }
1141
1142
1143 /**
1144  * Process successor statistic values.
1145  *
1146  * @param cls closure
1147  * @param peer the peer the statistic belong to
1148  * @param subsystem name of subsystem that created the statistic
1149  * @param name the name of the datum
1150  * @param value the current value
1151  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1152  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1153  */
1154 static int
1155 successor_stats_iterator (void *cls,
1156                           const struct GNUNET_TESTBED_Peer *peer,
1157                           const char *subsystem,
1158                           const char *name,
1159                           uint64_t value,
1160                           int is_persistent)
1161 {
1162   static const char *key_string = "XDHT";
1163   if (0 == max_searches)
1164     return GNUNET_OK;
1165
1166   if (0 == strncmp (key_string, name, strlen (key_string)))
1167   {
1168     char *my_id_str;
1169     char successor_str[13];
1170     char truncated_my_id_str[13];
1171     char truncated_successor_str[13];
1172     struct GNUNET_HashCode *my_id_key;
1173     struct GNUNET_HashCode *succ_key;
1174
1175     strtok((char *)name,":");
1176     my_id_str = strtok(NULL,":");
1177
1178     strncpy(truncated_my_id_str, my_id_str, 12);
1179     truncated_my_id_str[12] = '\0';
1180     my_id_key = GNUNET_new(struct GNUNET_HashCode);
1181     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
1182     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
1183     strncpy(truncated_successor_str, successor_str, 12);
1184     truncated_successor_str[12] ='\0';
1185
1186     succ_key = GNUNET_new(struct GNUNET_HashCode);
1187     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
1188
1189     if (0 == flag)
1190     {
1191       GNUNET_assert(NULL != my_id_key);
1192       start_key = my_id_key;
1193       GNUNET_assert(NULL != start_key);
1194       flag = 1;
1195     }
1196     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
1197                                        my_id_key, (void *)succ_key,
1198                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1199   }
1200
1201   return GNUNET_OK;
1202 }
1203
1204
1205 /*
1206  * Task that collects peer and its corresponding successors.
1207  *
1208  * @param cls Closure (NULL).
1209  */
1210 static void
1211 collect_stats (void *cls)
1212 {
1213   successor_stats_task = NULL;
1214   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1215               "Start collecting statistics...\n");
1216   GNUNET_assert(NULL != testbed_handles);
1217
1218   if (0 != max_searches)
1219     successor_peer_hashmap
1220       = GNUNET_CONTAINER_multihashmap_create (num_peers,
1221                                               GNUNET_NO);
1222   successor_stats_op
1223     = GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
1224                                      "dht", NULL,
1225                                      successor_stats_iterator,
1226                                      successor_stats_cont, cls);
1227   GNUNET_assert (NULL != successor_stats_op);
1228 }
1229
1230
1231 /**
1232  * Callback called when DHT service on the peer is started
1233  *
1234  * @param cls the context
1235  * @param op the operation that has been finished
1236  * @param emsg error message in case the operation has failed; will be NULL if
1237  *          operation has executed successfully.
1238  */
1239 static void
1240 service_started (void *cls,
1241                  struct GNUNET_TESTBED_Operation *op,
1242                  const char *emsg)
1243 {
1244   struct Context *ctx = cls;
1245
1246   GNUNET_assert (NULL != ctx);
1247   GNUNET_assert (NULL != ctx->op);
1248   GNUNET_TESTBED_operation_done (ctx->op);
1249   ctx->op = NULL;
1250   peers_started++;
1251   DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
1252   if (NULL == successor_stats_task && peers_started == num_peers)
1253   {
1254      DEBUG("successor_stats_task \n");
1255      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
1256      collect_stat_cls->service_connect_ctx = cls;
1257      collect_stat_cls->op = op;
1258
1259      successor_stats_task
1260        = GNUNET_SCHEDULER_add_delayed (delay_stats,
1261                                        &collect_stats,
1262                                        collect_stat_cls);
1263   }
1264 }
1265
1266
1267 /**
1268  * Signature of a main function for a testcase.
1269  *
1270  * @param cls closure
1271  * @param h the run handle
1272  * @param num_peers number of peers in 'peers'
1273  * @param peers handle to peers run in the testbed
1274  * @param links_succeeded the number of overlay link connection attempts that
1275  *          succeeded
1276  * @param links_failed the number of overlay link
1277  */
1278 static void
1279 test_run (void *cls,
1280           struct GNUNET_TESTBED_RunHandle *h,
1281           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
1282           unsigned int links_succeeded,
1283           unsigned int links_failed)
1284 {
1285   unsigned int cnt;
1286   unsigned int ac_cnt;
1287   testbed_handles = peers;
1288   if (NULL == peers)
1289   {
1290     /* exit */
1291     GNUNET_assert (0);
1292   }
1293   INFO ("%u peers started\n", num_peers);
1294   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
1295
1296   /* select the peers which actively participate in profiling */
1297   n_active = num_peers * PUT_PROBABILITY / 100;
1298   if (0 == n_active)
1299   {
1300     GNUNET_SCHEDULER_shutdown ();
1301     GNUNET_free (a_ctx);
1302     return;
1303   }
1304
1305   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1306   ac_cnt = 0;
1307
1308 #if ENABLE_MALICIOUS
1309   unsigned int malicious_peers;
1310   if(PUT_PROBABILITY + MALICIOUS_PROBABILITY > 100)
1311   {
1312     DEBUG ("Reduce either number of malicious peer or active peers. ");
1313     GNUNET_SCHEDULER_shutdown ();
1314     GNUNET_free (a_ctx);
1315     return;
1316   }
1317
1318   /* Select the peers which should act maliciously. */
1319   n_malicious = num_peers * MALICIOUS_PROBABILITY / 100;
1320
1321   a_mc = GNUNET_malloc (n_malicious * sizeof (struct MaliciousContext));
1322   malicious_peers = 0;
1323
1324   for (cnt = 0; cnt < num_peers && malicious_peers < n_malicious; cnt++)
1325   {
1326     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1327         MALICIOUS_PROBABILITY)
1328       continue;
1329     a_ctx[cnt].mc = &a_mc[malicious_peers];
1330     a_mc[malicious_peers].ctx = &a_ctx[cnt];
1331     malicious_peers++;
1332   }
1333   n_malicious = malicious_peers;
1334   INFO ("Malicious Peers: %u\n",malicious_peers);
1335
1336 #endif
1337
1338   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1339   ac_cnt = 0;
1340   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
1341   {
1342     if ((GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1343         PUT_PROBABILITY))
1344       continue;
1345
1346 #if ENABLE_MALICIOUS
1347     if(a_ctx[ac_cnt].mc != NULL)
1348       continue;
1349 #endif
1350
1351     a_ctx[cnt].ac = &a_ac[ac_cnt];
1352     a_ac[ac_cnt].ctx = &a_ctx[cnt];
1353     ac_cnt++;
1354   }
1355   n_active = ac_cnt;
1356   INFO ("Active peers: %u\n", n_active);
1357
1358   /* start DHT service on all peers */
1359   for (cnt = 0; cnt < num_peers; cnt++)
1360   {
1361     a_ctx[cnt].peer = peers[cnt];
1362     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
1363                                                         peers[cnt],
1364                                                         "dht",
1365                                                         &service_started,
1366                                                         &a_ctx[cnt],
1367                                                         1);
1368   }
1369 }
1370
1371
1372 /**
1373  * Main function that will be run by the scheduler.
1374  *
1375  * @param cls closure
1376  * @param args remaining command-line arguments
1377  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1378  * @param config configuration
1379  */
1380 static void
1381 run (void *cls, char *const *args, const char *cfgfile,
1382      const struct GNUNET_CONFIGURATION_Handle *config)
1383 {
1384   uint64_t event_mask;
1385
1386   if (0 == num_peers)
1387   {
1388     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1389                 _("Exiting as the number of peers is %u\n"),
1390                 num_peers);
1391     return;
1392   }
1393   cfg = GNUNET_CONFIGURATION_dup (config);
1394   event_mask = 0;
1395   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
1396                       NULL, &test_run, NULL);
1397   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
1398                                  NULL);
1399 }
1400
1401
1402 /**
1403  * Main function.
1404  *
1405  * @return 0 on success
1406  */
1407 int
1408 main (int argc, char *const *argv)
1409 {
1410   int rc;
1411
1412   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1413     {'n', "peers", "COUNT",
1414      gettext_noop ("number of peers to start"),
1415      1, &GNUNET_GETOPT_set_uint, &num_peers},
1416     {'s', "searches", "COUNT",
1417      gettext_noop ("maximum number of times we try to search for successor circle formation (0 for R5N)"),
1418      1, &GNUNET_GETOPT_set_uint, &max_searches},
1419     {'H', "hosts", "FILENAME",
1420      gettext_noop ("name of the file with the login information for the testbed"),
1421      1, &GNUNET_GETOPT_set_string, &hosts_file},
1422     {'D', "delay", "DELAY",
1423      gettext_noop ("delay between rounds for collecting statistics (default: 30 sec)"),
1424      1, &GNUNET_GETOPT_set_relative_time, &delay_stats},
1425     {'P', "PUT-delay", "DELAY",
1426      gettext_noop ("delay to start doing PUTs (default: 1 sec)"),
1427      1, &GNUNET_GETOPT_set_relative_time, &delay_put},
1428     {'G', "GET-delay", "DELAY",
1429      gettext_noop ("delay to start doing GETs (default: 5 min)"),
1430      1, &GNUNET_GETOPT_set_relative_time, &delay_get},
1431     {'r', "replication", "DEGREE",
1432      gettext_noop ("replication degree for DHT PUTs"),
1433      1, &GNUNET_GETOPT_set_uint, &replication},
1434     {'t', "timeout", "TIMEOUT",
1435      gettext_noop ("timeout for DHT PUT and GET requests (default: 1 min)"),
1436      1, &GNUNET_GETOPT_set_relative_time, &timeout},
1437     GNUNET_GETOPT_OPTION_END
1438   };
1439
1440   max_searches = 5;
1441   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1442     return 2;
1443   /* set default delays */
1444   delay_stats = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1445   delay_put = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1446   delay_get = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1447   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1448   replication = 1;      /* default replication */
1449   rc = 0;
1450   if (GNUNET_OK !=
1451       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
1452                           gettext_noop
1453                           ("Measure quality and performance of the DHT service."),
1454                           options, &run, NULL))
1455     rc = 1;
1456   return rc;
1457 }