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