If 0 max search, use r5n dht
[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    DEBUG("inside bandwidth_stats_iterator()\n");
465    
466    if (0 == strncmp (s_sent, name, strlen (s_sent)))
467      outgoing_bandwidth = outgoing_bandwidth + value;
468    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
469      incoming_bandwidth = incoming_bandwidth + value;
470    
471     return GNUNET_OK;
472 }
473
474
475 static void
476 summarize ()
477 {
478   INFO ("# PUTS made: %u\n", n_puts);
479   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
480   INFO ("# PUTS failed: %u\n", n_puts_fail);
481   INFO ("# GETS made: %u\n", n_gets);
482   INFO ("# GETS succeeded: %u\n", n_gets_ok);
483   INFO ("# GETS failed: %u\n", n_gets_fail);
484   INFO ("# average_put_path_length: %f\n", average_put_path_length);
485   INFO ("# average_get_path_length: %f\n", average_get_path_length);
486   
487   if (NULL == testbed_handles)
488   {
489     INFO ("No peers found\n");
490     return;
491   }
492   /* Collect Stats*/
493   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
494                                                       "dht", NULL,
495                                                        bandwidth_stats_iterator, 
496                                                        bandwidth_stats_cont, NULL);
497 }
498
499
500 /**
501  * Task to cancel DHT GET.
502  *
503  * @param cls NULL
504  * @param tc scheduler task context
505  */
506 static void
507 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
508 {
509   struct ActiveContext *ac = cls;
510   struct Context *ctx = ac->ctx;
511
512   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
513   GNUNET_assert (NULL != ac->dht_get);
514   GNUNET_DHT_get_stop (ac->dht_get);
515   ac->dht_get = NULL;
516   n_gets_fail++;
517   GNUNET_assert (NULL != ctx->op);
518   GNUNET_TESTBED_operation_done (ctx->op);
519   ctx->op = NULL;
520
521   DEBUG("inside cancel_get()");
522   
523   /* If profiling is complete, summarize */
524   if (n_active == n_gets_fail + n_gets_ok)
525   {
526     average_put_path_length = (double)total_put_path_length/(double)n_active;
527     average_get_path_length = (double)total_get_path_length/(double )n_gets_ok;
528     summarize ();
529   }
530 }
531
532
533 /**
534  * Iterator called on each result obtained for a DHT
535  * operation that expects a reply
536  *
537  * @param cls closure
538  * @param exp when will this value expire
539  * @param key key of the result
540  * @param get_path peers on reply path (or NULL if not recorded)
541  *                 [0] = datastore's first neighbor, [length - 1] = local peer
542  * @param get_path_length number of entries in @a get_path
543  * @param put_path peers on the PUT path (or NULL if not recorded)
544  *                 [0] = origin, [length - 1] = datastore
545  * @param put_path_length number of entries in @a put_path
546  * @param type type of the result
547  * @param size number of bytes in @a data
548  * @param data pointer to the result data
549  */
550 static void
551 get_iter (void *cls,
552           struct GNUNET_TIME_Absolute exp,
553           const struct GNUNET_HashCode *key,
554           const struct GNUNET_PeerIdentity *get_path,
555           unsigned int get_path_length,
556           const struct GNUNET_PeerIdentity *put_path,
557           unsigned int put_path_length,
558           enum GNUNET_BLOCK_Type type,
559           size_t size, const void *data)
560 {
561   struct ActiveContext *ac = cls;
562   struct ActiveContext *get_ac = ac->get_ac;
563   struct Context *ctx = ac->ctx;
564
565   /* Check the keys of put and get match or not. */
566   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
567   /* we found the data we are looking for */
568   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok)); //FIXME: It always prints 1.
569   n_gets_ok++;
570   get_ac->nrefs--;
571   GNUNET_DHT_get_stop (ac->dht_get);
572   ac->dht_get = NULL;
573   if (ac->delay_task != GNUNET_SCHEDULER_NO_TASK)
574     GNUNET_SCHEDULER_cancel (ac->delay_task);
575   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
576   GNUNET_assert (NULL != ctx->op);
577   GNUNET_TESTBED_operation_done (ctx->op);
578   ctx->op = NULL;
579   
580   total_put_path_length = total_put_path_length + put_path_length;
581   total_get_path_length = total_get_path_length + get_path_length;
582   
583   /* Summarize if profiling is complete */
584   if (n_active == n_gets_fail + n_gets_ok)
585   {
586     average_put_path_length = (double)total_put_path_length/(double)n_active;
587     average_get_path_length = (double)total_get_path_length/(double )n_gets_ok;
588     summarize ();
589   }
590 }
591
592
593 /**
594  * Task to do DHT GETs
595  *
596  * @param cls the active context
597  * @param tc the scheduler task context
598  */
599 static void
600 delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
601 {
602   struct ActiveContext *ac = cls;
603   struct ActiveContext *get_ac;
604   unsigned int r;
605
606   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
607   get_ac = NULL;
608   while (1)
609   {
610     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
611     get_ac = &a_ac[r];
612     if (NULL != get_ac->put_data)
613       break;
614   }
615   get_ac->nrefs++;
616   ac->get_ac = get_ac;
617   DEBUG ("GET_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
618   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
619                                       GNUNET_BLOCK_TYPE_TEST,
620                                       &get_ac->hash,
621                                       1, /* replication level */
622                                       GNUNET_DHT_RO_NONE,
623                                       NULL, 0, /* extended query and size */
624                                       get_iter, ac); /* GET iterator and closure
625                                                         */
626   n_gets++;
627
628   /* schedule the timeout task for GET */
629   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
630 }
631
632
633 /**
634  * Task to teardown the dht connection.  We do it as a task because calling
635  * GNUNET_DHT_disconnect() from put_continutation_callback seems illegal (the
636  * put_continuation_callback() is getting called again synchronously).  Also,
637  * only free the operation when we are not shutting down; the shutdown task will
638  * clear the operation during shutdown.
639  *
640  * @param cls the context
641  * @return tc scheduler task context.
642  */
643 static void
644 teardown_dht_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
645 {
646   struct Context *ctx = cls;
647   struct GNUNET_TESTBED_Operation *op;
648
649   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
650     return;
651   GNUNET_assert (NULL != ctx);
652   GNUNET_assert (NULL != (op = ctx->op));
653   ctx->op = NULL;
654   GNUNET_TESTBED_operation_done (op);
655 }
656
657
658 /**
659  * Queue up a delayed task for doing DHT GET
660  *
661  * @param cls the active context
662  * @param success #GNUNET_OK if the PUT was transmitted,
663  *                #GNUNET_NO on timeout,
664  *                #GNUNET_SYSERR on disconnect from service
665  *                after the PUT message was transmitted
666  *                (so we don't know if it was received or not)
667  */
668 static void
669 put_cont (void *cls, int success)
670 {
671   struct ActiveContext *ac = cls;
672   struct Context *ctx = ac->ctx;
673
674   ac->dht_put = NULL;
675   if (success)
676     n_puts_ok++;
677   else
678     n_puts_fail++;
679   GNUNET_assert (NULL != ctx);
680   (void) GNUNET_SCHEDULER_add_now (&teardown_dht_connection, ctx);
681 }
682
683
684 /**
685  * Task to do DHT PUTS
686  *
687  * @param cls the active context
688  * @param tc the scheduler task context
689  */
690 static void
691 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
692 {
693   struct ActiveContext *ac = cls;
694
695   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
696   /* Generate and DHT PUT some random data */
697   ac->put_data_size = 16;       /* minimum */
698   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
699                                                  (63*1024));
700   ac->put_data = GNUNET_malloc (ac->put_data_size);
701   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
702                               ac->put_data, ac->put_data_size);
703   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
704   DEBUG ("PUT_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
705   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
706                                 replication,
707                                 GNUNET_DHT_RO_NONE,
708                                 GNUNET_BLOCK_TYPE_TEST,
709                                 ac->put_data_size,
710                                 ac->put_data,
711                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
712                                 timeout,                      /* PUT timeout */
713                                 put_cont, ac);                /* continuation and its closure */
714   n_puts++;
715 }
716
717
718 /**
719  * Connection to DHT has been established.  Call the delay task.
720  *
721  * @param cls the active context
722  * @param op the operation that has been finished
723  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
724  * @param emsg error message in case the operation has failed; will be NULL if
725  *          operation has executed successfully.
726  */
727 static void
728 dht_connected (void *cls,
729                struct GNUNET_TESTBED_Operation *op,
730                void *ca_result,
731                const char *emsg)
732 {
733   struct ActiveContext *ac = cls;
734   struct Context *ctx = ac->ctx;
735
736   GNUNET_assert (NULL != ctx); //FIXME: Fails
737   GNUNET_assert (NULL != ctx->op);
738   GNUNET_assert (ctx->op == op);
739   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
740   if (NULL != emsg)
741   {
742     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
743     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
744     ctx->op = NULL;
745     return;
746   }
747   switch (mode)
748   {
749   case MODE_PUT:
750   {
751     struct GNUNET_TIME_Relative peer_delay_put;
752     peer_delay_put.rel_value_us =
753       delay_put.rel_value_us +
754       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
755                                 delay_put.rel_value_us);
756     ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_put, &delayed_put, ac);
757     break;
758   }
759   case MODE_GET:
760   {
761     struct GNUNET_TIME_Relative peer_delay_get;
762     peer_delay_get.rel_value_us =
763       delay_get.rel_value_us +
764       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
765                                 delay_get.rel_value_us);
766     ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_get, &delayed_get, ac);
767     break;
768   }
769   }
770 }
771
772
773 /**
774  * Connect to DHT service and return the DHT client handler
775  *
776  * @param cls the active context
777  * @param cfg configuration of the peer to connect to; will be available until
778  *          GNUNET_TESTBED_operation_done() is called on the operation returned
779  *          from GNUNET_TESTBED_service_connect()
780  * @return service handle to return in 'op_result', NULL on error
781  */
782 static void *
783 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
784 {
785   n_dht++;
786   return GNUNET_DHT_connect (cfg, 10);
787 }
788
789
790 /**
791  * Connect to DHT services of active peers
792  */
793 static void
794 start_profiling();
795
796
797 /**
798  * Adapter function called to destroy a connection to
799  * a service.
800  *
801  * @param cls the active context
802  * @param op_result service handle returned from the connect adapter
803  */
804 static void
805 dht_disconnect (void *cls, void *op_result)
806 {
807   struct ActiveContext *ac = cls;
808
809   GNUNET_assert (NULL != ac->dht);
810   GNUNET_assert (ac->dht == op_result);
811   GNUNET_DHT_disconnect (ac->dht);
812   ac->dht = NULL;
813   n_dht--;
814   if (0 != n_dht)
815     return;
816   if (GNUNET_YES == in_shutdown)
817     return;
818   switch (mode)
819   {
820   case MODE_PUT:
821     if ((n_puts_ok + n_puts_fail) != n_active)
822       return;
823     /* Start GETs if all PUTs have been made */
824     mode = MODE_GET;
825     //(void) GNUNET_SCHEDULER_add_now (&call_start_profiling, NULL);
826     start_profiling ();
827     return;
828   case MODE_GET:
829     if ((n_gets_ok + n_gets_fail) != n_active)
830       return;
831     break;
832   }
833 }
834
835
836 /**
837  * Connect to DHT services of active peers
838  */
839 static void
840 start_profiling()
841 {
842   struct Context *ctx;
843   unsigned int i;
844
845   DEBUG("GNUNET_TESTBED_service_connect \n");
846   GNUNET_break (GNUNET_YES != in_shutdown);
847   for(i = 0; i < n_active; i++)
848   {
849     struct ActiveContext *ac = &a_ac[i];
850     GNUNET_assert (NULL != (ctx = ac->ctx));
851     GNUNET_assert (NULL == ctx->op);
852     ctx->op =
853         GNUNET_TESTBED_service_connect (ctx,
854                                         ctx->peer,
855                                         "dht",
856                                         &dht_connected, ac,
857                                         &dht_connect,
858                                         &dht_disconnect,
859                                         ac);
860   }
861 }
862
863 static int 
864 hashmap_iterate_remove(void *cls, 
865                        const struct GNUNET_HashCode *key, 
866                        void *value)
867 {
868   GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(successor_peer_hashmap, key, value));
869   return GNUNET_YES;
870 }
871
872
873 static unsigned int tries;
874
875 /**
876  * Stats callback. Iterate over the hashmap and check if all th peers form
877  * a virtual ring topology.
878  *
879  * @param cls closure
880  * @param op the operation that has been finished
881  * @param emsg error message in case the operation has failed; will be NULL if
882  *          operation has executed successfully.
883  */
884 static void
885 successor_stats_cont (void *cls, 
886                       struct GNUNET_TESTBED_Operation *op, 
887                       const char *emsg)
888 {
889   struct GNUNET_HashCode *val;
890   struct GNUNET_HashCode *start_val;
891   struct GNUNET_HashCode *key;
892   int count;
893   
894   
895   /* Don't schedule the task till we are looking for circle here. */
896   successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
897   GNUNET_TESTBED_operation_done (successor_stats_op);
898   successor_stats_op = NULL;
899   if (0 == max_searches)
900   {
901     start_profiling();
902     return;
903   }
904   start_val =
905           (struct GNUNET_HashCode *) GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
906                                                 start_key);
907
908   val = start_val;
909   for (count = 0; count < num_peers; count++)
910   {
911     key = val;
912     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
913                                              key);
914     if(NULL == val)
915     {
916       break;
917     }
918     /* Remove the entry from hashmap. This is done to take care of loop. */
919     if (GNUNET_NO == 
920             GNUNET_CONTAINER_multihashmap_remove (successor_peer_hashmap,
921                                                   key, val))
922     {
923       DEBUG ("Failed to remove entry from hashmap\n");
924       break;
925     }
926     /* If a peer has its own identity as its successor. */
927     if (0 == memcmp(key, val, sizeof (struct GNUNET_HashCode)))
928     {
929       break;
930     } 
931   }
932   
933   GNUNET_assert(GNUNET_SYSERR != 
934           GNUNET_CONTAINER_multihashmap_iterate (successor_peer_hashmap,
935                                                  hashmap_iterate_remove,
936                                                  NULL));
937   
938   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
939                                                                     GNUNET_NO);
940   //TODO:Check if comparison is correct. 
941   if ((start_val == val) && (count == num_peers))
942   {
943     DEBUG("CIRCLE COMPLETED after %u tries", tries);
944     //FIXME: FREE HASHMAP.
945     //FIXME: If circle is done, then check that finger table of all the peers
946     //are fill atleast O(log N) and then start with the experiments.
947     if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
948       start_profiling();
949     
950     return;
951   }
952   else
953   {
954     if (max_searches == ++tries)
955     {
956       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
957                   "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
958                   " cirle formation.  Exiting\n",
959                   max_searches,tries);
960       if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
961       {
962         successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
963       }
964       if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
965       {
966         start_profiling();
967       }
968       
969       return;
970     }
971     else
972     {
973       flag = 0;
974       successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay_stats, &collect_stats, cls);
975     }
976   } 
977 }
978
979
980 /**
981  * Process successor statistic values.
982  *
983  * @param cls closure
984  * @param peer the peer the statistic belong to
985  * @param subsystem name of subsystem that created the statistic
986  * @param name the name of the datum
987  * @param value the current value
988  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
989  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
990  */
991 static int
992 successor_stats_iterator (void *cls, 
993                           const struct GNUNET_TESTBED_Peer *peer,
994                           const char *subsystem, 
995                           const char *name,
996                           uint64_t value, 
997                           int is_persistent)
998 {
999   static const char *key_string = "XDHT";
1000   if (0 == max_searches)
1001     return GNUNET_OK;
1002   
1003   if (0 == strncmp (key_string, name, strlen (key_string)))
1004   {
1005     char *my_id_str;
1006     char successor_str[13];
1007     char truncated_my_id_str[13];
1008     char truncated_successor_str[13];
1009     struct GNUNET_HashCode *my_id_key;
1010     struct GNUNET_HashCode *succ_key;
1011     
1012     strtok((char *)name,":");
1013     my_id_str = strtok(NULL,":");
1014     
1015     strncpy(truncated_my_id_str, my_id_str, 12);
1016     truncated_my_id_str[12] = '\0';
1017     my_id_key = GNUNET_new(struct GNUNET_HashCode);
1018     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
1019     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
1020     strncpy(truncated_successor_str, successor_str, 12);
1021     truncated_successor_str[12] ='\0';
1022    
1023     succ_key = GNUNET_new(struct GNUNET_HashCode);
1024     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
1025     
1026     if (0 == flag)
1027     {
1028       start_key = my_id_key;
1029       flag = 1;
1030     }
1031     /* FIXME: GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE do not free the value
1032      which is replaced, need to free it. */
1033     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
1034                                        my_id_key, (void *)succ_key,
1035                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1036   }
1037   return GNUNET_OK;
1038 }
1039
1040
1041 /* 
1042  * Task that collects peer and its corresponding successors. 
1043  * 
1044  * @param cls Closure (NULL).
1045  * @param tc Task Context.
1046  */
1047 static void
1048 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1049 {
1050   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
1051     return;
1052
1053   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
1054   GNUNET_assert(NULL != testbed_handles);
1055   
1056   if (0 != max_searches)
1057   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
1058                                                                     GNUNET_NO);
1059   successor_stats_op = 
1060           GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
1061                                          "dht", NULL,
1062                                           successor_stats_iterator, 
1063                                           successor_stats_cont, cls);
1064   
1065   GNUNET_assert(NULL != successor_stats_op);
1066 }
1067
1068
1069 #if ENABLE_MALICIOUS
1070 /**
1071  * Set the malicious variable in peer malicious context.
1072  */
1073 static void
1074 set_malicious()
1075 {
1076   unsigned int i;
1077   DEBUG ("Setting %u peers malicious");
1078   for(i = 0; i < n_malicious; i++)
1079   {
1080     struct MaliciousContext *mc = &a_mc[i];
1081     mc->ctx->op =
1082         GNUNET_TESTBED_service_connect (ac->ctx,
1083                                         ac->ctx->peer,
1084                                         "dht",
1085                                         &dht_set_malicious, mc,
1086                                         &dht_connect,
1087                                         &dht_finish,
1088                                         mc);
1089   }
1090 }
1091 #endif
1092
1093
1094 /**
1095  * Callback called when DHT service on the peer is started
1096  *
1097  * @param cls the context
1098  * @param op the operation that has been finished
1099  * @param emsg error message in case the operation has failed; will be NULL if
1100  *          operation has executed successfully.
1101  */
1102 static void
1103 service_started (void *cls,
1104                  struct GNUNET_TESTBED_Operation *op,
1105                  const char *emsg)
1106 {
1107   struct Context *ctx = cls;
1108
1109   GNUNET_assert (NULL != ctx);
1110   GNUNET_assert (NULL != ctx->op);
1111   GNUNET_TESTBED_operation_done (ctx->op);
1112   ctx->op = NULL;
1113   peers_started++;
1114   DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
1115   if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task && peers_started == num_peers)
1116   {
1117 #if ENABLE_MALICIOUS
1118     set_malicious();
1119 #endif
1120     
1121      DEBUG("successor_stats_task \n");
1122      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
1123      collect_stat_cls->service_connect_ctx = cls;
1124      collect_stat_cls->op = op;
1125      successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay_stats,
1126                                                           &collect_stats,
1127                                                           collect_stat_cls);
1128   }
1129 }
1130
1131
1132 /**
1133  * Signature of a main function for a testcase.
1134  *
1135  * @param cls closure
1136  * @param h the run handle
1137  * @param num_peers number of peers in 'peers'
1138  * @param peers handle to peers run in the testbed
1139  * @param links_succeeded the number of overlay link connection attempts that
1140  *          succeeded
1141  * @param links_failed the number of overlay link
1142  */
1143 static void
1144 test_run (void *cls,
1145           struct GNUNET_TESTBED_RunHandle *h,
1146           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
1147           unsigned int links_succeeded,
1148           unsigned int links_failed)
1149 {
1150   unsigned int cnt;
1151   unsigned int ac_cnt;
1152   
1153   testbed_handles = peers;  
1154   if (NULL == peers)
1155   {
1156     /* exit */
1157     GNUNET_assert (0);
1158   }
1159   INFO ("%u peers started\n", num_peers);
1160   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
1161
1162   /* select the peers which actively participate in profiling */
1163   n_active = num_peers * PUT_PROBABILITY / 100;
1164   if (0 == n_active)
1165   {
1166     GNUNET_SCHEDULER_shutdown ();
1167     GNUNET_free (a_ctx);
1168     return;
1169   }
1170   
1171 #if ENABLE_MALICIOUS
1172
1173   if(PUT_PROBABILITY + MALICIOUS_PEERS > 100)
1174   {
1175     DEBUG ("Reduce either number of malicious peer or active peers. ");
1176     GNUNET_SCHEDULER_shutdown ();
1177     GNUNET_free (a_ctx);
1178     return;
1179   }
1180   
1181   /* Select the peers which should act maliciously. */
1182   n_malicious = num_peers * MALICIOUS_PEERS / 100;
1183   
1184   /* Select n_malicious peers and ensure that those are not active peers. 
1185      keep all malicious peer at one place, and call act malicious for all
1186      those peers. */
1187   
1188 #endif
1189   
1190   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1191   ac_cnt = 0;
1192   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
1193   {
1194     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1195         PUT_PROBABILITY)
1196       continue;
1197     a_ctx[cnt].ac = &a_ac[ac_cnt];
1198     a_ac[ac_cnt].ctx = &a_ctx[cnt];
1199     ac_cnt++;
1200   }
1201   n_active = ac_cnt;
1202   INFO ("Active peers: %u\n", n_active);
1203
1204   /* start DHT service on all peers */
1205   for (cnt = 0; cnt < num_peers; cnt++)
1206   {
1207     a_ctx[cnt].peer = peers[cnt];
1208     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
1209                                                         peers[cnt],
1210                                                         "dht",
1211                                                         &service_started,
1212                                                         &a_ctx[cnt],
1213                                                         1);
1214   }
1215 }
1216
1217
1218 /**
1219  * Main function that will be run by the scheduler.
1220  *
1221  * @param cls closure
1222  * @param args remaining command-line arguments
1223  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1224  * @param config configuration
1225  */
1226 static void
1227 run (void *cls, char *const *args, const char *cfgfile,
1228      const struct GNUNET_CONFIGURATION_Handle *config)
1229 {
1230   uint64_t event_mask;
1231
1232   if (0 == num_peers)
1233   {
1234     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
1235                 num_peers);
1236     return;
1237   }
1238   cfg = GNUNET_CONFIGURATION_dup (config);
1239   event_mask = 0;
1240   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
1241                       NULL, &test_run, NULL);
1242   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
1243                                 NULL);
1244 }
1245
1246
1247 /**
1248  * Main function.
1249  *
1250  * @return 0 on success
1251  */
1252 int
1253 main (int argc, char *const *argv)
1254 {
1255   int rc;
1256
1257   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1258     {'n', "peers", "COUNT",
1259      gettext_noop ("number of peers to start"),
1260      1, &GNUNET_GETOPT_set_uint, &num_peers},
1261     {'s', "searches", "COUNT",
1262      gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
1263      1, &GNUNET_GETOPT_set_uint, &max_searches},
1264     {'H', "hosts", "FILENAME",
1265      gettext_noop ("name of the file with the login information for the testbed"),
1266      1, &GNUNET_GETOPT_set_string, &hosts_file},
1267     {'D', "delay", "DELAY",
1268      gettext_noop ("delay between rounds for collecting statistics (default: 30 sec)"),
1269      1, &GNUNET_GETOPT_set_relative_time, &delay_stats},
1270     {'P', "PUT-delay", "DELAY",
1271      gettext_noop ("delay to start doing PUTs (default: 1 sec)"),
1272      1, &GNUNET_GETOPT_set_relative_time, &delay_put},
1273     {'G', "GET-delay", "DELAY",
1274      gettext_noop ("delay to start doing GETs (default: 5 min)"),
1275      1, &GNUNET_GETOPT_set_relative_time, &delay_get},
1276     {'r', "replication", "DEGREE",
1277      gettext_noop ("replication degree for DHT PUTs"),
1278      1, &GNUNET_GETOPT_set_uint, &replication},
1279     {'t', "timeout", "TIMEOUT",
1280      gettext_noop ("timeout for DHT PUT and GET requests (default: 1 min)"),
1281      1, &GNUNET_GETOPT_set_relative_time, &timeout},
1282     GNUNET_GETOPT_OPTION_END
1283   };
1284
1285   max_searches = 5;
1286   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1287     return 2;
1288   /* set default delays */
1289   delay_stats = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1290   delay_put = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1291   delay_get = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1292   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1293   replication = 1;      /* default replication */
1294   rc = 0;
1295   if (GNUNET_OK !=
1296       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
1297                           gettext_noop
1298                           ("Measure quality and performance of the DHT service."),
1299                           options, &run, NULL))
1300     rc = 1;
1301   return rc;
1302 }