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