Changed find_finger and verify_successor timeouts
[oweals/gnunet.git] / src / dht / gnunet_dht_profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2014 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file dht/gnunet_dht_profiler.c
23  * @brief Profiler for GNUnet DHT
24  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_testbed_service.h"
30 #include "gnunet_dht_service.h"
31
32 #define INFO(...)                                       \
33   GNUNET_log (GNUNET_ERROR_TYPE_INFO, __VA_ARGS__)
34
35 #define DEBUG(...)                                           \
36   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
37
38 /**
39  * Number of peers which should perform a PUT out of 100 peers
40  */
41 #define PUT_PROBABILITY 100
42
43 /**
44  * Percentage of peers that should act maliciously.
45  * These peers will never start PUT/GET request.
46  * n_active and n_malicious should not intersect.
47  */
48 #define MALICIOUS_PEERS 0
49
50 /**
51  * Configuration
52  */
53 static struct GNUNET_CONFIGURATION_Handle *cfg;
54
55 /**
56  * Name of the file with the hosts to run the test over
57  */
58 static char *hosts_file;
59
60 /**
61  * Context for a peer which actively does DHT PUT/GET
62  */
63 struct ActiveContext;
64
65 /**
66  * Context to hold data of peer
67  */
68 struct Context
69 {
70
71   /**
72    * The testbed peer this context belongs to
73    */
74   struct GNUNET_TESTBED_Peer *peer;
75
76   /**
77    * Testbed operation acting on this peer
78    */
79   struct GNUNET_TESTBED_Operation *op;
80
81   /**
82    * Active context; NULL if this peer is not an active peer
83    */
84   struct ActiveContext *ac;
85 };
86
87
88 #if ENABLE_MALICIOUS
89 /**
90  * Context for a peer which should act maliciously.
91  */
92 struct MaliciousContext
93 {
94   /**
95    * The linked peer context
96    */
97   struct Context *ctx;
98
99   /**
100    * Handler to the DHT service
101    */
102   struct GNUNET_DHT_Handle *dht;
103 };
104
105 /**
106  * List of all the malicious peers contexts.
107  */
108 struct Context **malicious_peer_contexts = NULL;
109
110 #endif
111
112 /**
113  * Context for a peer which actively does DHT PUT/GET
114  */
115 struct ActiveContext
116 {
117   /**
118    * The linked peer context
119    */
120   struct Context *ctx;
121
122   /**
123    * Handler to the DHT service
124    */
125   struct GNUNET_DHT_Handle *dht;
126
127   /**
128    * The data used for do a PUT.  Will be NULL if a PUT hasn't been performed yet
129    */
130   void *put_data;
131
132   /**
133    * The active context used for our DHT GET
134    */
135   struct ActiveContext *get_ac;
136
137   /**
138    * The put handle
139    */
140   struct GNUNET_DHT_PutHandle *dht_put;
141
142   /**
143    * The get handle
144    */
145   struct GNUNET_DHT_GetHandle *dht_get;
146
147   /**
148    * The hash of the @e put_data
149    */
150   struct GNUNET_HashCode hash;
151
152   /**
153    * Delay task
154    */
155   GNUNET_SCHEDULER_TaskIdentifier delay_task;
156
157   /**
158    * The size of the @e put_data
159    */
160   uint16_t put_data_size;
161
162   /**
163    * The number of peers currently doing GET on our data
164    */
165   uint16_t nrefs;
166 };
167
168
169 /**
170  * An array of contexts.  The size of this array should be equal to @a num_peers
171  */
172 static struct Context *a_ctx;
173
174 /**
175  * Array of active peers
176  */
177 static struct ActiveContext *a_ac;
178
179 /**
180  * The delay between starting to do PUTS and GETS
181  */
182 static struct GNUNET_TIME_Relative delay;
183
184 /**
185  * The 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 /**
354  * Should we do a PUT (mode = 0) or GET (mode = 1);
355  */
356 static enum
357 {
358   MODE_PUT = 0,
359
360   MODE_GET = 1
361 } mode;
362
363 /**
364  * Task that collects successor statistics from all the peers. 
365  * @param cls
366  * @param tc
367  */
368 static void
369 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
370
371
372 /**
373  * Shutdown task.  Cleanup all resources and operations.
374  *
375  * @param cls NULL
376  * @param tc scheduler task context
377  */
378 static void
379 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
380 {
381   struct ActiveContext *ac;
382   unsigned int cnt;
383
384   if (NULL != a_ctx)
385   {
386     for (cnt=0; cnt < num_peers; cnt++)
387     {
388       if (NULL != a_ctx[cnt].op)
389         GNUNET_TESTBED_operation_done (a_ctx[cnt].op); //FIXME: assertion fails.
390
391       /* Cleanup active context if this peer is an active peer */
392       ac = a_ctx[cnt].ac;
393       if (NULL == ac)
394         continue;
395       if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
396         GNUNET_SCHEDULER_cancel (ac->delay_task);
397       if (NULL != ac->put_data)
398         GNUNET_free (ac->put_data);
399       if (NULL != ac->dht_put)
400         GNUNET_DHT_put_cancel (ac->dht_put);
401       if (NULL != ac->dht_get)
402         GNUNET_DHT_get_stop (ac->dht_get);
403     }
404     GNUNET_free (a_ctx);
405     a_ctx = NULL;
406   }
407   //FIXME: Should we collect stats only for put/get not for other messages.
408   if(NULL != bandwidth_stats_op)
409     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
410   bandwidth_stats_op = NULL;
411   GNUNET_free_non_null (a_ac);
412 }
413
414
415 /**
416  * Stats callback. Finish the stats testbed operation and when all stats have
417  * been iterated, shutdown the test.
418  *
419  * @param cls closure
420  * @param op the operation that has been finished
421  * @param emsg error message in case the operation has failed; will be NULL if
422  *          operation has executed successfully.
423  */
424 static void
425 bandwidth_stats_cont (void *cls, 
426                       struct GNUNET_TESTBED_Operation *op, 
427                       const char *emsg)
428 {
429   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
430   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
431   GNUNET_SCHEDULER_shutdown (); 
432 }
433
434
435 /**
436  * Process statistic values.
437  *
438  * @param cls closure
439  * @param peer the peer the statistic belong to
440  * @param subsystem name of subsystem that created the statistic
441  * @param name the name of the datum
442  * @param value the current value
443  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
444  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
445  */
446 static int
447 bandwidth_stats_iterator (void *cls, 
448                           const struct GNUNET_TESTBED_Peer *peer,
449                           const char *subsystem, 
450                           const char *name,
451                           uint64_t value, 
452                           int is_persistent)
453 {
454    static const char *s_sent = "# Bytes transmitted to other peers";
455    static const char *s_recv = "# Bytes received from other peers";
456
457    if (0 == strncmp (s_sent, name, strlen (s_sent)))
458      outgoing_bandwidth = outgoing_bandwidth + value;
459    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
460      incoming_bandwidth = incoming_bandwidth + value;
461    
462     return GNUNET_OK;
463 }
464
465
466 static void
467 summarize ()
468 {
469   INFO ("# PUTS made: %u\n", n_puts);
470   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
471   INFO ("# PUTS failed: %u\n", n_puts_fail);
472   INFO ("# GETS made: %u\n", n_gets);
473   INFO ("# GETS succeeded: %u\n", n_gets_ok);
474   INFO ("# GETS failed: %u\n", n_gets_fail);
475   INFO ("# average_put_path_length: %f\n", average_put_path_length);
476   INFO ("# average_get_path_length: %f\n", average_get_path_length);
477   
478   if (NULL == testbed_handles)
479   {
480     INFO ("No peers found\n");
481     return;
482   }
483   /* Collect Stats*/
484   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
485                                                       "dht", NULL,
486                                                        bandwidth_stats_iterator, 
487                                                        bandwidth_stats_cont, NULL);
488 }
489
490
491 /**
492  * Task to cancel DHT GET.
493  *
494  * @param cls NULL
495  * @param tc scheduler task context
496  */
497 static void
498 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
499 {
500   struct ActiveContext *ac = cls;
501   struct Context *ctx = ac->ctx;
502
503   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
504   GNUNET_assert (NULL != ac->dht_get);
505   GNUNET_DHT_get_stop (ac->dht_get);
506   ac->dht_get = NULL;
507   n_gets_fail++;
508   GNUNET_assert (NULL != ctx->op);
509   GNUNET_TESTBED_operation_done (ctx->op);
510   ctx->op = NULL;
511
512   /* If profiling is complete, summarize */
513   if (n_active == n_gets_fail + n_gets_ok)
514     summarize ();
515
516 }
517
518
519 /**
520  * Iterator called on each result obtained for a DHT
521  * operation that expects a reply
522  *
523  * @param cls closure
524  * @param exp when will this value expire
525  * @param key key of the result
526  * @param get_path peers on reply path (or NULL if not recorded)
527  *                 [0] = datastore's first neighbor, [length - 1] = local peer
528  * @param get_path_length number of entries in @a get_path
529  * @param put_path peers on the PUT path (or NULL if not recorded)
530  *                 [0] = origin, [length - 1] = datastore
531  * @param put_path_length number of entries in @a put_path
532  * @param type type of the result
533  * @param size number of bytes in @a data
534  * @param data pointer to the result data
535  */
536 static void
537 get_iter (void *cls,
538           struct GNUNET_TIME_Absolute exp,
539           const struct GNUNET_HashCode *key,
540           const struct GNUNET_PeerIdentity *get_path,
541           unsigned int get_path_length,
542           const struct GNUNET_PeerIdentity *put_path,
543           unsigned int put_path_length,
544           enum GNUNET_BLOCK_Type type,
545           size_t size, const void *data)
546 {
547   struct ActiveContext *ac = cls;
548   struct ActiveContext *get_ac = ac->get_ac;
549   struct Context *ctx = ac->ctx;
550
551   /* Check the keys of put and get match or not. */
552   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
553   /* we found the data we are looking for */
554   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
555   n_gets_ok++;
556   get_ac->nrefs--;
557   GNUNET_DHT_get_stop (ac->dht_get);
558   ac->dht_get = NULL;
559   GNUNET_SCHEDULER_cancel (ac->delay_task);
560   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
561   GNUNET_assert (NULL != ctx->op);
562   GNUNET_TESTBED_operation_done (ctx->op);
563   ctx->op = NULL;
564   
565   total_put_path_length = total_put_path_length + put_path_length;
566   total_get_path_length = total_get_path_length + get_path_length;
567   
568   /* Summarize if profiling is complete */
569   if (n_active == n_gets_fail + n_gets_ok)
570   {
571     average_put_path_length = (double)total_put_path_length/(double)n_active;
572     average_get_path_length = (double)total_get_path_length/(double )n_active;
573     summarize ();
574   }
575 }
576
577
578 /**
579  * Task to do DHT GETs
580  *
581  * @param cls the active context
582  * @param tc the scheduler task context
583  */
584 static void
585 delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
586 {
587   struct ActiveContext *ac = cls;
588   struct ActiveContext *get_ac;
589   unsigned int r;
590
591   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
592   get_ac = NULL;
593   while (1)
594   {
595     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
596     get_ac = &a_ac[r];
597     if (NULL != get_ac->put_data)
598       break;
599   }
600   get_ac->nrefs++;
601   ac->get_ac = get_ac;
602   DEBUG ("GET_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
603   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
604                                       GNUNET_BLOCK_TYPE_TEST,
605                                       &get_ac->hash,
606                                       1, /* replication level */
607                                       GNUNET_DHT_RO_NONE,
608                                       NULL, 0, /* extended query and size */
609                                       get_iter, ac); /* GET iterator and closure
610                                                         */
611   n_gets++;
612
613   /* schedule the timeout task for GET */
614   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
615 }
616
617
618 /**
619  * Connect to DHT services of active peers
620  */
621 static void
622 start_profiling();
623
624
625 /**
626  * Queue up a delayed task for doing DHT GET
627  *
628  * @param cls the active context
629  * @param success #GNUNET_OK if the PUT was transmitted,
630  *                #GNUNET_NO on timeout,
631  *                #GNUNET_SYSERR on disconnect from service
632  *                after the PUT message was transmitted
633  *                (so we don't know if it was received or not)
634  */
635 static void
636 put_cont (void *cls, int success)
637 {
638   struct ActiveContext *ac = cls;
639   struct Context *ctx = ac->ctx;
640   struct GNUNET_TESTBED_Operation *op;
641
642   ac->dht_put = NULL;
643   if (success)
644     n_puts_ok++;
645   else
646     n_puts_fail++;
647   GNUNET_assert (NULL != ctx);
648   op = ctx->op;
649   ctx->op = NULL;
650   GNUNET_TESTBED_operation_done (op);
651 }
652
653
654 /**
655  * Task to do DHT PUTS
656  *
657  * @param cls the active context
658  * @param tc the scheduler task context
659  */
660 static void
661 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
662 {
663   struct ActiveContext *ac = cls;
664
665   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
666   /* Generate and DHT PUT some random data */
667   ac->put_data_size = 16;       /* minimum */
668   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
669                                                  (63*1024));
670   ac->put_data = GNUNET_malloc (ac->put_data_size);
671   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
672                               ac->put_data, ac->put_data_size);
673   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
674   DEBUG ("PUT_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
675   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
676                                 replication,
677                                 GNUNET_DHT_RO_NONE,
678                                 GNUNET_BLOCK_TYPE_TEST,
679                                 ac->put_data_size,
680                                 ac->put_data,
681                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
682                                 timeout,                      /* PUT timeout */
683                                 put_cont, ac);                /* continuation and its closure */
684   n_puts++;
685 }
686
687
688 /**
689  * Connection to DHT has been established.  Call the delay task.
690  *
691  * @param cls the active context
692  * @param op the operation that has been finished
693  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
694  * @param emsg error message in case the operation has failed; will be NULL if
695  *          operation has executed successfully.
696  */
697 static void
698 dht_connected (void *cls,
699                struct GNUNET_TESTBED_Operation *op,
700                void *ca_result,
701                const char *emsg)
702 {
703   struct ActiveContext *ac = cls;
704   struct Context *ctx = ac->ctx;
705
706   GNUNET_assert (NULL != ctx); //FIXME: Fails
707   GNUNET_assert (NULL != ctx->op);
708   GNUNET_assert (ctx->op == op);
709   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
710   if (NULL != emsg)
711   {
712     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
713     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
714     ctx->op = NULL;
715     return;
716   }
717   switch (mode)
718   {
719   case MODE_PUT:
720     ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_put, ac);
721     break;
722   case MODE_GET:
723     ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_get, ac);
724     break;
725   }
726 }
727
728
729 /**
730  * Connect to DHT service and return the DHT client handler
731  *
732  * @param cls the active context
733  * @param cfg configuration of the peer to connect to; will be available until
734  *          GNUNET_TESTBED_operation_done() is called on the operation returned
735  *          from GNUNET_TESTBED_service_connect()
736  * @return service handle to return in 'op_result', NULL on error
737  */
738 static void *
739 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
740 {
741   n_dht++;
742   return GNUNET_DHT_connect (cfg, 10);
743 }
744
745
746 /**
747  * Adapter function called to destroy a connection to
748  * a service.
749  *
750  * @param cls the active context
751  * @param op_result service handle returned from the connect adapter
752  */
753 static void
754 dht_disconnect (void *cls, void *op_result)
755 {
756   struct ActiveContext *ac = cls;
757
758   GNUNET_assert (NULL != ac->dht);
759   GNUNET_assert (ac->dht == op_result);
760   GNUNET_DHT_disconnect (ac->dht);
761   ac->dht = NULL;
762   n_dht--;
763   if (0 != n_dht)
764     return;
765   /* Start GETs if all PUTs have been made */
766   if (MODE_PUT == mode)
767   {
768     mode = MODE_GET;
769     start_profiling ();
770     return;
771   }
772   GNUNET_SCHEDULER_shutdown ();
773 }
774
775
776 /**
777  * Connect to DHT services of active peers
778  */
779 static void
780 start_profiling()
781 {
782   unsigned int i;
783   DEBUG("GNUNET_TESTBED_service_connect \n");
784   for(i = 0; i < n_active; i++)
785   {
786     struct ActiveContext *ac = &a_ac[i];
787     ac->ctx->op =
788         GNUNET_TESTBED_service_connect (ac->ctx,
789                                         ac->ctx->peer,
790                                         "dht",
791                                         &dht_connected, ac,
792                                         &dht_connect,
793                                         &dht_disconnect,
794                                         ac);
795   }
796 }
797
798 static int 
799 hashmap_iterate_remove(void *cls, 
800                        const struct GNUNET_HashCode *key, 
801                        void *value)
802 {
803   GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(successor_peer_hashmap, key, value));
804   return GNUNET_YES;
805 }
806
807
808 static unsigned int tries;
809
810 /**
811  * Stats callback. Iterate over the hashmap and check if all th peers form
812  * a virtual ring topology.
813  *
814  * @param cls closure
815  * @param op the operation that has been finished
816  * @param emsg error message in case the operation has failed; will be NULL if
817  *          operation has executed successfully.
818  */
819 static void
820 successor_stats_cont (void *cls, 
821                       struct GNUNET_TESTBED_Operation *op, 
822                       const char *emsg)
823 {
824   struct GNUNET_HashCode *val;
825   struct GNUNET_HashCode *start_val;
826   struct GNUNET_HashCode *key;
827   int count;
828   
829   /* Don't schedule the task till we are looking for circle here. */
830   successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
831   GNUNET_TESTBED_operation_done (successor_stats_op);
832   successor_stats_op = NULL;
833   
834   start_val =
835           (struct GNUNET_HashCode *) GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
836                                                 start_key);
837
838   val = start_val;
839   for (count = 0; count < num_peers; count++)
840   {
841     key = val;
842     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
843                                              key);
844     if(NULL == val)
845     {
846       break;
847     }
848     /* Remove the entry from hashmap. This is done to take care of loop. */
849     if (GNUNET_NO == 
850             GNUNET_CONTAINER_multihashmap_remove (successor_peer_hashmap,
851                                                   key, val))
852     {
853       DEBUG ("Failed to remove entry from hashmap\n");
854       break;
855     }
856     /* If a peer has its own identity as its successor. */
857     if (0 == memcmp(key, val, sizeof (struct GNUNET_HashCode)))
858     {
859       break;
860     } 
861   }
862   
863   GNUNET_assert(GNUNET_SYSERR != 
864           GNUNET_CONTAINER_multihashmap_iterate (successor_peer_hashmap,
865                                                  hashmap_iterate_remove,
866                                                  NULL));
867   
868   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
869                                                                     GNUNET_NO);
870   
871   if ((start_val == val) && (count == num_peers))
872   {
873     DEBUG("CIRCLE COMPLETED after %u tries", tries);
874     //FIXME: FREE HASHMAP.
875     //FIXME: If circle is done, then check that finger table of all the peers
876     //are fill atleast O(log N) and then start with the experiments.
877     if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
878       start_profiling();
879     
880     return;
881   }
882   else
883   {
884     if (max_searches == ++tries)
885     {
886       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887                   "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
888                   " cirle formation.  Exiting\n",
889                   max_searches,tries);
890       if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
891       {
892         successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
893       }
894       if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
895       {
896         start_profiling();
897       }
898       
899       return;
900     }
901     else
902     {
903       flag = 0;
904       successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay, &collect_stats, cls);
905     }
906   } 
907 }
908
909
910 /**
911  * Process successor statistic values.
912  *
913  * @param cls closure
914  * @param peer the peer the statistic belong to
915  * @param subsystem name of subsystem that created the statistic
916  * @param name the name of the datum
917  * @param value the current value
918  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
919  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
920  */
921 static int
922 successor_stats_iterator (void *cls, 
923                           const struct GNUNET_TESTBED_Peer *peer,
924                           const char *subsystem, 
925                           const char *name,
926                           uint64_t value, 
927                           int is_persistent)
928 {
929   static const char *key_string = "XDHT";
930   if (0 == strncmp (key_string, name, strlen (key_string)))
931   {
932     char *my_id_str;
933     char successor_str[13];
934     char truncated_my_id_str[13];
935     char truncated_successor_str[13];
936     struct GNUNET_HashCode *my_id_key;
937     struct GNUNET_HashCode *succ_key;
938     
939     strtok((char *)name,":");
940     my_id_str = strtok(NULL,":");
941     
942     strncpy(truncated_my_id_str, my_id_str, 12);
943     truncated_my_id_str[12] = '\0';
944     my_id_key = GNUNET_new(struct GNUNET_HashCode);
945     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
946     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
947     strncpy(truncated_successor_str, successor_str, 12);
948     truncated_successor_str[12] ='\0';
949    
950     succ_key = GNUNET_new(struct GNUNET_HashCode);
951     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
952     
953     if (0 == flag)
954     {
955       start_key = my_id_key;
956       flag = 1;
957     }
958     /* FIXME: GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE do not free the value
959      which is replaced, need to free it. */
960     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
961                                        my_id_key, (void *)succ_key,
962                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
963   }
964   return GNUNET_OK;
965 }
966
967
968 /* 
969  * Task that collects peer and its corresponding successors. 
970  * 
971  * @param cls Closure (NULL).
972  * @param tc Task Context.
973  */
974 static void
975 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
976 {
977   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
978     return;
979
980   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
981   GNUNET_assert(NULL != testbed_handles);
982   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
983                                                                     GNUNET_NO);
984   successor_stats_op = 
985           GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
986                                          "dht", NULL,
987                                           successor_stats_iterator, 
988                                           successor_stats_cont, cls);
989   
990   GNUNET_assert(NULL != successor_stats_op);
991 }
992
993
994 #if ENABLE_MALICIOUS
995 /**
996  * Set the malicious variable in peer malicious context.
997  */
998 static void
999 set_malicious()
1000 {
1001   unsigned int i;
1002   DEBUG ("Setting %u peers malicious");
1003   for(i = 0; i < n_malicious; i++)
1004   {
1005     struct MaliciousContext *mc = &a_mc[i];
1006     mc->ctx->op =
1007         GNUNET_TESTBED_service_connect (ac->ctx,
1008                                         ac->ctx->peer,
1009                                         "dht",
1010                                         &dht_set_malicious, mc,
1011                                         &dht_connect,
1012                                         &dht_finish,
1013                                         mc);
1014   }
1015 }
1016 #endif
1017 /**
1018  * Callback called when DHT service on the peer is started
1019  *
1020  * @param cls the context
1021  * @param op the operation that has been finished
1022  * @param emsg error message in case the operation has failed; will be NULL if
1023  *          operation has executed successfully.
1024  */
1025 static void
1026 service_started (void *cls,
1027                  struct GNUNET_TESTBED_Operation *op,
1028                  const char *emsg)
1029 {
1030   struct Context *ctx = cls;
1031
1032   GNUNET_assert (NULL != ctx);
1033   GNUNET_assert (NULL != ctx->op);
1034   GNUNET_TESTBED_operation_done (ctx->op);
1035   peers_started++;
1036   DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
1037   if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task && peers_started == num_peers)
1038   {
1039 #if ENABLE_MALICIOUS
1040     set_malicious();
1041 #endif
1042      DEBUG("successor_stats_task \n");
1043      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
1044      collect_stat_cls->service_connect_ctx = cls;
1045      collect_stat_cls->op = op;
1046      successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay,
1047                                                           &collect_stats,
1048                                                           collect_stat_cls);
1049   }
1050 }
1051
1052
1053 /**
1054  * Signature of a main function for a testcase.
1055  *
1056  * @param cls closure
1057  * @param h the run handle
1058  * @param num_peers number of peers in 'peers'
1059  * @param peers handle to peers run in the testbed
1060  * @param links_succeeded the number of overlay link connection attempts that
1061  *          succeeded
1062  * @param links_failed the number of overlay link
1063  */
1064 static void
1065 test_run (void *cls,
1066           struct GNUNET_TESTBED_RunHandle *h,
1067           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
1068           unsigned int links_succeeded,
1069           unsigned int links_failed)
1070 {
1071   unsigned int cnt;
1072   unsigned int ac_cnt;
1073   
1074   testbed_handles = peers;  
1075   if (NULL == peers)
1076   {
1077     /* exit */
1078     GNUNET_assert (0);
1079   }
1080   INFO ("%u peers started\n", num_peers);
1081   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
1082
1083   /* select the peers which actively participate in profiling */
1084   n_active = num_peers * PUT_PROBABILITY / 100;
1085   if (0 == n_active)
1086   {
1087     GNUNET_SCHEDULER_shutdown ();
1088     GNUNET_free (a_ctx);
1089     return;
1090   }
1091   
1092 #if ENABLE_MALICIOUS
1093
1094   if(PUT_PROBABILITY + MALICIOUS_PEERS > 100)
1095   {
1096     DEBUG ("Reduce either number of malicious peer or active peers. ");
1097     GNUNET_SCHEDULER_shutdown ();
1098     GNUNET_free (a_ctx);
1099     return;
1100   }
1101   
1102   /* Select the peers which should act maliciously. */
1103   n_malicious = num_peers * MALICIOUS_PEERS / 100;
1104   
1105   /* Select n_malicious peers and ensure that those are not active peers. 
1106      keep all malicious peer at one place, and call act malicious for all
1107      those peers. */
1108   
1109 #endif
1110   
1111   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1112   ac_cnt = 0;
1113   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
1114   {
1115     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1116         PUT_PROBABILITY)
1117       continue;
1118     a_ctx[cnt].ac = &a_ac[ac_cnt];
1119     a_ac[ac_cnt].ctx = &a_ctx[cnt];
1120     ac_cnt++;
1121   }
1122   n_active = ac_cnt;
1123   a_ac = GNUNET_realloc (a_ac, n_active * sizeof (struct ActiveContext));
1124   INFO ("Active peers: %u\n", n_active);
1125
1126   /* start DHT service on all peers */
1127   for (cnt = 0; cnt < num_peers; cnt++)
1128   {
1129     a_ctx[cnt].peer = peers[cnt];
1130     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
1131                                                         peers[cnt],
1132                                                         "dht",
1133                                                         &service_started,
1134                                                         &a_ctx[cnt],
1135                                                         1);
1136   }
1137 }
1138
1139
1140 /**
1141  * Main function that will be run by the scheduler.
1142  *
1143  * @param cls closure
1144  * @param args remaining command-line arguments
1145  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1146  * @param config configuration
1147  */
1148 static void
1149 run (void *cls, char *const *args, const char *cfgfile,
1150      const struct GNUNET_CONFIGURATION_Handle *config)
1151 {
1152   uint64_t event_mask;
1153
1154   if (0 == num_peers)
1155   {
1156     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
1157                 num_peers);
1158     return;
1159   }
1160   cfg = GNUNET_CONFIGURATION_dup (config);
1161   event_mask = 0;
1162   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
1163                       NULL, &test_run, NULL);
1164   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
1165                                 NULL);
1166 }
1167
1168
1169 /**
1170  * Main function.
1171  *
1172  * @return 0 on success
1173  */
1174 int
1175 main (int argc, char *const *argv)
1176 {
1177   int rc;
1178
1179   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1180     {'n', "peers", "COUNT",
1181      gettext_noop ("number of peers to start"),
1182      1, &GNUNET_GETOPT_set_uint, &num_peers},
1183     {'s', "searches", "COUNT",
1184      gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
1185      1, &GNUNET_GETOPT_set_uint, &max_searches},
1186     {'H', "hosts", "FILENAME",
1187      gettext_noop ("name of the file with the login information for the testbed"),
1188      1, &GNUNET_GETOPT_set_string, &hosts_file},
1189     {'d', "delay", "DELAY",
1190      gettext_noop ("delay for starting DHT PUT and GET"),
1191      1, &GNUNET_GETOPT_set_relative_time, &delay},
1192     {'r', "replication", "DEGREE",
1193      gettext_noop ("replication degree for DHT PUTs"),
1194      1, &GNUNET_GETOPT_set_uint, &replication},
1195     {'t', "timeout", "TIMEOUT",
1196      gettext_noop ("timeout for DHT PUT and GET requests"),
1197      1, &GNUNET_GETOPT_set_relative_time, &timeout},
1198     GNUNET_GETOPT_OPTION_END
1199   };
1200
1201   max_searches = 5;
1202   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1203     return 2;
1204   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30); /* default delay */
1205   delay_put = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1); /* default delay */
1206   delay_get = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5); /* default delay */
1207   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1); /* default timeout */
1208   replication = 1;      /* default replication */
1209   rc = 0;
1210   if (GNUNET_OK !=
1211       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
1212                           gettext_noop
1213                           ("Measure quality and performance of the DHT service."),
1214                           options, &run, NULL))
1215     rc = 1;
1216   return rc;
1217 }