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