Check that you are not present in trail twice
[oweals/gnunet.git] / src / dht / gnunet_dht_profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 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 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 100
42
43 /**
44  * Percentage of peers that should act maliciously.
45  * These peers will never start PUT/GET request.
46  * n_active and n_malicious should not intersect.
47  */
48 #define MALICIOUS_PEERS 0
49
50 /**
51  * Configuration
52  */
53 static struct GNUNET_CONFIGURATION_Handle *cfg;
54
55 /**
56  * Name of the file with the hosts to run the test over
57  */
58 static char *hosts_file;
59
60 /**
61  * Context for a peer which actively does DHT PUT/GET
62  */
63 struct ActiveContext;
64
65 /**
66  * Context to hold data of peer
67  */
68 struct Context
69 {
70
71   /**
72    * The testbed peer this context belongs to
73    */
74   struct GNUNET_TESTBED_Peer *peer;
75
76   /**
77    * Testbed operation acting on this peer
78    */
79   struct GNUNET_TESTBED_Operation *op;
80
81   /**
82    * Active context; NULL if this peer is not an active peer
83    */
84   struct ActiveContext *ac;
85 };
86
87
88 #if ENABLE_MALICIOUS
89 /**
90  * Context for a peer which should act maliciously.
91  */
92 struct MaliciousContext
93 {
94   /**
95    * The linked peer context
96    */
97   struct Context *ctx;
98
99   /**
100    * Handler to the DHT service
101    */
102   struct GNUNET_DHT_Handle *dht;
103 };
104
105 /**
106  * List of all the malicious peers contexts.
107  */
108 struct Context **malicious_peer_contexts = NULL;
109
110 #endif
111
112 /**
113  * Context for a peer which actively does DHT PUT/GET
114  */
115 struct ActiveContext
116 {
117   /**
118    * The linked peer context
119    */
120   struct Context *ctx;
121
122   /**
123    * Handler to the DHT service
124    */
125   struct GNUNET_DHT_Handle *dht;
126
127   /**
128    * The data used for do a PUT.  Will be NULL if a PUT hasn't been performed yet
129    */
130   void *put_data;
131
132   /**
133    * The active context used for our DHT GET
134    */
135   struct ActiveContext *get_ac;
136
137   /**
138    * The put handle
139    */
140   struct GNUNET_DHT_PutHandle *dht_put;
141
142   /**
143    * The get handle
144    */
145   struct GNUNET_DHT_GetHandle *dht_get;
146
147   /**
148    * The hash of the @e put_data
149    */
150   struct GNUNET_HashCode hash;
151
152   /**
153    * Delay task
154    */
155   GNUNET_SCHEDULER_TaskIdentifier delay_task;
156
157   /**
158    * The size of the @e put_data
159    */
160   uint16_t put_data_size;
161
162   /**
163    * The number of peers currently doing GET on our data
164    */
165   uint16_t nrefs;
166 };
167
168
169 /**
170  * An array of contexts.  The size of this array should be equal to @a num_peers
171  */
172 static struct Context *a_ctx;
173
174 /**
175  * Array of active peers
176  */
177 static struct ActiveContext *a_ac;
178
179 /**
180  * The delay between starting to do PUTS and GETS
181  */
182 static struct GNUNET_TIME_Relative delay;
183
184 /**
185  * The timeout for GET and PUT
186  */
187 static struct GNUNET_TIME_Relative timeout;
188
189 /**
190  * Number of peers
191  */
192 static unsigned int num_peers;
193
194 #if ENABLE_MALICIOUS
195 /**
196  * Number or malicious peers.
197  */
198 static unsigned int n_malicious;
199 #endif
200
201 /**
202  * Number of active peers
203  */
204 static unsigned int n_active;
205
206 /**
207  * Number of DHT service connections we currently have
208  */
209 static unsigned int n_dht;
210
211 /**
212  * Number of DHT PUTs made
213  */
214 static unsigned int n_puts;
215
216 /**
217  * Number of DHT PUTs succeeded
218  */
219 static unsigned int n_puts_ok;
220
221 /**
222  * Number of DHT PUTs failed
223  */
224 static unsigned int n_puts_fail;
225
226 /**
227  * Number of DHT GETs made
228  */
229 static unsigned int n_gets;
230
231 /**
232  * Number of DHT GETs succeeded
233  */
234 static unsigned int n_gets_ok;
235
236 /**
237  * Number of DHT GETs succeeded
238  */
239 static unsigned int n_gets_fail;
240
241 /**
242  * Replication degree
243  */
244 static unsigned int replication;
245
246 /**
247  * Number of times we try to find the successor circle formation
248  */
249 static unsigned int max_searches;
250
251 /**
252  * Testbed Operation (to get stats).
253  */
254 static struct GNUNET_TESTBED_Operation *bandwidth_stats_op;
255
256 /**
257  * To get successor stats.
258  */
259 static struct GNUNET_TESTBED_Operation *successor_stats_op;
260
261 /**
262  * Testbed peer handles.
263  */
264 static struct GNUNET_TESTBED_Peer **testbed_handles;
265
266 /**
267  * Total number of messages sent by peer. 
268  */
269 static uint64_t outgoing_bandwidth;
270
271 /**
272  * Total number of messages received by peer.
273  */
274 static uint64_t incoming_bandwidth;
275
276 /**
277  * Average number of hops taken to do put.
278  */
279 static unsigned int average_put_path_length;
280
281 /**
282  * Average number of hops taken to do get. 
283  */
284 static unsigned int average_get_path_length;
285
286 /**
287  * Total put path length across all peers. 
288  */
289 static unsigned int total_put_path_length;
290
291 /**
292  * Total get path length across all peers. 
293  */
294 static unsigned int total_get_path_length;
295
296 /**
297  * Hashmap to store pair of peer and its corresponding successor. 
298  */
299 static struct GNUNET_CONTAINER_MultiHashMap *successor_peer_hashmap;
300
301 /**
302  * Key to start the lookup on successor_peer_hashmap. 
303  */
304 static struct GNUNET_HashCode *start_key;
305
306 /**
307  * Flag used to get the start_key.
308  */
309 static int flag = 0;
310
311 /**
312  * Task to collect peer and its current successor statistics.
313  */
314 static GNUNET_SCHEDULER_TaskIdentifier successor_stats_task;
315
316 /**
317  * Closure for successor_stats_task.
318  */
319 struct Collect_Stat_Context
320 {
321   /**
322    * Current Peer Context. 
323    */
324   struct Context *service_connect_ctx;
325   
326   /**
327    * Testbed operation acting on this peer
328    */
329   struct GNUNET_TESTBED_Operation *op;
330 };
331
332 /**
333  * List of all the peers contexts.
334  */
335 struct Context **peer_contexts = NULL;
336
337 /**
338  * Counter to keep track of peers added to peer_context lists. 
339  */
340 static int peers_started = 0;
341
342 /**
343  * Task that collects successor statistics from all the peers. 
344  * @param cls
345  * @param tc
346  */
347 static void
348 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
349
350
351 /**
352  * Shutdown task.  Cleanup all resources and operations.
353  *
354  * @param cls NULL
355  * @param tc scheduler task context
356  */
357 static void
358 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
359 {
360   struct ActiveContext *ac;
361   unsigned int cnt;
362
363   if (NULL != a_ctx)
364   {
365     for (cnt=0; cnt < num_peers; cnt++)
366     {
367       if (NULL != a_ctx[cnt].op)
368         GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
369
370       /* Cleanup active context if this peer is an active peer */
371       ac = a_ctx[cnt].ac;
372       if (NULL == ac)
373         continue;
374       if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
375         GNUNET_SCHEDULER_cancel (ac->delay_task);
376       if (NULL != ac->put_data)
377         GNUNET_free (ac->put_data);
378       if (NULL != ac->dht_put)
379         GNUNET_DHT_put_cancel (ac->dht_put);
380       if (NULL != ac->dht_get)
381         GNUNET_DHT_get_stop (ac->dht_get);
382     }
383     GNUNET_free (a_ctx);
384     a_ctx = NULL;
385   }
386   if(NULL != bandwidth_stats_op)
387     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
388   bandwidth_stats_op = NULL;
389   GNUNET_free_non_null (a_ac);
390 }
391
392
393 /**
394  * Stats callback. Finish the stats testbed operation and when all stats have
395  * been iterated, shutdown the test.
396  *
397  * @param cls closure
398  * @param op the operation that has been finished
399  * @param emsg error message in case the operation has failed; will be NULL if
400  *          operation has executed successfully.
401  */
402 static void
403 bandwidth_stats_cont (void *cls, 
404                       struct GNUNET_TESTBED_Operation *op, 
405                       const char *emsg)
406 {
407   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
408   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
409   GNUNET_SCHEDULER_shutdown (); 
410 }
411
412
413 /**
414  * Process statistic values.
415  *
416  * @param cls closure
417  * @param peer the peer the statistic belong to
418  * @param subsystem name of subsystem that created the statistic
419  * @param name the name of the datum
420  * @param value the current value
421  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
422  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
423  */
424 static int
425 bandwidth_stats_iterator (void *cls, 
426                           const struct GNUNET_TESTBED_Peer *peer,
427                           const char *subsystem, 
428                           const char *name,
429                           uint64_t value, 
430                           int is_persistent)
431 {
432    static const char *s_sent = "# Bytes transmitted to other peers";
433    static const char *s_recv = "# Bytes received from other peers";
434
435    if (0 == strncmp (s_sent, name, strlen (s_sent)))
436      outgoing_bandwidth = outgoing_bandwidth + value;
437    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
438      incoming_bandwidth = incoming_bandwidth + value;
439    else
440      return GNUNET_OK;
441    DEBUG ("Bandwith - Out: %lu; In: %lu\n",
442           (unsigned long) outgoing_bandwidth,
443           (unsigned long) incoming_bandwidth);
444    return GNUNET_OK;
445 }
446
447
448 static void
449 summarize ()
450 {
451   INFO ("# PUTS made: %u\n", n_puts);
452   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
453   INFO ("# PUTS failed: %u\n", n_puts_fail);
454   INFO ("# GETS made: %u\n", n_gets);
455   INFO ("# GETS succeeded: %u\n", n_gets_ok);
456   INFO ("# GETS failed: %u\n", n_gets_fail);
457   INFO ("# average_put_path_length: %u\n", average_put_path_length);
458   INFO ("# average_get_path_length: %u\n", average_get_path_length);
459   
460   if (NULL == testbed_handles)
461   {
462     INFO ("No peers found\n");
463     return;
464   }
465   /* Collect Stats*/
466   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
467                                                       "dht", NULL,
468                                                        bandwidth_stats_iterator, 
469                                                        bandwidth_stats_cont, NULL);
470 }
471
472
473 /**
474  * Task to cancel DHT GET.
475  *
476  * @param cls NULL
477  * @param tc scheduler task context
478  */
479 static void
480 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
481 {
482   struct ActiveContext *ac = cls;
483
484   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
485   GNUNET_assert (NULL != ac->dht_get);
486   GNUNET_DHT_get_stop (ac->dht_get);
487   ac->dht_get = NULL;
488   n_gets_fail++;
489
490   /* If profiling is complete, summarize */
491   if (n_active == n_gets_fail + n_gets_ok)
492     summarize ();
493
494 }
495
496
497 /**
498  * Iterator called on each result obtained for a DHT
499  * operation that expects a reply
500  *
501  * @param cls closure
502  * @param exp when will this value expire
503  * @param key key of the result
504  * @param get_path peers on reply path (or NULL if not recorded)
505  *                 [0] = datastore's first neighbor, [length - 1] = local peer
506  * @param get_path_length number of entries in @a get_path
507  * @param put_path peers on the PUT path (or NULL if not recorded)
508  *                 [0] = origin, [length - 1] = datastore
509  * @param put_path_length number of entries in @a put_path
510  * @param type type of the result
511  * @param size number of bytes in @a data
512  * @param data pointer to the result data
513  */
514 static void
515 get_iter (void *cls,
516           struct GNUNET_TIME_Absolute exp,
517           const struct GNUNET_HashCode *key,
518           const struct GNUNET_PeerIdentity *get_path,
519           unsigned int get_path_length,
520           const struct GNUNET_PeerIdentity *put_path,
521           unsigned int put_path_length,
522           enum GNUNET_BLOCK_Type type,
523           size_t size, const void *data)
524 {
525   struct ActiveContext *ac = cls;
526   struct ActiveContext *get_ac = ac->get_ac;
527
528   /* Check the keys of put and get match or not. */
529   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
530   /* we found the data we are looking for */
531   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
532   n_gets_ok++;
533   get_ac->nrefs--;
534   GNUNET_DHT_get_stop (ac->dht_get);
535   ac->dht_get = NULL;
536   GNUNET_SCHEDULER_cancel (ac->delay_task);
537   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
538   
539   total_put_path_length = total_put_path_length + put_path_length;
540   total_get_path_length = total_get_path_length + get_path_length;
541   
542   /* Summarize if profiling is complete */
543   if (n_active == n_gets_fail + n_gets_ok)
544   {
545     average_put_path_length = total_put_path_length/n_active;
546     average_get_path_length = total_get_path_length/n_active;
547     summarize ();
548   }
549 }
550
551
552 /**
553  * Task to do DHT GETs
554  *
555  * @param cls the active context
556  * @param tc the scheduler task context
557  */
558 static void
559 delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
560 {
561   struct ActiveContext *ac = cls;
562   struct ActiveContext *get_ac;
563   unsigned int r;
564
565   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
566   get_ac = NULL;
567   while (1)
568   {
569     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
570     get_ac = &a_ac[r];
571     if (NULL != get_ac->put_data)
572       break;
573   }
574   get_ac->nrefs++;
575   ac->get_ac = get_ac;
576   DEBUG ("Doing a DHT GET for data of size %u\n", get_ac->put_data_size);
577   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
578                                       GNUNET_BLOCK_TYPE_TEST,
579                                       &get_ac->hash,
580                                       1, /* replication level */
581                                       GNUNET_DHT_RO_NONE,
582                                       NULL, 0, /* extended query and size */
583                                       get_iter, ac); /* GET iterator and closure
584                                                         */
585   n_gets++;
586
587   /* schedule the timeout task for GET */
588   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
589 }
590
591
592 /**
593  * Queue up a delayed task for doing DHT GET
594  *
595  * @param cls the active context
596  * @param success #GNUNET_OK if the PUT was transmitted,
597  *                #GNUNET_NO on timeout,
598  *                #GNUNET_SYSERR on disconnect from service
599  *                after the PUT message was transmitted
600  *                (so we don't know if it was received or not)
601  */
602 static void
603 put_cont (void *cls, int success)
604 {
605   struct ActiveContext *ac = cls;
606
607   ac->dht_put = NULL;
608   if (success)
609     n_puts_ok++;
610   else
611     n_puts_fail++;
612   ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_get, ac);
613 }
614
615
616 /**
617  * Task to do DHT PUTS
618  *
619  * @param cls the active context
620  * @param tc the scheduler task context
621  */
622 static void
623 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
624 {
625   struct ActiveContext *ac = cls;
626
627   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
628   /* Generate and DHT PUT some random data */
629   ac->put_data_size = 16;       /* minimum */
630   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
631                                                  (63*1024));
632   ac->put_data = GNUNET_malloc (ac->put_data_size);
633   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
634                               ac->put_data, ac->put_data_size);
635   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
636   DEBUG ("Doing a DHT PUT with data of size %u\n", ac->put_data_size);
637   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
638                                 replication,
639                                 GNUNET_DHT_RO_NONE,
640                                 GNUNET_BLOCK_TYPE_TEST,
641                                 ac->put_data_size,
642                                 ac->put_data,
643                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
644                                 timeout,                      /* PUT timeout */
645                                 put_cont, ac);                /* continuation and its closure */
646   n_puts++;
647 }
648
649
650 /**
651  * Connection to DHT has been established.  Call the delay task.
652  *
653  * @param cls the active context
654  * @param op the operation that has been finished
655  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
656  * @param emsg error message in case the operation has failed; will be NULL if
657  *          operation has executed successfully.
658  */
659 static void
660 dht_connected (void *cls,
661                struct GNUNET_TESTBED_Operation *op,
662                void *ca_result,
663                const char *emsg)
664 {
665   struct ActiveContext *ac = cls;
666   struct Context *ctx = ac->ctx;
667
668   GNUNET_assert (NULL != ctx);
669   GNUNET_assert (NULL != ctx->op);
670   GNUNET_assert (ctx->op == op);
671   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
672   if (NULL != emsg)
673   {
674     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
675     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
676     ctx->op = NULL;
677     return;
678   }
679   
680   ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_put, ac);
681 }
682
683
684 /**
685  * Connect to DHT service and return the DHT client handler
686  *
687  * @param cls the active context
688  * @param cfg configuration of the peer to connect to; will be available until
689  *          GNUNET_TESTBED_operation_done() is called on the operation returned
690  *          from GNUNET_TESTBED_service_connect()
691  * @return service handle to return in 'op_result', NULL on error
692  */
693 static void *
694 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
695 {
696   n_dht++;
697   return GNUNET_DHT_connect (cfg, 10);
698 }
699
700
701 /**
702  * Adapter function called to destroy a connection to
703  * a service.
704  *
705  * @param cls the active context
706  * @param op_result service handle returned from the connect adapter
707  */
708 static void
709 dht_disconnect (void *cls, void *op_result)
710 {
711   struct ActiveContext *ac = cls;
712
713   GNUNET_assert (NULL != ac->dht);
714   GNUNET_assert (ac->dht == op_result);
715   GNUNET_DHT_disconnect (ac->dht);
716   n_dht--;
717   if (0 == n_dht)
718     GNUNET_SCHEDULER_shutdown ();
719 }
720
721
722 /**
723  * FIXME:Verify where is n_active used. Should this service be started only
724  * for n_active peers?
725  * Start testbed service for all the peers. 
726  */
727 static void
728 start_testbed_service_on_all_peers()
729 {
730   unsigned int i;
731   for(i = 0; i < peers_started; i++)
732   {
733       struct Context *ctx = peer_contexts[i];
734       DEBUG("GNUNET_TESTBED_service_connect \n");
735       ctx->op = 
736               GNUNET_TESTBED_service_connect (ctx, 
737                                               ctx->peer,
738                                               "dht",
739                                               &dht_connected, ctx->ac,
740                                               &dht_connect,
741                                               &dht_disconnect,
742                                               ctx->ac);
743      
744   }
745 }
746
747 static unsigned int tries;
748
749 /**
750  * Stats callback. Iterate over the hashmap and check if all th peers form
751  * a virtual ring topology.
752  *
753  * @param cls closure
754  * @param op the operation that has been finished
755  * @param emsg error message in case the operation has failed; will be NULL if
756  *          operation has executed successfully.
757  */
758 static void
759 successor_stats_cont (void *cls, 
760                       struct GNUNET_TESTBED_Operation *op, 
761                       const char *emsg)
762 {
763   struct GNUNET_HashCode *val;
764   struct GNUNET_HashCode *start_val;
765   int count = 0;
766   struct GNUNET_HashCode *key;
767   
768   start_val =(struct GNUNET_HashCode *) GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
769                                                 start_key);
770
771   val = GNUNET_new(struct GNUNET_HashCode);
772   val = start_val;
773   while (count < num_peers)
774   {
775     key = GNUNET_new(struct GNUNET_HashCode);
776     key = val;
777     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
778                                              key);
779     GNUNET_assert(NULL != val);
780     count++;
781   }
782   
783   if (start_val == val)
784   {
785     DEBUG("CIRCLE COMPLETED after %u tries", tries);
786     if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
787     {
788       successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
789       //FIXME: free hashmap. 
790     }
791     successor_stats_op = NULL;
792     
793     if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
794     {
795       start_testbed_service_on_all_peers();
796     }
797     
798     return;
799   }
800   else
801   {
802     if (max_searches == ++tries)
803     {
804       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
805                   "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
806                   " cirle formation.  Exiting\n",
807                   max_searches,tries);
808       if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
809       {
810         successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
811         //FIXME: free hashmap
812       }
813       successor_stats_op = NULL;
814       
815       if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
816       {
817         start_testbed_service_on_all_peers();
818       }
819       
820       return;
821     }
822     
823     //FIXME: change delay use exponential back off. 
824     successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay, &collect_stats, cls);
825   }
826 }
827
828
829 /**
830  * Process successor statistic values.
831  *
832  * @param cls closure
833  * @param peer the peer the statistic belong to
834  * @param subsystem name of subsystem that created the statistic
835  * @param name the name of the datum
836  * @param value the current value
837  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
838  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
839  */
840 static int
841 successor_stats_iterator (void *cls, 
842                           const struct GNUNET_TESTBED_Peer *peer,
843                           const char *subsystem, 
844                           const char *name,
845                           uint64_t value, 
846                           int is_persistent)
847 {
848   static const char *key_string = "XDHT";
849   if (0 == strncmp (key_string, name, strlen (key_string)))
850   {
851     char *my_id_str;
852     char successor_str[13];
853     char truncated_my_id_str[13];
854     char truncated_successor_str[13];
855     struct GNUNET_HashCode *my_id_key;
856     struct GNUNET_HashCode *succ_key;
857     
858     strtok((char *)name,":");
859     my_id_str = strtok(NULL,":");
860     
861     strncpy(truncated_my_id_str, my_id_str, 12);
862     truncated_my_id_str[12] = '\0';
863     my_id_key = GNUNET_new(struct GNUNET_HashCode);
864     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
865     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
866     strncpy(truncated_successor_str, successor_str, 12);
867     truncated_successor_str[12] ='\0';
868    
869     succ_key = GNUNET_new(struct GNUNET_HashCode);
870     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
871     
872     if (0 == flag)
873     {
874       start_key = my_id_key;
875       flag = 1;
876     }
877     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
878                                        my_id_key, (void *)succ_key,
879                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
880   }
881   return GNUNET_OK;
882 }
883
884
885 /* 
886  * Task that collects peer and its corresponding successors. 
887  * 
888  * @param cls Closure (NULL).
889  * @param tc Task Context.
890  */
891 static void
892 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
893 {
894   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
895     return;
896
897   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
898   DEBUG("num_peers = %d", num_peers);
899   GNUNET_assert(NULL != testbed_handles);
900          
901   
902  /* Check for successor pointer, don't start put till the virtual ring topology
903    is not created. */
904   successor_stats_op = 
905           GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
906                                          "dht", NULL,
907                                           successor_stats_iterator, 
908                                           successor_stats_cont, cls);
909   
910   GNUNET_assert(successor_stats_op);
911 }
912
913 /**
914  * Callback called when DHT service on the peer is started
915  *
916  * @param cls the context
917  * @param op the operation that has been finished
918  * @param emsg error message in case the operation has failed; will be NULL if
919  *          operation has executed successfully.
920  */
921 static void
922 service_started (void *cls,
923                  struct GNUNET_TESTBED_Operation *op,
924                  const char *emsg)
925 {
926   struct Context *ctx = cls;
927   
928   GNUNET_assert (NULL != ctx);
929   GNUNET_assert (NULL != ctx->op);
930   GNUNET_TESTBED_operation_done (ctx->op);
931   ctx->op = NULL;
932   if (NULL == ctx->ac)
933     return;
934   
935   if (NULL == peer_contexts)
936   {
937     peer_contexts = GNUNET_malloc(num_peers * sizeof(struct Context *));
938   }
939   
940   peer_contexts[peers_started] = ctx;
941   peers_started++;
942   DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
943     
944   if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task && peers_started == num_peers)
945   {
946      DEBUG("successor_stats_task \n");
947      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
948      collect_stat_cls->service_connect_ctx = cls;
949      collect_stat_cls->op = op;
950      
951      successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
952                                                                     GNUNET_NO);
953      successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay, 
954                                                           &collect_stats, 
955                                                           collect_stat_cls);
956   }
957 }
958
959
960 /**
961  * Signature of a main function for a testcase.
962  *
963  * @param cls closure
964  * @param h the run handle
965  * @param num_peers number of peers in 'peers'
966  * @param peers handle to peers run in the testbed
967  * @param links_succeeded the number of overlay link connection attempts that
968  *          succeeded
969  * @param links_failed the number of overlay link
970  */
971 static void
972 test_run (void *cls,
973           struct GNUNET_TESTBED_RunHandle *h,
974           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
975           unsigned int links_succeeded,
976           unsigned int links_failed)
977 {
978   unsigned int cnt;
979   unsigned int ac_cnt;
980   
981   testbed_handles = peers;  
982   if (NULL == peers)
983   {
984     /* exit */
985     GNUNET_assert (0);
986   }
987   INFO ("%u peers started\n", num_peers);
988   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
989
990   /* select the peers which actively participate in profiling */
991   n_active = num_peers * PUT_PROBABILITY / 100;
992   if (0 == n_active)
993   {
994     GNUNET_SCHEDULER_shutdown ();
995     GNUNET_free (a_ctx);
996     return;
997   }
998   
999 #if ENABLE_MALICIOUS
1000
1001   if(PUT_PROBABILITY + MALICIOUS_PEERS > 100)
1002   {
1003     DEBUG ("Reduce either number of malicious peer or active peers. ");
1004     GNUNET_SCHEDULER_shutdown ();
1005     GNUNET_free (a_ctx);
1006     return;
1007   }
1008   
1009   /* Select the peers which should act maliciously. */
1010   n_malicious = num_peers * MALICIOUS_PEERS / 100;
1011   
1012   /* Select n_malicious peers and ensure that those are not active peers. 
1013      keep all malicious peer at one place, and call act malicious for all
1014      those peers. */
1015   
1016 #endif
1017   
1018   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1019   ac_cnt = 0;
1020   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
1021   {
1022     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1023         PUT_PROBABILITY)
1024       continue;
1025     a_ctx[cnt].ac = &a_ac[ac_cnt];
1026     a_ac[ac_cnt].ctx = &a_ctx[cnt];
1027     ac_cnt++;
1028   }
1029   n_active = ac_cnt;
1030   a_ac = GNUNET_realloc (a_ac, n_active * sizeof (struct ActiveContext));
1031   INFO ("Active peers: %u\n", n_active);
1032
1033   /* start DHT service on all peers */
1034   for (cnt = 0; cnt < num_peers; cnt++)
1035   {
1036     a_ctx[cnt].peer = peers[cnt];
1037     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
1038                                                         peers[cnt],
1039                                                         "dht",
1040                                                         &service_started,
1041                                                         &a_ctx[cnt],
1042                                                         1);
1043   }
1044 }
1045
1046
1047 /**
1048  * Main function that will be run by the scheduler.
1049  *
1050  * @param cls closure
1051  * @param args remaining command-line arguments
1052  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1053  * @param config configuration
1054  */
1055 static void
1056 run (void *cls, char *const *args, const char *cfgfile,
1057      const struct GNUNET_CONFIGURATION_Handle *config)
1058 {
1059   uint64_t event_mask;
1060
1061   if (0 == num_peers)
1062   {
1063     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
1064                 num_peers);
1065     return;
1066   }
1067   cfg = GNUNET_CONFIGURATION_dup (config);
1068   event_mask = 0;
1069   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
1070                       NULL, &test_run, NULL);
1071   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
1072                                 NULL);
1073 }
1074
1075
1076 /**
1077  * Main function.
1078  *
1079  * @return 0 on success
1080  */
1081 int
1082 main (int argc, char *const *argv)
1083 {
1084   int rc;
1085
1086   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1087     {'n', "peers", "COUNT",
1088      gettext_noop ("number of peers to start"),
1089      1, &GNUNET_GETOPT_set_uint, &num_peers},
1090     {'s', "searches", "COUNT",
1091      gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
1092      1, &GNUNET_GETOPT_set_uint, &max_searches},
1093     {'H', "hosts", "FILENAME",
1094      gettext_noop ("name of the file with the login information for the testbed"),
1095      1, &GNUNET_GETOPT_set_string, &hosts_file},
1096     {'d', "delay", "DELAY",
1097      gettext_noop ("delay for starting DHT PUT and GET"),
1098      1, &GNUNET_GETOPT_set_relative_time, &delay},
1099     {'r', "replication", "DEGREE",
1100      gettext_noop ("replication degree for DHT PUTs"),
1101      1, &GNUNET_GETOPT_set_uint, &replication},
1102     {'t', "timeout", "TIMEOUT",
1103      gettext_noop ("timeout for DHT PUT and GET requests"),
1104      1, &GNUNET_GETOPT_set_relative_time, &timeout},
1105     GNUNET_GETOPT_OPTION_END
1106   };
1107
1108   max_searches = 10;
1109   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1110     return 2;
1111   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20); /* default delay */
1112   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1); /* default timeout */
1113   replication = 1;      /* default replication */
1114   rc = 0;
1115   if (GNUNET_OK !=
1116       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
1117                           gettext_noop
1118                           ("Measure quality and performance of the DHT service."),
1119                           options, &run, NULL))
1120     rc = 1;
1121   return rc;
1122 }