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