a2bb1fca17229ae3308638b76446d29a8a1b1756
[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 double average_put_path_length;
280
281 /**
282  * Average number of hops taken to do get. 
283  */
284 static double 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 /**
344  * Should we do a PUT (mode = 0) or GET (mode = 1);
345  */
346 static enum
347 {
348   MODE_PUT = 0,
349
350   MODE_GET = 1
351 } mode;
352
353 /**
354  * Task that collects successor statistics from all the peers. 
355  * @param cls
356  * @param tc
357  */
358 static void
359 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
360
361
362 /**
363  * Shutdown task.  Cleanup all resources and operations.
364  *
365  * @param cls NULL
366  * @param tc scheduler task context
367  */
368 static void
369 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
370 {
371   struct ActiveContext *ac;
372   unsigned int cnt;
373
374   if (NULL != a_ctx)
375   {
376     for (cnt=0; cnt < num_peers; cnt++)
377     {
378       if (NULL != a_ctx[cnt].op)
379         GNUNET_TESTBED_operation_done (a_ctx[cnt].op); //FIXME: assertion fails.
380
381       /* Cleanup active context if this peer is an active peer */
382       ac = a_ctx[cnt].ac;
383       if (NULL == ac)
384         continue;
385       if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
386         GNUNET_SCHEDULER_cancel (ac->delay_task);
387       if (NULL != ac->put_data)
388         GNUNET_free (ac->put_data);
389       if (NULL != ac->dht_put)
390         GNUNET_DHT_put_cancel (ac->dht_put);
391       if (NULL != ac->dht_get)
392         GNUNET_DHT_get_stop (ac->dht_get);
393     }
394     GNUNET_free (a_ctx);
395     a_ctx = NULL;
396   }
397   //FIXME: Should we collect stats only for put/get not for other messages.
398   if(NULL != bandwidth_stats_op)
399     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
400   bandwidth_stats_op = NULL;
401   GNUNET_free_non_null (a_ac);
402 }
403
404
405 /**
406  * Stats callback. Finish the stats testbed operation and when all stats have
407  * been iterated, shutdown the test.
408  *
409  * @param cls closure
410  * @param op the operation that has been finished
411  * @param emsg error message in case the operation has failed; will be NULL if
412  *          operation has executed successfully.
413  */
414 static void
415 bandwidth_stats_cont (void *cls, 
416                       struct GNUNET_TESTBED_Operation *op, 
417                       const char *emsg)
418 {
419   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
420   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
421   GNUNET_SCHEDULER_shutdown (); 
422 }
423
424
425 /**
426  * Process statistic values.
427  *
428  * @param cls closure
429  * @param peer the peer the statistic belong to
430  * @param subsystem name of subsystem that created the statistic
431  * @param name the name of the datum
432  * @param value the current value
433  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
434  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
435  */
436 static int
437 bandwidth_stats_iterator (void *cls, 
438                           const struct GNUNET_TESTBED_Peer *peer,
439                           const char *subsystem, 
440                           const char *name,
441                           uint64_t value, 
442                           int is_persistent)
443 {
444    static const char *s_sent = "# Bytes transmitted to other peers";
445    static const char *s_recv = "# Bytes received from other peers";
446
447    if (0 == strncmp (s_sent, name, strlen (s_sent)))
448      outgoing_bandwidth = outgoing_bandwidth + value;
449    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
450      incoming_bandwidth = incoming_bandwidth + value;
451    
452     return GNUNET_OK;
453 }
454
455
456 static void
457 summarize ()
458 {
459   INFO ("# PUTS made: %u\n", n_puts);
460   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
461   INFO ("# PUTS failed: %u\n", n_puts_fail);
462   INFO ("# GETS made: %u\n", n_gets);
463   INFO ("# GETS succeeded: %u\n", n_gets_ok);
464   INFO ("# GETS failed: %u\n", n_gets_fail);
465   INFO ("# average_put_path_length: %f\n", average_put_path_length);
466   INFO ("# average_get_path_length: %f\n", average_get_path_length);
467   
468   if (NULL == testbed_handles)
469   {
470     INFO ("No peers found\n");
471     return;
472   }
473   /* Collect Stats*/
474   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
475                                                       "dht", NULL,
476                                                        bandwidth_stats_iterator, 
477                                                        bandwidth_stats_cont, NULL);
478 }
479
480
481 /**
482  * Task to cancel DHT GET.
483  *
484  * @param cls NULL
485  * @param tc scheduler task context
486  */
487 static void
488 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
489 {
490   struct ActiveContext *ac = cls;
491   struct Context *ctx = ac->ctx;
492
493   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
494   GNUNET_assert (NULL != ac->dht_get);
495   GNUNET_DHT_get_stop (ac->dht_get);
496   ac->dht_get = NULL;
497   n_gets_fail++;
498   GNUNET_assert (NULL != ctx->op);
499   GNUNET_TESTBED_operation_done (ctx->op);
500   ctx->op = NULL;
501
502   /* If profiling is complete, summarize */
503   if (n_active == n_gets_fail + n_gets_ok)
504     summarize ();
505
506 }
507
508
509 /**
510  * Iterator called on each result obtained for a DHT
511  * operation that expects a reply
512  *
513  * @param cls closure
514  * @param exp when will this value expire
515  * @param key key of the result
516  * @param get_path peers on reply path (or NULL if not recorded)
517  *                 [0] = datastore's first neighbor, [length - 1] = local peer
518  * @param get_path_length number of entries in @a get_path
519  * @param put_path peers on the PUT path (or NULL if not recorded)
520  *                 [0] = origin, [length - 1] = datastore
521  * @param put_path_length number of entries in @a put_path
522  * @param type type of the result
523  * @param size number of bytes in @a data
524  * @param data pointer to the result data
525  */
526 static void
527 get_iter (void *cls,
528           struct GNUNET_TIME_Absolute exp,
529           const struct GNUNET_HashCode *key,
530           const struct GNUNET_PeerIdentity *get_path,
531           unsigned int get_path_length,
532           const struct GNUNET_PeerIdentity *put_path,
533           unsigned int put_path_length,
534           enum GNUNET_BLOCK_Type type,
535           size_t size, const void *data)
536 {
537   struct ActiveContext *ac = cls;
538   struct ActiveContext *get_ac = ac->get_ac;
539   struct Context *ctx = ac->ctx;
540
541   /* Check the keys of put and get match or not. */
542   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
543   /* we found the data we are looking for */
544   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
545   n_gets_ok++;
546   get_ac->nrefs--;
547   GNUNET_DHT_get_stop (ac->dht_get);
548   ac->dht_get = NULL;
549   GNUNET_SCHEDULER_cancel (ac->delay_task);
550   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
551   GNUNET_assert (NULL != ctx->op);
552   GNUNET_TESTBED_operation_done (ctx->op);
553   ctx->op = NULL;
554   
555   total_put_path_length = total_put_path_length + put_path_length;
556   total_get_path_length = total_get_path_length + get_path_length;
557   
558   /* Summarize if profiling is complete */
559   if (n_active == n_gets_fail + n_gets_ok)
560   {
561     average_put_path_length = (double)total_put_path_length/(double)n_active;
562     average_get_path_length = (double)total_get_path_length/(double )n_active;
563     summarize ();
564   }
565 }
566
567
568 /**
569  * Task to do DHT GETs
570  *
571  * @param cls the active context
572  * @param tc the scheduler task context
573  */
574 static void
575 delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
576 {
577   struct ActiveContext *ac = cls;
578   struct ActiveContext *get_ac;
579   unsigned int r;
580
581   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
582   get_ac = NULL;
583   while (1)
584   {
585     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
586     get_ac = &a_ac[r];
587     if (NULL != get_ac->put_data)
588       break;
589   }
590   get_ac->nrefs++;
591   ac->get_ac = get_ac;
592   DEBUG ("GET_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
593   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
594                                       GNUNET_BLOCK_TYPE_TEST,
595                                       &get_ac->hash,
596                                       1, /* replication level */
597                                       GNUNET_DHT_RO_NONE,
598                                       NULL, 0, /* extended query and size */
599                                       get_iter, ac); /* GET iterator and closure
600                                                         */
601   n_gets++;
602
603   /* schedule the timeout task for GET */
604   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
605 }
606
607
608 /**
609  * Connect to DHT services of active peers
610  */
611 static void
612 start_profiling();
613
614
615 /**
616  * Queue up a delayed task for doing DHT GET
617  *
618  * @param cls the active context
619  * @param success #GNUNET_OK if the PUT was transmitted,
620  *                #GNUNET_NO on timeout,
621  *                #GNUNET_SYSERR on disconnect from service
622  *                after the PUT message was transmitted
623  *                (so we don't know if it was received or not)
624  */
625 static void
626 put_cont (void *cls, int success)
627 {
628   struct ActiveContext *ac = cls;
629   struct Context *ctx = ac->ctx;
630   struct GNUNET_TESTBED_Operation *op;
631
632   ac->dht_put = NULL;
633   if (success)
634     n_puts_ok++;
635   else
636     n_puts_fail++;
637   GNUNET_assert (NULL != ctx);
638   op = ctx->op;
639   ctx->op = NULL;
640   GNUNET_TESTBED_operation_done (op);
641 }
642
643
644 /**
645  * Task to do DHT PUTS
646  *
647  * @param cls the active context
648  * @param tc the scheduler task context
649  */
650 static void
651 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
652 {
653   struct ActiveContext *ac = cls;
654
655   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
656   /* Generate and DHT PUT some random data */
657   ac->put_data_size = 16;       /* minimum */
658   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
659                                                  (63*1024));
660   ac->put_data = GNUNET_malloc (ac->put_data_size);
661   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
662                               ac->put_data, ac->put_data_size);
663   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
664   DEBUG ("PUT_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
665   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
666                                 replication,
667                                 GNUNET_DHT_RO_NONE,
668                                 GNUNET_BLOCK_TYPE_TEST,
669                                 ac->put_data_size,
670                                 ac->put_data,
671                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
672                                 timeout,                      /* PUT timeout */
673                                 put_cont, ac);                /* continuation and its closure */
674   n_puts++;
675 }
676
677
678 /**
679  * Connection to DHT has been established.  Call the delay task.
680  *
681  * @param cls the active context
682  * @param op the operation that has been finished
683  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
684  * @param emsg error message in case the operation has failed; will be NULL if
685  *          operation has executed successfully.
686  */
687 static void
688 dht_connected (void *cls,
689                struct GNUNET_TESTBED_Operation *op,
690                void *ca_result,
691                const char *emsg)
692 {
693   struct ActiveContext *ac = cls;
694   struct Context *ctx = ac->ctx;
695
696   GNUNET_assert (NULL != ctx); //FIXME: Fails
697   GNUNET_assert (NULL != ctx->op);
698   GNUNET_assert (ctx->op == op);
699   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
700   if (NULL != emsg)
701   {
702     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
703     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
704     ctx->op = NULL;
705     return;
706   }
707   switch (mode)
708   {
709   case MODE_PUT:
710     ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_put, ac);
711     break;
712   case MODE_GET:
713     ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_get, ac);
714     break;
715   }
716 }
717
718
719 /**
720  * Connect to DHT service and return the DHT client handler
721  *
722  * @param cls the active context
723  * @param cfg configuration of the peer to connect to; will be available until
724  *          GNUNET_TESTBED_operation_done() is called on the operation returned
725  *          from GNUNET_TESTBED_service_connect()
726  * @return service handle to return in 'op_result', NULL on error
727  */
728 static void *
729 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
730 {
731   n_dht++;
732   return GNUNET_DHT_connect (cfg, 10);
733 }
734
735
736 /**
737  * Adapter function called to destroy a connection to
738  * a service.
739  *
740  * @param cls the active context
741  * @param op_result service handle returned from the connect adapter
742  */
743 static void
744 dht_disconnect (void *cls, void *op_result)
745 {
746   struct ActiveContext *ac = cls;
747
748   GNUNET_assert (NULL != ac->dht);
749   GNUNET_assert (ac->dht == op_result);
750   GNUNET_DHT_disconnect (ac->dht);
751   ac->dht = NULL;
752   n_dht--;
753   if (0 != n_dht)
754     return;
755   /* Start GETs if all PUTs have been made */
756   if (MODE_PUT == mode)
757   {
758     mode = MODE_GET;
759     start_profiling ();
760     return;
761   }
762   GNUNET_SCHEDULER_shutdown ();
763 }
764
765
766 /**
767  * Connect to DHT services of active peers
768  */
769 static void
770 start_profiling()
771 {
772   unsigned int i;
773   DEBUG("GNUNET_TESTBED_service_connect \n");
774   for(i = 0; i < n_active; i++)
775   {
776     struct ActiveContext *ac = &a_ac[i];
777     ac->ctx->op =
778         GNUNET_TESTBED_service_connect (ac->ctx,
779                                         ac->ctx->peer,
780                                         "dht",
781                                         &dht_connected, ac,
782                                         &dht_connect,
783                                         &dht_disconnect,
784                                         ac);
785   }
786 }
787
788 static unsigned int tries;
789
790 /**
791  * Stats callback. Iterate over the hashmap and check if all th peers form
792  * a virtual ring topology.
793  *
794  * @param cls closure
795  * @param op the operation that has been finished
796  * @param emsg error message in case the operation has failed; will be NULL if
797  *          operation has executed successfully.
798  */
799 static void
800 successor_stats_cont (void *cls, 
801                       struct GNUNET_TESTBED_Operation *op, 
802                       const char *emsg)
803 {
804   struct GNUNET_HashCode *val;
805   struct GNUNET_HashCode *start_val;
806   struct GNUNET_HashCode *key;
807   int count;
808   
809   /* Don't schedule the task till we are looking for circle here. */
810   successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
811   GNUNET_TESTBED_operation_done (successor_stats_op);
812   successor_stats_op = NULL;
813   
814   start_val =
815           (struct GNUNET_HashCode *) GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
816                                                 start_key);
817   val = GNUNET_new(struct GNUNET_HashCode);
818   key = GNUNET_new(struct GNUNET_HashCode);
819   val = start_val;
820   for (count = 0; count < num_peers; count++)
821   {
822     key = val;
823     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
824                                              key);
825     if(NULL == val)
826     {
827       break;
828     }
829     /* Remove the entry from hashmap. This is done to take care of loop. */
830     if (GNUNET_NO == 
831             GNUNET_CONTAINER_multihashmap_remove (successor_peer_hashmap,
832                                                   key, val))
833     {
834       DEBUG ("Failed to remove entry from hashmap\n");
835       break;
836     }
837     /* If a peer has its own identity as its successor. */
838     if (0 == memcmp(&key, &val, sizeof (struct GNUNET_HashCode)))
839     {
840       break;
841     } 
842   }
843   
844   if ((start_val == val) && (count == num_peers))
845   {
846     DEBUG("CIRCLE COMPLETED after %u tries", tries);
847     //FIXME: FREE HASHMAP.
848     //FIXME: If circle is done, then check that finger table of all the peers
849     //are fill atleast O(log N) and then start with the experiments.
850     if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
851       start_profiling();
852     return;
853   }
854   else
855   {
856     if (max_searches == ++tries)
857     {
858       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859                   "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
860                   " cirle formation.  Exiting\n",
861                   max_searches,tries);
862       //FIXME: FREE HASHMAP
863       if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
864       {
865         successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
866       }
867       if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
868       {
869         start_profiling();
870       }
871       
872       return;
873     }
874     else
875     {
876       flag = 0;
877       successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay, &collect_stats, cls);
878     }
879   } 
880 }
881
882
883 /**
884  * Process successor statistic values.
885  *
886  * @param cls closure
887  * @param peer the peer the statistic belong to
888  * @param subsystem name of subsystem that created the statistic
889  * @param name the name of the datum
890  * @param value the current value
891  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
892  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
893  */
894 static int
895 successor_stats_iterator (void *cls, 
896                           const struct GNUNET_TESTBED_Peer *peer,
897                           const char *subsystem, 
898                           const char *name,
899                           uint64_t value, 
900                           int is_persistent)
901 {
902   static const char *key_string = "XDHT";
903   if (0 == strncmp (key_string, name, strlen (key_string)))
904   {
905     char *my_id_str;
906     char successor_str[13];
907     char truncated_my_id_str[13];
908     char truncated_successor_str[13];
909     struct GNUNET_HashCode *my_id_key;
910     struct GNUNET_HashCode *succ_key;
911     
912     strtok((char *)name,":");
913     my_id_str = strtok(NULL,":");
914     
915     strncpy(truncated_my_id_str, my_id_str, 12);
916     truncated_my_id_str[12] = '\0';
917     my_id_key = GNUNET_new(struct GNUNET_HashCode);
918     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
919     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
920     strncpy(truncated_successor_str, successor_str, 12);
921     truncated_successor_str[12] ='\0';
922    
923     succ_key = GNUNET_new(struct GNUNET_HashCode);
924     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
925     
926     if (0 == flag)
927     {
928       start_key = my_id_key;
929       flag = 1;
930     }
931     /* FIXME: GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE do not free the value
932      which is replaced, need to free it. */
933     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
934                                        my_id_key, (void *)succ_key,
935                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
936   }
937   return GNUNET_OK;
938 }
939
940
941 /* 
942  * Task that collects peer and its corresponding successors. 
943  * 
944  * @param cls Closure (NULL).
945  * @param tc Task Context.
946  */
947 static void
948 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
949 {
950   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
951     return;
952
953   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
954   GNUNET_assert(NULL != testbed_handles);
955   successor_stats_op = 
956           GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
957                                          "dht", NULL,
958                                           successor_stats_iterator, 
959                                           successor_stats_cont, cls);
960   
961   GNUNET_assert(NULL != successor_stats_op);
962 }
963
964
965 #if ENABLE_MALICIOUS
966 /**
967  * Set the malicious variable in peer malicious context.
968  */
969 static void
970 set_malicious()
971 {
972   unsigned int i;
973   DEBUG ("Setting %u peers malicious");
974   for(i = 0; i < n_malicious; i++)
975   {
976     struct MaliciousContext *mc = &a_mc[i];
977     mc->ctx->op =
978         GNUNET_TESTBED_service_connect (ac->ctx,
979                                         ac->ctx->peer,
980                                         "dht",
981                                         &dht_set_malicious, mc,
982                                         &dht_connect,
983                                         &dht_finish,
984                                         mc);
985   }
986 }
987 #endif
988 /**
989  * Callback called when DHT service on the peer is started
990  *
991  * @param cls the context
992  * @param op the operation that has been finished
993  * @param emsg error message in case the operation has failed; will be NULL if
994  *          operation has executed successfully.
995  */
996 static void
997 service_started (void *cls,
998                  struct GNUNET_TESTBED_Operation *op,
999                  const char *emsg)
1000 {
1001   struct Context *ctx = cls;
1002
1003   GNUNET_assert (NULL != ctx);
1004   GNUNET_assert (NULL != ctx->op);
1005   GNUNET_TESTBED_operation_done (ctx->op);
1006   peers_started++;
1007   DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
1008   if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task && peers_started == num_peers)
1009   {
1010 #if ENABLE_MALICIOUS
1011     set_malicious();
1012 #endif
1013      DEBUG("successor_stats_task \n");
1014      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
1015      collect_stat_cls->service_connect_ctx = cls;
1016      collect_stat_cls->op = op;
1017      successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
1018                                                                     GNUNET_NO);
1019      successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay,
1020                                                           &collect_stats,
1021                                                           collect_stat_cls);
1022   }
1023 }
1024
1025
1026 /**
1027  * Signature of a main function for a testcase.
1028  *
1029  * @param cls closure
1030  * @param h the run handle
1031  * @param num_peers number of peers in 'peers'
1032  * @param peers handle to peers run in the testbed
1033  * @param links_succeeded the number of overlay link connection attempts that
1034  *          succeeded
1035  * @param links_failed the number of overlay link
1036  */
1037 static void
1038 test_run (void *cls,
1039           struct GNUNET_TESTBED_RunHandle *h,
1040           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
1041           unsigned int links_succeeded,
1042           unsigned int links_failed)
1043 {
1044   unsigned int cnt;
1045   unsigned int ac_cnt;
1046   
1047   testbed_handles = peers;  
1048   if (NULL == peers)
1049   {
1050     /* exit */
1051     GNUNET_assert (0);
1052   }
1053   INFO ("%u peers started\n", num_peers);
1054   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
1055
1056   /* select the peers which actively participate in profiling */
1057   n_active = num_peers * PUT_PROBABILITY / 100;
1058   if (0 == n_active)
1059   {
1060     GNUNET_SCHEDULER_shutdown ();
1061     GNUNET_free (a_ctx);
1062     return;
1063   }
1064   
1065 #if ENABLE_MALICIOUS
1066
1067   if(PUT_PROBABILITY + MALICIOUS_PEERS > 100)
1068   {
1069     DEBUG ("Reduce either number of malicious peer or active peers. ");
1070     GNUNET_SCHEDULER_shutdown ();
1071     GNUNET_free (a_ctx);
1072     return;
1073   }
1074   
1075   /* Select the peers which should act maliciously. */
1076   n_malicious = num_peers * MALICIOUS_PEERS / 100;
1077   
1078   /* Select n_malicious peers and ensure that those are not active peers. 
1079      keep all malicious peer at one place, and call act malicious for all
1080      those peers. */
1081   
1082 #endif
1083   
1084   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1085   ac_cnt = 0;
1086   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
1087   {
1088     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1089         PUT_PROBABILITY)
1090       continue;
1091     a_ctx[cnt].ac = &a_ac[ac_cnt];
1092     a_ac[ac_cnt].ctx = &a_ctx[cnt];
1093     ac_cnt++;
1094   }
1095   n_active = ac_cnt;
1096   a_ac = GNUNET_realloc (a_ac, n_active * sizeof (struct ActiveContext));
1097   INFO ("Active peers: %u\n", n_active);
1098
1099   /* start DHT service on all peers */
1100   for (cnt = 0; cnt < num_peers; cnt++)
1101   {
1102     a_ctx[cnt].peer = peers[cnt];
1103     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
1104                                                         peers[cnt],
1105                                                         "dht",
1106                                                         &service_started,
1107                                                         &a_ctx[cnt],
1108                                                         1);
1109   }
1110 }
1111
1112
1113 /**
1114  * Main function that will be run by the scheduler.
1115  *
1116  * @param cls closure
1117  * @param args remaining command-line arguments
1118  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1119  * @param config configuration
1120  */
1121 static void
1122 run (void *cls, char *const *args, const char *cfgfile,
1123      const struct GNUNET_CONFIGURATION_Handle *config)
1124 {
1125   uint64_t event_mask;
1126
1127   if (0 == num_peers)
1128   {
1129     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
1130                 num_peers);
1131     return;
1132   }
1133   cfg = GNUNET_CONFIGURATION_dup (config);
1134   event_mask = 0;
1135   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
1136                       NULL, &test_run, NULL);
1137   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
1138                                 NULL);
1139 }
1140
1141
1142 /**
1143  * Main function.
1144  *
1145  * @return 0 on success
1146  */
1147 int
1148 main (int argc, char *const *argv)
1149 {
1150   int rc;
1151
1152   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1153     {'n', "peers", "COUNT",
1154      gettext_noop ("number of peers to start"),
1155      1, &GNUNET_GETOPT_set_uint, &num_peers},
1156     {'s', "searches", "COUNT",
1157      gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
1158      1, &GNUNET_GETOPT_set_uint, &max_searches},
1159     {'H', "hosts", "FILENAME",
1160      gettext_noop ("name of the file with the login information for the testbed"),
1161      1, &GNUNET_GETOPT_set_string, &hosts_file},
1162     {'d', "delay", "DELAY",
1163      gettext_noop ("delay for starting DHT PUT and GET"),
1164      1, &GNUNET_GETOPT_set_relative_time, &delay},
1165     {'r', "replication", "DEGREE",
1166      gettext_noop ("replication degree for DHT PUTs"),
1167      1, &GNUNET_GETOPT_set_uint, &replication},
1168     {'t', "timeout", "TIMEOUT",
1169      gettext_noop ("timeout for DHT PUT and GET requests"),
1170      1, &GNUNET_GETOPT_set_relative_time, &timeout},
1171     GNUNET_GETOPT_OPTION_END
1172   };
1173
1174   max_searches = 5;
1175   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1176     return 2;
1177   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20); /* default delay */
1178   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1); /* default timeout */
1179   replication = 1;      /* default replication */
1180   rc = 0;
1181   if (GNUNET_OK !=
1182       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
1183                           gettext_noop
1184                           ("Measure quality and performance of the DHT service."),
1185                           options, &run, NULL))
1186     rc = 1;
1187   return rc;
1188 }