-Fixmes
[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  * Configuration
45  */
46 static struct GNUNET_CONFIGURATION_Handle *cfg;
47
48 /**
49  * Name of the file with the hosts to run the test over
50  */
51 static char *hosts_file;
52
53 /**
54  * Context for a peer which actively does DHT PUT/GET
55  */
56 struct ActiveContext;
57
58 /**
59  * Context to hold data of peer
60  */
61 struct Context
62 {
63
64   /**
65    * The testbed peer this context belongs to
66    */
67   struct GNUNET_TESTBED_Peer *peer;
68
69   /**
70    * Testbed operation acting on this peer
71    */
72   struct GNUNET_TESTBED_Operation *op;
73
74   /**
75    * Active context; NULL if this peer is not an active peer
76    */
77   struct ActiveContext *ac;
78 };
79
80
81 /**
82  * Context for a peer which actively does DHT PUT/GET
83  */
84 struct ActiveContext
85 {
86   /**
87    * The linked peer context
88    */
89   struct Context *ctx;
90
91   /**
92    * Handler to the DHT service
93    */
94   struct GNUNET_DHT_Handle *dht;
95
96   /**
97    * The data used for do a PUT.  Will be NULL if a PUT hasn't been performed yet
98    */
99   void *put_data;
100
101   /**
102    * The active context used for our DHT GET
103    */
104   struct ActiveContext *get_ac;
105
106   /**
107    * The put handle
108    */
109   struct GNUNET_DHT_PutHandle *dht_put;
110
111   /**
112    * The get handle
113    */
114   struct GNUNET_DHT_GetHandle *dht_get;
115
116   /**
117    * The hash of the @e put_data
118    */
119   struct GNUNET_HashCode hash;
120
121   /**
122    * Delay task
123    */
124   GNUNET_SCHEDULER_TaskIdentifier delay_task;
125
126   /**
127    * The size of the @e put_data
128    */
129   uint16_t put_data_size;
130
131   /**
132    * The number of peers currently doing GET on our data
133    */
134   uint16_t nrefs;
135 };
136
137
138 /**
139  * An array of contexts.  The size of this array should be equal to @a num_peers
140  */
141 static struct Context *a_ctx;
142
143 /**
144  * Array of active peers
145  */
146 static struct ActiveContext *a_ac;
147
148 /**
149  * The delay between starting to do PUTS and GETS
150  */
151 static struct GNUNET_TIME_Relative delay;
152
153 /**
154  * The timeout for GET and PUT
155  */
156 static struct GNUNET_TIME_Relative timeout;
157
158 /**
159  * Number of peers
160  */
161 static unsigned int num_peers;
162
163 /**
164  * Number of active peers
165  */
166 static unsigned int n_active;
167
168 /**
169  * Number of DHT service connections we currently have
170  */
171 static unsigned int n_dht;
172
173 /**
174  * Number of DHT PUTs made
175  */
176 static unsigned int n_puts;
177
178 /**
179  * Number of DHT PUTs succeeded
180  */
181 static unsigned int n_puts_ok;
182
183 /**
184  * Number of DHT PUTs failed
185  */
186 static unsigned int n_puts_fail;
187
188 /**
189  * Number of DHT GETs made
190  */
191 static unsigned int n_gets;
192
193 /**
194  * Number of DHT GETs succeeded
195  */
196 static unsigned int n_gets_ok;
197
198 /**
199  * Number of DHT GETs succeeded
200  */
201 static unsigned int n_gets_fail;
202
203 /**
204  * Replication degree
205  */
206 static unsigned int replication;
207
208 /**
209  * Number of times we try to find the successor circle formation
210  */
211 static unsigned int max_searches;
212
213 /**
214  * Testbed Operation (to get stats).
215  */
216 static struct GNUNET_TESTBED_Operation *bandwidth_stats_op;
217
218 /**
219  * To get successor stats.
220  */
221 static struct GNUNET_TESTBED_Operation *successor_stats_op;
222
223 /**
224  * Testbed peer handles.
225  */
226 static struct GNUNET_TESTBED_Peer **testbed_handles;
227
228 /**
229  * Total number of messages sent by peer. 
230  */
231 static uint64_t outgoing_bandwidth;
232
233 /**
234  * Total number of messages received by peer.
235  */
236 static uint64_t incoming_bandwidth;
237
238 /**
239  * Average number of hops taken to do put.
240  */
241 static unsigned int average_put_path_length;
242
243 /**
244  * Average number of hops taken to do get. 
245  */
246 static unsigned int average_get_path_length;
247
248 /**
249  * 
250  */
251 static unsigned int total_put_path_length;
252
253 /**
254  *
255  */
256 static unsigned int total_get_path_length;
257
258 /**
259  *
260  */
261 static struct GNUNET_CONTAINER_MultiHashMap *successor_peer_hashmap;
262
263 /**
264  *
265  */
266 static struct GNUNET_HashCode *start_key;
267
268 /**
269  *
270  */
271 static int flag = 0;
272
273 /**
274  * Shutdown task.  Cleanup all resources and operations.
275  *
276  * @param cls NULL
277  * @param tc scheduler task context
278  */
279 static void
280 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
281 {
282   struct ActiveContext *ac;
283   unsigned int cnt;
284
285   if (NULL != a_ctx)
286   {
287     for (cnt=0; cnt < num_peers; cnt++)
288     {
289       if (NULL != a_ctx[cnt].op)
290         GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
291
292       /* Cleanup active context if this peer is an active peer */
293       ac = a_ctx[cnt].ac;
294       if (NULL == ac)
295         continue;
296       if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
297         GNUNET_SCHEDULER_cancel (ac->delay_task);
298       if (NULL != ac->put_data)
299         GNUNET_free (ac->put_data);
300       if (NULL != ac->dht_put)
301         GNUNET_DHT_put_cancel (ac->dht_put);
302       if (NULL != ac->dht_get)
303         GNUNET_DHT_get_stop (ac->dht_get);
304     }
305     GNUNET_free (a_ctx);
306     a_ctx = NULL;
307   }
308   if(NULL != bandwidth_stats_op)
309     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
310   bandwidth_stats_op = NULL;
311   GNUNET_free_non_null (a_ac);
312 }
313
314
315 /**
316  * Stats callback. Finish the stats testbed operation and when all stats have
317  * been iterated, shutdown the test.
318  *
319  * @param cls closure
320  * @param op the operation that has been finished
321  * @param emsg error message in case the operation has failed; will be NULL if
322  *          operation has executed successfully.
323  */
324 static void
325 bandwidth_stats_cont (void *cls, 
326                       struct GNUNET_TESTBED_Operation *op, 
327                       const char *emsg)
328 {
329   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
330   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
331   GNUNET_SCHEDULER_shutdown (); 
332 }
333
334
335 /**
336  * Process statistic values.
337  *
338  * @param cls closure
339  * @param peer the peer the statistic belong to
340  * @param subsystem name of subsystem that created the statistic
341  * @param name the name of the datum
342  * @param value the current value
343  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
344  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
345  */
346 static int
347 bandwidth_stats_iterator (void *cls, 
348                           const struct GNUNET_TESTBED_Peer *peer,
349                           const char *subsystem, 
350                           const char *name,
351                           uint64_t value, 
352                           int is_persistent)
353 {
354    static const char *s_sent = "# Bytes transmitted to other peers";
355    static const char *s_recv = "# Bytes received from other peers";
356
357    if (0 == strncmp (s_sent, name, strlen (s_sent)))
358      outgoing_bandwidth = outgoing_bandwidth + value;
359    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
360      incoming_bandwidth = incoming_bandwidth + value;
361    else
362      return GNUNET_OK;
363    DEBUG ("Bandwith - Out: %lu; In: %lu\n",
364           (unsigned long) outgoing_bandwidth,
365           (unsigned long) incoming_bandwidth);
366    return GNUNET_OK;
367 }
368
369
370 static void
371 summarize ()
372 {
373   INFO ("# PUTS made: %u\n", n_puts);
374   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
375   INFO ("# PUTS failed: %u\n", n_puts_fail);
376   INFO ("# GETS made: %u\n", n_gets);
377   INFO ("# GETS succeeded: %u\n", n_gets_ok);
378   INFO ("# GETS failed: %u\n", n_gets_fail);
379   INFO ("# average_put_path_length: %u\n", average_put_path_length);
380   INFO ("# average_get_path_length: %u\n", average_get_path_length);
381   
382   if (NULL == testbed_handles)
383   {
384     INFO ("No peers found\n");
385     return;
386   }
387   /* Collect Stats*/
388   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
389                                                       "dht", NULL,
390                                                        bandwidth_stats_iterator, 
391                                                        bandwidth_stats_cont, NULL);
392 }
393
394
395 /**
396  * Task to cancel DHT GET.
397  *
398  * @param cls NULL
399  * @param tc scheduler task context
400  */
401 static void
402 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
403 {
404   struct ActiveContext *ac = cls;
405
406   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
407   GNUNET_assert (NULL != ac->dht_get);
408   GNUNET_DHT_get_stop (ac->dht_get);
409   ac->dht_get = NULL;
410   n_gets_fail++;
411
412   /* If profiling is complete, summarize */
413   if (n_active == n_gets_fail + n_gets_ok)
414     summarize ();
415
416 }
417
418
419 /**
420  * Iterator called on each result obtained for a DHT
421  * operation that expects a reply
422  *
423  * @param cls closure
424  * @param exp when will this value expire
425  * @param key key of the result
426  * @param get_path peers on reply path (or NULL if not recorded)
427  *                 [0] = datastore's first neighbor, [length - 1] = local peer
428  * @param get_path_length number of entries in @a get_path
429  * @param put_path peers on the PUT path (or NULL if not recorded)
430  *                 [0] = origin, [length - 1] = datastore
431  * @param put_path_length number of entries in @a put_path
432  * @param type type of the result
433  * @param size number of bytes in @a data
434  * @param data pointer to the result data
435  */
436 static void
437 get_iter (void *cls,
438           struct GNUNET_TIME_Absolute exp,
439           const struct GNUNET_HashCode *key,
440           const struct GNUNET_PeerIdentity *get_path,
441           unsigned int get_path_length,
442           const struct GNUNET_PeerIdentity *put_path,
443           unsigned int put_path_length,
444           enum GNUNET_BLOCK_Type type,
445           size_t size, const void *data)
446 {
447   struct ActiveContext *ac = cls;
448   struct ActiveContext *get_ac = ac->get_ac;
449
450   /* Check the keys of put and get match or not. */
451   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
452   /* we found the data we are looking for */
453   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
454   n_gets_ok++;
455   get_ac->nrefs--;
456   GNUNET_DHT_get_stop (ac->dht_get);
457   ac->dht_get = NULL;
458   GNUNET_SCHEDULER_cancel (ac->delay_task);
459   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
460   
461   total_put_path_length = total_put_path_length + put_path_length;
462   total_get_path_length = total_get_path_length + get_path_length;
463   
464   /* Summarize if profiling is complete */
465   if (n_active == n_gets_fail + n_gets_ok)
466   {
467     average_put_path_length = total_put_path_length/n_active;
468     average_get_path_length = total_get_path_length/n_active;
469     summarize ();
470   }
471 }
472
473
474 /**
475  * Task to do DHT GETs
476  *
477  * @param cls the active context
478  * @param tc the scheduler task context
479  */
480 static void
481 delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
482 {
483   struct ActiveContext *ac = cls;
484   struct ActiveContext *get_ac;
485   unsigned int r;
486
487   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
488   get_ac = NULL;
489   while (1)
490   {
491     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
492     get_ac = &a_ac[r];
493     if (NULL != get_ac->put_data)
494       break;
495   }
496   get_ac->nrefs++;
497   ac->get_ac = get_ac;
498   DEBUG ("Doing a DHT GET for data of size %u\n", get_ac->put_data_size);
499   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
500                                       GNUNET_BLOCK_TYPE_TEST,
501                                       &get_ac->hash,
502                                       1, /* replication level */
503                                       GNUNET_DHT_RO_NONE,
504                                       NULL, 0, /* extended query and size */
505                                       get_iter, ac); /* GET iterator and closure
506                                                         */
507   n_gets++;
508
509   /* schedule the timeout task for GET */
510   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
511 }
512
513
514 /**
515  * Queue up a delayed task for doing DHT GET
516  *
517  * @param cls the active context
518  * @param success #GNUNET_OK if the PUT was transmitted,
519  *                #GNUNET_NO on timeout,
520  *                #GNUNET_SYSERR on disconnect from service
521  *                after the PUT message was transmitted
522  *                (so we don't know if it was received or not)
523  */
524 static void
525 put_cont (void *cls, int success)
526 {
527   struct ActiveContext *ac = cls;
528
529   ac->dht_put = NULL;
530   if (success)
531     n_puts_ok++;
532   else
533     n_puts_fail++;
534   ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_get, ac);
535 }
536
537
538 /**
539  * Stats callback. Finish the stats testbed operation and when all stats have
540  * been iterated, shutdown the test.
541  *
542  * @param cls closure
543  * @param op the operation that has been finished
544  * @param emsg error message in case the operation has failed; will be NULL if
545  *          operation has executed successfully.
546  */
547 static void
548 successor_stats_cont (void *cls, 
549                       struct GNUNET_TESTBED_Operation *op, 
550                       const char *emsg)
551 {
552   /* Check if ring is formed. If yes then schedule put. */
553   struct GNUNET_HashCode *val;
554   struct GNUNET_HashCode *start_val;
555   int count = 0;
556   struct GNUNET_HashCode *key;
557   
558   start_val = GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
559                                                 start_key);
560   
561   val = GNUNET_new(struct GNUNET_HashCode);
562   val = start_val;
563   while (count < n_active)
564   {
565     key = val;
566     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
567                                              key);
568     count++;
569   }
570   
571   if (start_val == val)
572   {
573     DEBUG("Circle complete\n");
574     /* FIXME: Schedule the delayed PUT task */
575   }
576   else
577   {
578     static unsigned int tries;
579
580     DEBUG("Circle not complete\n");
581     if (max_searches == ++tries)
582     {
583       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
584                   "Maximum tries %u exceeded while checking successor"
585                   " cirle formation.  Exiting\n",
586                   max_searches);
587       GNUNET_SCHEDULER_shutdown ();
588       return;
589     }
590     /* FIXME: Re-schedule the successor stats gathering task to run after some
591        delay */
592   }
593 }
594
595
596 /**
597  * Process successor statistic values.
598  *
599  * @param cls closure
600  * @param peer the peer the statistic belong to
601  * @param subsystem name of subsystem that created the statistic
602  * @param name the name of the datum
603  * @param value the current value
604  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
605  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
606  */
607 static int
608 successor_stats_iterator (void *cls, 
609                           const struct GNUNET_TESTBED_Peer *peer,
610                           const char *subsystem, 
611                           const char *name,
612                           uint64_t value, 
613                           int is_persistent)
614 {
615   static const char *key_string = "XDHT";
616   
617   DEBUG (" Inside successor stats,name = %s\n",name);
618   if (0 == strncmp (key_string, name, strlen (key_string)))
619   {
620     char *my_id_str;
621     char *successor_id_str;
622     struct GNUNET_HashCode *my_id;
623     struct GNUNET_HashCode *successor_id;
624     
625     /* Parse the string to get the peer and its successor. */
626     strtok((char *)name,":");
627     my_id_str = strtok(NULL,":");
628     successor_id_str = strtok(NULL,":");
629     
630     /* Get Hash of my_id_str and successor_id_str */
631     my_id = GNUNET_new(struct GNUNET_HashCode);
632     successor_id = GNUNET_new(struct GNUNET_HashCode);
633     GNUNET_CRYPTO_hash (my_id_str, sizeof(my_id_str),my_id);
634     GNUNET_CRYPTO_hash (successor_id_str, sizeof(successor_id_str),successor_id);
635     
636     if (0 == flag)
637     {
638       start_key = my_id;
639       flag = 1;
640     }
641     
642     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
643                                        my_id, (void *)successor_id,
644                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
645    
646
647   }
648   
649   return GNUNET_OK;
650 }
651
652
653 /**
654  * Task to do DHT PUTS
655  *
656  * @param cls the active context
657  * @param tc the scheduler task context
658  */
659 static void
660 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
661 {
662   struct ActiveContext *ac = cls;
663   
664   successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (n_active, 
665                                                                  GNUNET_NO);
666   /* Check for successor pointer, don't start put till the virtual ring topology
667    is not created. */
668   successor_stats_op = 
669           GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
670                                          "dht", NULL,
671                                           successor_stats_iterator, 
672                                           successor_stats_cont, NULL);
673   
674   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
675   /* Generate and DHT PUT some random data */
676   ac->put_data_size = 16;       /* minimum */
677   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
678                                                  (63*1024));
679   ac->put_data = GNUNET_malloc (ac->put_data_size);
680   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
681                               ac->put_data, ac->put_data_size);
682   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
683   DEBUG ("Doing a DHT PUT with data of size %u\n", ac->put_data_size);
684   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
685                                 replication,
686                                 GNUNET_DHT_RO_NONE,
687                                 GNUNET_BLOCK_TYPE_TEST,
688                                 ac->put_data_size,
689                                 ac->put_data,
690                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
691                                 timeout,                      /* PUT timeout */
692                                 put_cont, ac);                /* continuation and its closure */
693   n_puts++;
694 }
695
696
697
698 /**
699  * Connection to DHT has been established.  Call the delay task.
700  *
701  * @param cls the active context
702  * @param op the operation that has been finished
703  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
704  * @param emsg error message in case the operation has failed; will be NULL if
705  *          operation has executed successfully.
706  */
707 static void
708 dht_connected (void *cls,
709                struct GNUNET_TESTBED_Operation *op,
710                void *ca_result,
711                const char *emsg)
712 {
713   struct ActiveContext *ac = cls;
714   struct Context *ctx = ac->ctx;
715
716   GNUNET_assert (NULL != ctx);
717   GNUNET_assert (NULL != ctx->op);
718   GNUNET_assert (ctx->op == op);
719   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
720   if (NULL != emsg)
721   {
722     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
723     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
724     ctx->op = NULL;
725     return;
726   }
727   
728   DEBUG (" Call stats \n");
729  
730   /* FIXME: move this to happen after the successor circle formation is
731      complete */
732   ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_put, ac);
733 }
734
735
736 /**
737  * Connect to DHT service and return the DHT client handler
738  *
739  * @param cls the active context
740  * @param cfg configuration of the peer to connect to; will be available until
741  *          GNUNET_TESTBED_operation_done() is called on the operation returned
742  *          from GNUNET_TESTBED_service_connect()
743  * @return service handle to return in 'op_result', NULL on error
744  */
745 static void *
746 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
747 {
748   n_dht++;
749   return GNUNET_DHT_connect (cfg, 10);
750 }
751
752
753 /**
754  * Adapter function called to destroy a connection to
755  * a service.
756  *
757  * @param cls the active context
758  * @param op_result service handle returned from the connect adapter
759  */
760 static void
761 dht_disconnect (void *cls, void *op_result)
762 {
763   struct ActiveContext *ac = cls;
764
765   GNUNET_assert (NULL != ac->dht);
766   GNUNET_assert (ac->dht == op_result);
767   GNUNET_DHT_disconnect (ac->dht);
768   n_dht--;
769   if (0 == n_dht)
770     GNUNET_SCHEDULER_shutdown ();
771 }
772
773
774 /**
775  * Callback called when DHT service on the peer is started
776  *
777  * @param cls the context
778  * @param op the operation that has been finished
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 service_started (void *cls,
784                  struct GNUNET_TESTBED_Operation *op,
785                  const char *emsg)
786 {
787   struct Context *ctx = cls;
788   static unsigned int nstarted;
789
790   GNUNET_assert (NULL != ctx);
791   GNUNET_assert (NULL != ctx->op);
792   GNUNET_TESTBED_operation_done (ctx->op);
793   ctx->op = NULL;
794   if (NULL == ctx->ac)
795     return;
796   ctx->op = GNUNET_TESTBED_service_connect (ctx, ctx->peer,
797                                             "dht",
798                                             &dht_connected, ctx->ac,
799                                             &dht_connect,
800                                             &dht_disconnect,
801                                             ctx->ac);
802   if (num_peers == ++nstarted)
803   {
804     /* FIXME: schedule a delayed task to scan the successors from statistics of
805        all peers */
806   }
807 }
808
809
810 /**
811  * Signature of a main function for a testcase.
812  *
813  * @param cls closure
814  * @param h the run handle
815  * @param num_peers number of peers in 'peers'
816  * @param peers handle to peers run in the testbed
817  * @param links_succeeded the number of overlay link connection attempts that
818  *          succeeded
819  * @param links_failed the number of overlay link
820  */
821 static void
822 test_run (void *cls,
823           struct GNUNET_TESTBED_RunHandle *h,
824           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
825           unsigned int links_succeeded,
826           unsigned int links_failed)
827 {
828   unsigned int cnt;
829   unsigned int ac_cnt;
830   
831   testbed_handles = peers;  
832   if (NULL == peers)
833   {
834     /* exit */
835     GNUNET_assert (0);
836   }
837   INFO ("%u peers started\n", num_peers);
838   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
839
840   /* select the peers which actively participate in profiling */
841   n_active = num_peers * PUT_PROBABILITY / 100;
842   if (0 == n_active)
843   {
844     GNUNET_SCHEDULER_shutdown ();
845     GNUNET_free (a_ctx);
846     return;
847   }
848   
849   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
850   ac_cnt = 0;
851   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
852   {
853     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
854         PUT_PROBABILITY)
855       continue;
856     a_ctx[cnt].ac = &a_ac[ac_cnt];
857     a_ac[ac_cnt].ctx = &a_ctx[cnt];
858     ac_cnt++;
859   }
860   n_active = ac_cnt;
861   a_ac = GNUNET_realloc (a_ac, n_active * sizeof (struct ActiveContext));
862   INFO ("Active peers: %u\n", n_active);
863
864   /* start DHT service on all peers */
865   for (cnt = 0; cnt < num_peers; cnt++)
866   {
867     a_ctx[cnt].peer = peers[cnt];
868     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
869                                                         peers[cnt],
870                                                         "dht",
871                                                         &service_started,
872                                                         &a_ctx[cnt],
873                                                         1);
874   }
875 }
876
877
878 /**
879  * Main function that will be run by the scheduler.
880  *
881  * @param cls closure
882  * @param args remaining command-line arguments
883  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
884  * @param config configuration
885  */
886 static void
887 run (void *cls, char *const *args, const char *cfgfile,
888      const struct GNUNET_CONFIGURATION_Handle *config)
889 {
890   uint64_t event_mask;
891
892   if (0 == num_peers)
893   {
894     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
895                 num_peers);
896     return;
897   }
898   cfg = GNUNET_CONFIGURATION_dup (config);
899   event_mask = 0;
900   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
901                       NULL, &test_run, NULL);
902   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
903                                 NULL);
904 }
905
906
907 /**
908  * Main function.
909  *
910  * @return 0 on success
911  */
912 int
913 main (int argc, char *const *argv)
914 {
915   int rc;
916
917   static struct GNUNET_GETOPT_CommandLineOption options[] = {
918     {'n', "peers", "COUNT",
919      gettext_noop ("number of peers to start"),
920      1, &GNUNET_GETOPT_set_uint, &num_peers},
921     {'s', "searches", "COUNT",
922      gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
923      1, &GNUNET_GETOPT_set_uint, &max_searches},
924     {'H', "hosts", "FILENAME",
925      gettext_noop ("name of the file with the login information for the testbed"),
926      1, &GNUNET_GETOPT_set_string, &hosts_file},
927     {'d', "delay", "DELAY",
928      gettext_noop ("delay for starting DHT PUT and GET"),
929      1, &GNUNET_GETOPT_set_relative_time, &delay},
930     {'r', "replication", "DEGREE",
931      gettext_noop ("replication degree for DHT PUTs"),
932      1, &GNUNET_GETOPT_set_uint, &replication},
933     {'t', "timeout", "TIMEOUT",
934      gettext_noop ("timeout for DHT PUT and GET requests"),
935      1, &GNUNET_GETOPT_set_relative_time, &timeout},
936     GNUNET_GETOPT_OPTION_END
937   };
938
939   max_searches = 1;
940   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
941     return 2;
942   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1); /* default delay */
943   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1); /* default timeout */
944   replication = 1;      /* default replication */
945   rc = 0;
946   if (GNUNET_OK !=
947       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
948                           gettext_noop
949                           ("Measure quality and performance of the DHT service."),
950                           options, &run, NULL))
951     rc = 1;
952   return rc;
953 }