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