bc1ee86d882c4bd55972efc544c54d46f9e14fe3
[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 /**
378  * Shutdown task.  Cleanup all resources and operations.
379  *
380  * @param cls NULL
381  * @param tc scheduler task context
382  */
383 static void
384 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
385 {
386   struct ActiveContext *ac;
387   unsigned int cnt;
388
389   in_shutdown = GNUNET_YES;
390   if (NULL != a_ctx)
391   {
392     for (cnt=0; cnt < num_peers; cnt++)
393     {
394       /* Cleanup active context if this peer is an active peer */
395       ac = a_ctx[cnt].ac;
396       if (NULL != ac)
397       {
398         if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
399           GNUNET_SCHEDULER_cancel (ac->delay_task);
400         if (NULL != ac->put_data)
401           GNUNET_free (ac->put_data);
402         if (NULL != ac->dht_put)
403           GNUNET_DHT_put_cancel (ac->dht_put);
404         if (NULL != ac->dht_get)
405           GNUNET_DHT_get_stop (ac->dht_get);
406       }
407       /* Cleanup testbed operation handle at the last as this operation may
408          contain service connection to DHT */
409       if (NULL != a_ctx[cnt].op)
410         GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
411     }
412     GNUNET_free (a_ctx);
413     a_ctx = NULL;
414   }
415   //FIXME: Should we collect stats only for put/get not for other messages.
416   if(NULL != bandwidth_stats_op)
417     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
418   bandwidth_stats_op = NULL;
419   GNUNET_free_non_null (a_ac);
420 }
421
422
423 /**
424  * Stats callback. Finish the stats testbed operation and when all stats have
425  * been iterated, shutdown the test.
426  *
427  * @param cls closure
428  * @param op the operation that has been finished
429  * @param emsg error message in case the operation has failed; will be NULL if
430  *          operation has executed successfully.
431  */
432 static void
433 bandwidth_stats_cont (void *cls, 
434                       struct GNUNET_TESTBED_Operation *op, 
435                       const char *emsg)
436 {
437   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
438   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
439   GNUNET_SCHEDULER_shutdown (); 
440 }
441
442
443 /**
444  * Process statistic values.
445  *
446  * @param cls closure
447  * @param peer the peer the statistic belong to
448  * @param subsystem name of subsystem that created the statistic
449  * @param name the name of the datum
450  * @param value the current value
451  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
452  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
453  */
454 static int
455 bandwidth_stats_iterator (void *cls, 
456                           const struct GNUNET_TESTBED_Peer *peer,
457                           const char *subsystem, 
458                           const char *name,
459                           uint64_t value, 
460                           int is_persistent)
461 {
462    static const char *s_sent = "# Bytes transmitted to other peers";
463    static const char *s_recv = "# Bytes received from other peers";
464
465    if (0 == strncmp (s_sent, name, strlen (s_sent)))
466      outgoing_bandwidth = outgoing_bandwidth + value;
467    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
468      incoming_bandwidth = incoming_bandwidth + value;
469    
470     return GNUNET_OK;
471 }
472
473
474 static void
475 summarize ()
476 {
477   INFO ("# PUTS made: %u\n", n_puts);
478   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
479   INFO ("# PUTS failed: %u\n", n_puts_fail);
480   INFO ("# GETS made: %u\n", n_gets);
481   INFO ("# GETS succeeded: %u\n", n_gets_ok);
482   INFO ("# GETS failed: %u\n", n_gets_fail);
483   INFO ("# average_put_path_length: %f\n", average_put_path_length);
484   INFO ("# average_get_path_length: %f\n", average_get_path_length);
485   
486   if (NULL == testbed_handles)
487   {
488     INFO ("No peers found\n");
489     return;
490   }
491   /* Collect Stats*/
492   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
493                                                       "dht", NULL,
494                                                        bandwidth_stats_iterator, 
495                                                        bandwidth_stats_cont, NULL);
496 }
497
498
499 /**
500  * Task to cancel DHT GET.
501  *
502  * @param cls NULL
503  * @param tc scheduler task context
504  */
505 static void
506 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
507 {
508   struct ActiveContext *ac = cls;
509   struct Context *ctx = ac->ctx;
510
511   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
512   GNUNET_assert (NULL != ac->dht_get);
513   GNUNET_DHT_get_stop (ac->dht_get);
514   ac->dht_get = NULL;
515   n_gets_fail++;
516   GNUNET_assert (NULL != ctx->op);
517   GNUNET_TESTBED_operation_done (ctx->op);
518   ctx->op = NULL;
519
520   /* If profiling is complete, summarize */
521   if (n_active == n_gets_fail + n_gets_ok)
522     summarize ();
523
524 }
525
526
527 /**
528  * Iterator called on each result obtained for a DHT
529  * operation that expects a reply
530  *
531  * @param cls closure
532  * @param exp when will this value expire
533  * @param key key of the result
534  * @param get_path peers on reply path (or NULL if not recorded)
535  *                 [0] = datastore's first neighbor, [length - 1] = local peer
536  * @param get_path_length number of entries in @a get_path
537  * @param put_path peers on the PUT path (or NULL if not recorded)
538  *                 [0] = origin, [length - 1] = datastore
539  * @param put_path_length number of entries in @a put_path
540  * @param type type of the result
541  * @param size number of bytes in @a data
542  * @param data pointer to the result data
543  */
544 static void
545 get_iter (void *cls,
546           struct GNUNET_TIME_Absolute exp,
547           const struct GNUNET_HashCode *key,
548           const struct GNUNET_PeerIdentity *get_path,
549           unsigned int get_path_length,
550           const struct GNUNET_PeerIdentity *put_path,
551           unsigned int put_path_length,
552           enum GNUNET_BLOCK_Type type,
553           size_t size, const void *data)
554 {
555   struct ActiveContext *ac = cls;
556   struct ActiveContext *get_ac = ac->get_ac;
557   struct Context *ctx = ac->ctx;
558
559   /* Check the keys of put and get match or not. */
560   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
561   /* we found the data we are looking for */
562   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
563   n_gets_ok++;
564   get_ac->nrefs--;
565   GNUNET_DHT_get_stop (ac->dht_get);
566   ac->dht_get = NULL;
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     ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay_put, &delayed_put, ac);
744     break;
745   case MODE_GET:
746     ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay_get, &delayed_get, ac);
747     break;
748   }
749 }
750
751
752 /**
753  * Connect to DHT service and return the DHT client handler
754  *
755  * @param cls the active context
756  * @param cfg configuration of the peer to connect to; will be available until
757  *          GNUNET_TESTBED_operation_done() is called on the operation returned
758  *          from GNUNET_TESTBED_service_connect()
759  * @return service handle to return in 'op_result', NULL on error
760  */
761 static void *
762 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
763 {
764   n_dht++;
765   return GNUNET_DHT_connect (cfg, 10);
766 }
767
768
769 /**
770  * Connect to DHT services of active peers
771  */
772 static void
773 start_profiling();
774
775
776 /**
777  * Adapter function called to destroy a connection to
778  * a service.
779  *
780  * @param cls the active context
781  * @param op_result service handle returned from the connect adapter
782  */
783 static void
784 dht_disconnect (void *cls, void *op_result)
785 {
786   struct ActiveContext *ac = cls;
787
788   GNUNET_assert (NULL != ac->dht);
789   GNUNET_assert (ac->dht == op_result);
790   GNUNET_DHT_disconnect (ac->dht);
791   ac->dht = NULL;
792   n_dht--;
793   if (0 != n_dht)
794     return;
795   if (GNUNET_YES == in_shutdown)
796     return;
797   switch (mode)
798   {
799   case MODE_PUT:
800     if ((n_puts_ok + n_puts_fail) != n_active)
801       return;
802     /* Start GETs if all PUTs have been made */
803     mode = MODE_GET;
804     //(void) GNUNET_SCHEDULER_add_now (&call_start_profiling, NULL);
805     start_profiling ();
806     return;
807   case MODE_GET:
808     if ((n_gets_ok + n_gets_fail) != n_active)
809       return;
810     break;
811   }
812   GNUNET_SCHEDULER_shutdown ();
813 }
814
815
816 /**
817  * Connect to DHT services of active peers
818  */
819 static void
820 start_profiling()
821 {
822   struct Context *ctx;
823   unsigned int i;
824
825   DEBUG("GNUNET_TESTBED_service_connect \n");
826   GNUNET_break (GNUNET_YES != in_shutdown);
827   for(i = 0; i < n_active; i++)
828   {
829     struct ActiveContext *ac = &a_ac[i];
830     GNUNET_assert (NULL != (ctx = ac->ctx));
831     GNUNET_assert (NULL == ctx->op);
832     ctx->op =
833         GNUNET_TESTBED_service_connect (ctx,
834                                         ctx->peer,
835                                         "dht",
836                                         &dht_connected, ac,
837                                         &dht_connect,
838                                         &dht_disconnect,
839                                         ac);
840   }
841 }
842
843 static int 
844 hashmap_iterate_remove(void *cls, 
845                        const struct GNUNET_HashCode *key, 
846                        void *value)
847 {
848   GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(successor_peer_hashmap, key, value));
849   return GNUNET_YES;
850 }
851
852
853 static unsigned int tries;
854
855 /**
856  * Stats callback. Iterate over the hashmap and check if all th peers form
857  * a virtual ring topology.
858  *
859  * @param cls closure
860  * @param op the operation that has been finished
861  * @param emsg error message in case the operation has failed; will be NULL if
862  *          operation has executed successfully.
863  */
864 static void
865 successor_stats_cont (void *cls, 
866                       struct GNUNET_TESTBED_Operation *op, 
867                       const char *emsg)
868 {
869   struct GNUNET_HashCode *val;
870   struct GNUNET_HashCode *start_val;
871   struct GNUNET_HashCode *key;
872   int count;
873   
874   /* Don't schedule the task till we are looking for circle here. */
875   successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
876   GNUNET_TESTBED_operation_done (successor_stats_op);
877   successor_stats_op = NULL;
878   
879   start_val =
880           (struct GNUNET_HashCode *) GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
881                                                 start_key);
882
883   val = start_val;
884   for (count = 0; count < num_peers; count++)
885   {
886     key = val;
887     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
888                                              key);
889     if(NULL == val)
890     {
891       break;
892     }
893     /* Remove the entry from hashmap. This is done to take care of loop. */
894     if (GNUNET_NO == 
895             GNUNET_CONTAINER_multihashmap_remove (successor_peer_hashmap,
896                                                   key, val))
897     {
898       DEBUG ("Failed to remove entry from hashmap\n");
899       break;
900     }
901     /* If a peer has its own identity as its successor. */
902     if (0 == memcmp(key, val, sizeof (struct GNUNET_HashCode)))
903     {
904       break;
905     } 
906   }
907   
908   GNUNET_assert(GNUNET_SYSERR != 
909           GNUNET_CONTAINER_multihashmap_iterate (successor_peer_hashmap,
910                                                  hashmap_iterate_remove,
911                                                  NULL));
912   
913   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
914                                                                     GNUNET_NO);
915   
916   if ((start_val == val) && (count == num_peers))
917   {
918     DEBUG("CIRCLE COMPLETED after %u tries", tries);
919     //FIXME: FREE HASHMAP.
920     //FIXME: If circle is done, then check that finger table of all the peers
921     //are fill atleast O(log N) and then start with the experiments.
922     if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
923       start_profiling();
924     
925     return;
926   }
927   else
928   {
929     if (max_searches == ++tries)
930     {
931       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932                   "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
933                   " cirle formation.  Exiting\n",
934                   max_searches,tries);
935       if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
936       {
937         successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
938       }
939       if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
940       {
941         start_profiling();
942       }
943       
944       return;
945     }
946     else
947     {
948       flag = 0;
949       successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay_stats, &collect_stats, cls);
950     }
951   } 
952 }
953
954
955 /**
956  * Process successor statistic values.
957  *
958  * @param cls closure
959  * @param peer the peer the statistic belong to
960  * @param subsystem name of subsystem that created the statistic
961  * @param name the name of the datum
962  * @param value the current value
963  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
964  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
965  */
966 static int
967 successor_stats_iterator (void *cls, 
968                           const struct GNUNET_TESTBED_Peer *peer,
969                           const char *subsystem, 
970                           const char *name,
971                           uint64_t value, 
972                           int is_persistent)
973 {
974   static const char *key_string = "XDHT";
975   if (0 == strncmp (key_string, name, strlen (key_string)))
976   {
977     char *my_id_str;
978     char successor_str[13];
979     char truncated_my_id_str[13];
980     char truncated_successor_str[13];
981     struct GNUNET_HashCode *my_id_key;
982     struct GNUNET_HashCode *succ_key;
983     
984     strtok((char *)name,":");
985     my_id_str = strtok(NULL,":");
986     
987     strncpy(truncated_my_id_str, my_id_str, 12);
988     truncated_my_id_str[12] = '\0';
989     my_id_key = GNUNET_new(struct GNUNET_HashCode);
990     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
991     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
992     strncpy(truncated_successor_str, successor_str, 12);
993     truncated_successor_str[12] ='\0';
994    
995     succ_key = GNUNET_new(struct GNUNET_HashCode);
996     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
997     
998     if (0 == flag)
999     {
1000       start_key = my_id_key;
1001       flag = 1;
1002     }
1003     /* FIXME: GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE do not free the value
1004      which is replaced, need to free it. */
1005     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
1006                                        my_id_key, (void *)succ_key,
1007                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1008   }
1009   return GNUNET_OK;
1010 }
1011
1012
1013 /* 
1014  * Task that collects peer and its corresponding successors. 
1015  * 
1016  * @param cls Closure (NULL).
1017  * @param tc Task Context.
1018  */
1019 static void
1020 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1021 {
1022   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
1023     return;
1024
1025   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
1026   GNUNET_assert(NULL != testbed_handles);
1027   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
1028                                                                     GNUNET_NO);
1029   successor_stats_op = 
1030           GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
1031                                          "dht", NULL,
1032                                           successor_stats_iterator, 
1033                                           successor_stats_cont, cls);
1034   
1035   GNUNET_assert(NULL != successor_stats_op);
1036 }
1037
1038
1039 #if ENABLE_MALICIOUS
1040 /**
1041  * Set the malicious variable in peer malicious context.
1042  */
1043 static void
1044 set_malicious()
1045 {
1046   unsigned int i;
1047   DEBUG ("Setting %u peers malicious");
1048   for(i = 0; i < n_malicious; i++)
1049   {
1050     struct MaliciousContext *mc = &a_mc[i];
1051     mc->ctx->op =
1052         GNUNET_TESTBED_service_connect (ac->ctx,
1053                                         ac->ctx->peer,
1054                                         "dht",
1055                                         &dht_set_malicious, mc,
1056                                         &dht_connect,
1057                                         &dht_finish,
1058                                         mc);
1059   }
1060 }
1061 #endif
1062 /**
1063  * Callback called when DHT service on the peer is started
1064  *
1065  * @param cls the context
1066  * @param op the operation that has been finished
1067  * @param emsg error message in case the operation has failed; will be NULL if
1068  *          operation has executed successfully.
1069  */
1070 static void
1071 service_started (void *cls,
1072                  struct GNUNET_TESTBED_Operation *op,
1073                  const char *emsg)
1074 {
1075   struct Context *ctx = cls;
1076
1077   GNUNET_assert (NULL != ctx);
1078   GNUNET_assert (NULL != ctx->op);
1079   GNUNET_TESTBED_operation_done (ctx->op);
1080   ctx->op = NULL;
1081   peers_started++;
1082   DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
1083   if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task && peers_started == num_peers)
1084   {
1085 #if ENABLE_MALICIOUS
1086     set_malicious();
1087 #endif
1088      DEBUG("successor_stats_task \n");
1089      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
1090      collect_stat_cls->service_connect_ctx = cls;
1091      collect_stat_cls->op = op;
1092      successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay_stats,
1093                                                           &collect_stats,
1094                                                           collect_stat_cls);
1095   }
1096 }
1097
1098
1099 /**
1100  * Signature of a main function for a testcase.
1101  *
1102  * @param cls closure
1103  * @param h the run handle
1104  * @param num_peers number of peers in 'peers'
1105  * @param peers handle to peers run in the testbed
1106  * @param links_succeeded the number of overlay link connection attempts that
1107  *          succeeded
1108  * @param links_failed the number of overlay link
1109  */
1110 static void
1111 test_run (void *cls,
1112           struct GNUNET_TESTBED_RunHandle *h,
1113           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
1114           unsigned int links_succeeded,
1115           unsigned int links_failed)
1116 {
1117   unsigned int cnt;
1118   unsigned int ac_cnt;
1119   
1120   testbed_handles = peers;  
1121   if (NULL == peers)
1122   {
1123     /* exit */
1124     GNUNET_assert (0);
1125   }
1126   INFO ("%u peers started\n", num_peers);
1127   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
1128
1129   /* select the peers which actively participate in profiling */
1130   n_active = num_peers * PUT_PROBABILITY / 100;
1131   if (0 == n_active)
1132   {
1133     GNUNET_SCHEDULER_shutdown ();
1134     GNUNET_free (a_ctx);
1135     return;
1136   }
1137   
1138 #if ENABLE_MALICIOUS
1139
1140   if(PUT_PROBABILITY + MALICIOUS_PEERS > 100)
1141   {
1142     DEBUG ("Reduce either number of malicious peer or active peers. ");
1143     GNUNET_SCHEDULER_shutdown ();
1144     GNUNET_free (a_ctx);
1145     return;
1146   }
1147   
1148   /* Select the peers which should act maliciously. */
1149   n_malicious = num_peers * MALICIOUS_PEERS / 100;
1150   
1151   /* Select n_malicious peers and ensure that those are not active peers. 
1152      keep all malicious peer at one place, and call act malicious for all
1153      those peers. */
1154   
1155 #endif
1156   
1157   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
1158   ac_cnt = 0;
1159   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
1160   {
1161     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
1162         PUT_PROBABILITY)
1163       continue;
1164     a_ctx[cnt].ac = &a_ac[ac_cnt];
1165     a_ac[ac_cnt].ctx = &a_ctx[cnt];
1166     ac_cnt++;
1167   }
1168   n_active = ac_cnt;
1169   INFO ("Active peers: %u\n", n_active);
1170
1171   /* start DHT service on all peers */
1172   for (cnt = 0; cnt < num_peers; cnt++)
1173   {
1174     a_ctx[cnt].peer = peers[cnt];
1175     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
1176                                                         peers[cnt],
1177                                                         "dht",
1178                                                         &service_started,
1179                                                         &a_ctx[cnt],
1180                                                         1);
1181   }
1182 }
1183
1184
1185 /**
1186  * Main function that will be run by the scheduler.
1187  *
1188  * @param cls closure
1189  * @param args remaining command-line arguments
1190  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1191  * @param config configuration
1192  */
1193 static void
1194 run (void *cls, char *const *args, const char *cfgfile,
1195      const struct GNUNET_CONFIGURATION_Handle *config)
1196 {
1197   uint64_t event_mask;
1198
1199   if (0 == num_peers)
1200   {
1201     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
1202                 num_peers);
1203     return;
1204   }
1205   cfg = GNUNET_CONFIGURATION_dup (config);
1206   event_mask = 0;
1207   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
1208                       NULL, &test_run, NULL);
1209   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
1210                                 NULL);
1211 }
1212
1213
1214 /**
1215  * Main function.
1216  *
1217  * @return 0 on success
1218  */
1219 int
1220 main (int argc, char *const *argv)
1221 {
1222   int rc;
1223
1224   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1225     {'n', "peers", "COUNT",
1226      gettext_noop ("number of peers to start"),
1227      1, &GNUNET_GETOPT_set_uint, &num_peers},
1228     {'s', "searches", "COUNT",
1229      gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
1230      1, &GNUNET_GETOPT_set_uint, &max_searches},
1231     {'H', "hosts", "FILENAME",
1232      gettext_noop ("name of the file with the login information for the testbed"),
1233      1, &GNUNET_GETOPT_set_string, &hosts_file},
1234     {'D', "delay", "DELAY",
1235      gettext_noop ("delay between rounds for collecting statistics (default: 30 sec)"),
1236      1, &GNUNET_GETOPT_set_relative_time, &delay_stats},
1237     {'P', "PUT-delay", "DELAY",
1238      gettext_noop ("delay to start doing PUTs (default: 1 sec)"),
1239      1, &GNUNET_GETOPT_set_relative_time, &delay_put},
1240     {'G', "GET-delay", "DELAY",
1241      gettext_noop ("delay to start doing GETs (default: 5 min)"),
1242      1, &GNUNET_GETOPT_set_relative_time, &delay_get},
1243     {'r', "replication", "DEGREE",
1244      gettext_noop ("replication degree for DHT PUTs"),
1245      1, &GNUNET_GETOPT_set_uint, &replication},
1246     {'t', "timeout", "TIMEOUT",
1247      gettext_noop ("timeout for DHT PUT and GET requests (default: 1 min)"),
1248      1, &GNUNET_GETOPT_set_relative_time, &timeout},
1249     GNUNET_GETOPT_OPTION_END
1250   };
1251
1252   max_searches = 5;
1253   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1254     return 2;
1255   /* set default delays */
1256   delay_stats = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30);
1257   delay_put = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1);
1258   delay_get = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1259   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1);
1260   replication = 1;      /* default replication */
1261   rc = 0;
1262   if (GNUNET_OK !=
1263       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
1264                           gettext_noop
1265                           ("Measure quality and performance of the DHT service."),
1266                           options, &run, NULL))
1267     rc = 1;
1268   return rc;
1269 }