cleaning up testcase some
[oweals/gnunet.git] / src / dht / test_dht_multipeer.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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  * @file dht/test_dht_multipeer.c
22  * @brief testcase for testing DHT service with
23  *        multiple peers.
24  */
25 #include "platform.h"
26 #include "gnunet_testing_lib.h"
27 #include "gnunet_core_service.h"
28 #include "gnunet_dht_service.h"
29
30 /* DEFINES */
31 #define VERBOSE GNUNET_NO
32
33 /* Timeout for entire testcase */
34 #define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
35
36 /* Timeout for waiting for replies to get requests */
37 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
38
39 /* Timeout for waiting for gets to complete */
40 #define GET_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1)
41
42 /* Timeout for waiting for puts to complete */
43 #define PUT_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1)
44
45 #define SECONDS_PER_PEER_START 45
46
47 /* If number of peers not in config file, use this number */
48 #define DEFAULT_NUM_PEERS 5
49
50 #define TEST_DATA_SIZE 8
51
52 #define MAX_OUTSTANDING_PUTS 10
53
54 #define MAX_OUTSTANDING_GETS 10
55
56 #define PATH_TRACKING GNUNET_YES
57
58 /* Structs */
59
60 struct TestPutContext
61 {
62   /**
63    * This is a linked list
64    */
65   struct TestPutContext *next;
66
67   /**
68    * Handle to the first peers DHT service (via the API)
69    */
70   struct GNUNET_DHT_Handle *dht_handle;
71
72   /**
73    *  Handle to the PUT peer daemon
74    */
75   struct GNUNET_TESTING_Daemon *daemon;
76
77   /**
78    *  Identifier for this PUT
79    */
80   uint32_t uid;
81
82   /**
83    * Task for disconnecting DHT handles
84    */
85   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
86 };
87
88 struct TestGetContext
89 {
90   /* This is a linked list */
91   struct TestGetContext *next;
92
93   /**
94    * Handle to the first peers DHT service (via the API)
95    */
96   struct GNUNET_DHT_Handle *dht_handle;
97
98   /**
99    * Handle for the DHT get request
100    */
101   struct GNUNET_DHT_GetHandle *get_handle;
102
103   /**
104    *  Handle to the GET peer daemon
105    */
106   struct GNUNET_TESTING_Daemon *daemon;
107
108   /**
109    *  Identifier for this GET
110    */
111   uint32_t uid;
112
113   /**
114    * Task for disconnecting DHT handles (and stopping GET)
115    */
116   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
117
118   /**
119    * Whether or not this request has been fulfilled already.
120    */
121   int succeeded;
122 };
123
124 /* Globals */
125
126 /**
127  * List of GETS to perform
128  */
129 struct TestGetContext *all_gets;
130
131 /**
132  * List of PUTS to perform
133  */
134 struct TestPutContext *all_puts;
135
136 /**
137  * Directory to store temp data in, defined in config file
138  */
139 static char *test_directory;
140
141 /**
142  * Variable used to store the number of connections we should wait for.
143  */
144 static unsigned int expected_connections;
145
146 /**
147  * Variable used to keep track of how many peers aren't yet started.
148  */
149 static unsigned long long peers_left;
150
151 /**
152  * Handle to the set of all peers run for this test.
153  */
154 static struct GNUNET_TESTING_PeerGroup *pg;
155
156
157 /**
158  * Total number of peers to run, set based on config file.
159  */
160 static unsigned long long num_peers;
161
162 /**
163  * Total number of items to insert.
164  */
165 static unsigned long long num_puts;
166
167 /**
168  * Total number of items to attempt to get.
169  */
170 static unsigned long long num_gets;
171
172 /**
173  * How many puts do we currently have in flight?
174  */
175 static unsigned long long outstanding_puts;
176
177 /**
178  * How many puts are done?
179  */
180 static unsigned long long puts_completed;
181
182 /**
183  * How many puts do we currently have in flight?
184  */
185 static unsigned long long outstanding_gets;
186
187 /**
188  * How many gets are done?
189  */
190 static unsigned long long gets_completed;
191
192 /**
193  * How many gets failed?
194  */
195 static unsigned long long gets_failed;
196
197 /**
198  * Global used to count how many connections we have currently
199  * been notified about (how many times has topology_callback been called
200  * with success?)
201  */
202 static unsigned int total_connections;
203
204 /**
205  * Global used to count how many failed connections we have
206  * been notified about (how many times has topology_callback
207  * been called with failure?)
208  */
209 static unsigned int failed_connections;
210
211 static enum GNUNET_DHT_RouteOption route_option;
212
213 /* Task handle to use to schedule test failure */
214 static GNUNET_SCHEDULER_TaskIdentifier die_task;
215
216 static char *blacklist_transports;
217
218 static enum GNUNET_TESTING_Topology topology;
219
220 static enum GNUNET_TESTING_Topology blacklist_topology = GNUNET_TESTING_TOPOLOGY_NONE;  /* Don't do any blacklisting */
221
222 static enum GNUNET_TESTING_Topology connection_topology = GNUNET_TESTING_TOPOLOGY_NONE; /* NONE actually means connect all allowed peers */
223
224 static enum GNUNET_TESTING_TopologyOption connect_topology_option =
225     GNUNET_TESTING_TOPOLOGY_OPTION_ALL;
226
227 static double connect_topology_option_modifier = 0.0;
228
229 /* Global return value (0 for success, anything else for failure) */
230 static int ok;
231
232 /**
233  * Check whether peers successfully shut down.
234  */
235 static void
236 shutdown_callback (void *cls, const char *emsg)
237 {
238   if (emsg != NULL)
239   {
240     if (ok == 0)
241       ok = 2;
242   }
243 }
244
245 /**
246  * Task to release DHT handles for PUT
247  */
248 static void
249 put_disconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
250 {
251   struct TestPutContext *test_put = cls;
252
253   test_put->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
254   GNUNET_DHT_disconnect (test_put->dht_handle);
255   test_put->dht_handle = NULL;
256 }
257
258 /**
259  * Function scheduled to be run on the successful completion of this
260  * testcase.
261  */
262 static void
263 finish_testing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
264 {
265   GNUNET_assert (pg != NULL);
266   struct TestPutContext *test_put = all_puts;
267   struct TestGetContext *test_get = all_gets;
268
269   while (test_put != NULL)
270   {
271     if (test_put->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
272       GNUNET_SCHEDULER_cancel (test_put->disconnect_task);
273     if (test_put->dht_handle != NULL)
274       GNUNET_DHT_disconnect (test_put->dht_handle);
275     test_put = test_put->next;
276   }
277
278   while (test_get != NULL)
279   {
280     if (test_get->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
281       GNUNET_SCHEDULER_cancel (test_get->disconnect_task);
282     if (test_get->get_handle != NULL)
283       GNUNET_DHT_get_stop (test_get->get_handle);
284     if (test_get->dht_handle != NULL)
285       GNUNET_DHT_disconnect (test_get->dht_handle);
286     test_get = test_get->next;
287   }
288
289   GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
290   ok = 0;
291 }
292
293
294 /**
295  * Check if the get_handle is being used, if so stop the request.  Either
296  * way, schedule the end_badly_cont function which actually shuts down the
297  * test.
298  */
299 static void
300 end_badly (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
301 {
302   const char *emsg = cls;
303
304   fprintf (stderr, 
305            "Failing test with error: `%s'!\n",
306            emsg);
307
308   struct TestPutContext *test_put = all_puts;
309   struct TestGetContext *test_get = all_gets;
310
311   while (test_put != NULL)
312   {
313     if (test_put->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
314       GNUNET_SCHEDULER_cancel (test_put->disconnect_task);
315     if (test_put->dht_handle != NULL)
316       GNUNET_DHT_disconnect (test_put->dht_handle);
317     test_put = test_put->next;
318   }
319
320   while (test_get != NULL)
321   {
322     if (test_get->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
323       GNUNET_SCHEDULER_cancel (test_get->disconnect_task);
324     if (test_get->get_handle != NULL)
325       GNUNET_DHT_get_stop (test_get->get_handle);
326     if (test_get->dht_handle != NULL)
327       GNUNET_DHT_disconnect (test_get->dht_handle);
328     test_get = test_get->next;
329   }
330
331   GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
332   ok = 1;
333 }
334
335
336 /**
337  * Task to release get handle.
338  */
339 static void
340 get_stop_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
341 {
342   struct TestGetContext *test_get = cls;
343   GNUNET_HashCode search_key;   /* Key stored under */
344   char original_data[TEST_DATA_SIZE];   /* Made up data to store */
345
346   test_get->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
347   memset (original_data, test_get->uid, sizeof (original_data));
348   GNUNET_CRYPTO_hash (original_data, TEST_DATA_SIZE, &search_key);
349
350   if (test_get->succeeded != GNUNET_YES)
351   {
352     gets_failed++;
353     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
354                 "Get from peer %s for key %s failed!\n",
355                 test_get->daemon->shortname, GNUNET_h2s (&search_key));
356   }
357   GNUNET_assert (test_get->get_handle != NULL);
358   GNUNET_DHT_get_stop (test_get->get_handle);
359   test_get->get_handle = NULL;
360
361   outstanding_gets--;           /* GET is really finished */
362   GNUNET_DHT_disconnect (test_get->dht_handle);
363   test_get->dht_handle = NULL;
364
365   fprintf (stderr,
366            "%llu gets succeeded, %llu gets failed!\n",
367            gets_completed, gets_failed);
368   if ((gets_completed + gets_failed == num_gets) && (outstanding_gets == 0))       /* Had some failures */
369   {
370       GNUNET_SCHEDULER_cancel (die_task);
371       die_task =
372         GNUNET_SCHEDULER_add_now (&end_badly, "not all gets succeeded");
373       return;
374   }
375
376   if ( (gets_completed == num_gets) && (outstanding_gets == 0) )  /* All gets successful */
377   {
378     GNUNET_SCHEDULER_cancel (die_task);
379     //GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5), &get_topology, NULL);
380     die_task = GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
381   }
382 }
383
384 /**
385  * Iterator called if the GET request initiated returns a response.
386  *
387  * @param cls closure
388  * @param exp when will this value expire
389  * @param key key of the result
390  * @param type type of the result
391  * @param size number of bytes in data
392  * @param data pointer to the result data
393  */
394 static void
395 get_result_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
396                      const GNUNET_HashCode * key,
397                      const struct GNUNET_PeerIdentity *get_path,
398                      unsigned int get_path_length,
399                      const struct GNUNET_PeerIdentity *put_path,
400                      unsigned int put_path_length,
401                      enum GNUNET_BLOCK_Type type, size_t size, const void *data)
402 {
403   struct TestGetContext *test_get = cls;
404   GNUNET_HashCode search_key;   /* Key stored under */
405   char original_data[TEST_DATA_SIZE];   /* Made up data to store */
406   unsigned int i;
407
408   memset (original_data, test_get->uid, sizeof (original_data));
409   GNUNET_CRYPTO_hash (original_data, TEST_DATA_SIZE, &search_key);
410
411   if (test_get->succeeded == GNUNET_YES)
412     return;                     /* Get has already been successful, probably ending now */
413
414 #if PATH_TRACKING
415   if (put_path != NULL)
416   {
417     fprintf (stderr, "PUT Path: ");
418     for (i = 0; i<put_path_length; i++)
419       fprintf (stderr, "%s%s", i == 0 ? "" : "->", GNUNET_i2s (&put_path[i]));
420     fprintf (stderr, "\n");
421   }
422   if (get_path != NULL)
423   {
424     fprintf (stderr, "GET Path: ");
425     for (i = 0; i < get_path_length; i++)
426       fprintf (stderr, "%s%s", i == 0 ? "" : "->", GNUNET_i2s (&get_path[i]));
427     fprintf (stderr, "\n");
428   }
429 #endif
430
431   if ((0 != memcmp (&search_key, key, sizeof (GNUNET_HashCode))) ||
432       (0 != memcmp (original_data, data, sizeof (original_data))))
433   {
434     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
435                 "Key or data is not the same as was inserted!\n");
436   }
437   else
438   {
439     fprintf (stderr, "GET successful!\n");
440     gets_completed++;
441     test_get->succeeded = GNUNET_YES;
442   }
443
444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received correct GET response!\n");
445   GNUNET_SCHEDULER_cancel (test_get->disconnect_task);
446   test_get->disconnect_task = GNUNET_SCHEDULER_add_now (&get_stop_task, test_get);
447 }
448
449
450 /**
451  * Set up some data, and call API PUT function
452  */
453 static void
454 do_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
455 {
456   struct TestGetContext *test_get = cls;
457   GNUNET_HashCode key;          /* Made up key to store data under */
458   char data[TEST_DATA_SIZE];    /* Made up data to store */
459
460   if (test_get == NULL)
461     return;                     /* End of the list */
462   memset (data, test_get->uid, sizeof (data));
463   GNUNET_CRYPTO_hash (data, TEST_DATA_SIZE, &key);
464
465   if (outstanding_gets > MAX_OUTSTANDING_GETS)
466   {
467     GNUNET_SCHEDULER_add_delayed (GET_DELAY, &do_get, test_get);
468     return;
469   }
470
471   test_get->dht_handle = GNUNET_DHT_connect (test_get->daemon->cfg, 10);
472   /* Insert the data at the first peer */
473   GNUNET_assert (test_get->dht_handle != NULL);
474   outstanding_gets++;
475   test_get->get_handle =
476       GNUNET_DHT_get_start (test_get->dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
477                             GNUNET_BLOCK_TYPE_TEST, &key,
478                             1, route_option, NULL, 0,
479                             &get_result_iterator, test_get);
480 #if VERBOSE
481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting get for uid %u from peer %s\n",
482               test_get->uid, test_get->daemon->shortname);
483 #endif
484   test_get->disconnect_task =
485       GNUNET_SCHEDULER_add_delayed (GET_TIMEOUT, &get_stop_task, test_get);
486   GNUNET_SCHEDULER_add_now (&do_get, test_get->next);
487 }
488
489 /**
490  * Called when the PUT request has been transmitted to the DHT service.
491  * Schedule the GET request for some time in the future.
492  */
493 static void
494 put_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
495 {
496   struct TestPutContext *test_put = cls;
497
498   outstanding_puts--;
499   puts_completed++;
500
501   GNUNET_SCHEDULER_cancel (test_put->disconnect_task);
502   test_put->disconnect_task =
503       GNUNET_SCHEDULER_add_now (&put_disconnect_task, test_put);
504   if (puts_completed == num_puts)
505   {
506     GNUNET_assert (outstanding_puts == 0);
507     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
508                                   (GNUNET_TIME_UNIT_SECONDS, 10), &do_get,
509                                   all_gets);
510     return;
511   }
512 }
513
514 /**
515  * Set up some data, and call API PUT function
516  */
517 static void
518 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
519 {
520   struct TestPutContext *test_put = cls;
521   GNUNET_HashCode key;          /* Made up key to store data under */
522   char data[TEST_DATA_SIZE];    /* Made up data to store */
523
524   if (test_put == NULL)
525     return;                     /* End of list */
526
527   memset (data, test_put->uid, sizeof (data));
528   GNUNET_CRYPTO_hash (data, TEST_DATA_SIZE, &key);
529
530   if (outstanding_puts > MAX_OUTSTANDING_PUTS)
531   {
532     GNUNET_SCHEDULER_add_delayed (PUT_DELAY, &do_put, test_put);
533     return;
534   }
535
536 #if VERBOSE
537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting put for uid %u from peer %s\n",
538               test_put->uid, test_put->daemon->shortname);
539 #endif
540   test_put->dht_handle = GNUNET_DHT_connect (test_put->daemon->cfg, 10);
541
542   GNUNET_assert (test_put->dht_handle != NULL);
543   outstanding_puts++;
544   GNUNET_DHT_put (test_put->dht_handle, &key, 1,
545                   route_option, GNUNET_BLOCK_TYPE_TEST, sizeof (data), data,
546                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
547                   &put_finished, test_put);
548   test_put->disconnect_task =
549     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
550                                   &put_disconnect_task, test_put);
551   GNUNET_SCHEDULER_add_now (&do_put, test_put->next);
552 }
553
554
555
556 /**
557  * This function is called whenever a connection attempt is finished between two of
558  * the started peers (started with GNUNET_TESTING_daemons_start).  The total
559  * number of times this function is called should equal the number returned
560  * from the GNUNET_TESTING_connect_topology call.
561  *
562  * The emsg variable is NULL on success (peers connected), and non-NULL on
563  * failure (peers failed to connect).
564  */
565 static void
566 topology_callback (void *cls, const struct GNUNET_PeerIdentity *first,
567                    const struct GNUNET_PeerIdentity *second, uint32_t distance,
568                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
569                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
570                    struct GNUNET_TESTING_Daemon *first_daemon,
571                    struct GNUNET_TESTING_Daemon *second_daemon,
572                    const char *emsg)
573 {
574   unsigned long long i;
575   uint32_t temp_daemon;
576   struct TestPutContext *test_put;
577   struct TestGetContext *test_get;
578   int remember[num_puts][num_peers];
579
580   if (emsg == NULL)
581   {
582     total_connections++;
583 #if VERBOSE > 1
584     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585                 "connected peer %s to peer %s, distance %u\n",
586                 first_daemon->shortname, second_daemon->shortname, distance);
587 #endif
588   }
589   else
590   {
591     failed_connections++;
592     fprintf (stderr,
593              "Failed to connect peer %s to peer %s with error :\n%s\n",
594              first_daemon->shortname, second_daemon->shortname, emsg);
595     GNUNET_SCHEDULER_cancel (die_task);
596     die_task =
597       GNUNET_SCHEDULER_add_now (&end_badly,
598                                 "from topology_callback (connections failed)");
599     return;
600   }
601   if (total_connections < expected_connections)
602     return;
603   fprintf (stderr,
604            "Created topology with %u connections\n",
605            total_connections);
606   GNUNET_SCHEDULER_cancel (die_task);
607   die_task =
608     GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
609                                   "from setup puts/gets");
610   fprintf (stderr, 
611            "Issuing %llu PUTs at random locations\n", 
612            num_puts);
613   for (i = 0; i < num_puts; i++)
614   {
615     test_put = GNUNET_malloc (sizeof (struct TestPutContext));
616     test_put->uid = i;
617     temp_daemon =
618         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
619     test_put->daemon = GNUNET_TESTING_daemon_get (pg, temp_daemon);
620     
621     test_put->next = all_puts;
622     all_puts = test_put;
623   }
624   GNUNET_SCHEDULER_add_now (&do_put, all_puts);
625
626   fprintf (stderr, 
627            "Issuing %llu GETs at random locations for random PUT data\n",
628            num_gets);
629   memset (remember, 0, sizeof (remember));
630   for (i = 0; i < num_gets; i++)
631   {
632     test_get = GNUNET_malloc (sizeof (struct TestGetContext));
633     test_get->uid =
634         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_puts);
635     temp_daemon =
636         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
637     while (remember[test_get->uid][temp_daemon] == 1)
638       temp_daemon =
639           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
640     test_get->daemon = GNUNET_TESTING_daemon_get (pg, temp_daemon);
641     remember[test_get->uid][temp_daemon] = 1;
642     test_get->next = all_gets;
643     all_gets = test_get;
644   }
645
646
647 }
648
649
650 static void
651 peers_started_callback (void *cls, const struct GNUNET_PeerIdentity *id,
652                         const struct GNUNET_CONFIGURATION_Handle *cfg,
653                         struct GNUNET_TESTING_Daemon *d, const char *emsg)
654 {
655   if (emsg != NULL)
656   {
657     fprintf (stderr,
658              "Failed to start daemon with error: `%s'\n", emsg);
659     return;
660   }
661   GNUNET_assert (id != NULL);
662
663 #if VERBOSE
664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Started daemon %llu out of %llu\n",
665               (num_peers - peers_left) + 1, num_peers);
666 #endif
667
668   peers_left--;
669   if (peers_left > 0)
670     return;
671
672 #if VERBOSE
673   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
674               "All %d daemons started, now connecting peers!\n", num_peers);
675 #endif
676   
677   expected_connections = -1;
678   if ((pg != NULL) && (peers_left == 0))
679     {
680       expected_connections =
681         GNUNET_TESTING_connect_topology (pg, connection_topology,
682                                          connect_topology_option,
683                                          connect_topology_option_modifier,
684                                          TIMEOUT, num_peers, NULL, NULL);
685 #if VERBOSE
686       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Have %d expected connections\n",
687                   expected_connections);
688 #endif
689     }
690   
691   GNUNET_SCHEDULER_cancel (die_task);
692   if (expected_connections == GNUNET_SYSERR)
693     {
694       die_task =
695         GNUNET_SCHEDULER_add_now (&end_badly,
696                                   "from connect topology (bad return)");
697     }
698   else
699     {
700       die_task =
701         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
702                                       "from connect topology (timeout)");
703     }
704   ok = 0;
705 }
706
707
708 /**
709  * Callback indicating that the hostkey was created for a peer.
710  *
711  * @param cls NULL
712  * @param id the peer identity
713  * @param d the daemon handle (pretty useless at this point, remove?)
714  * @param emsg non-null on failure
715  */
716 static void
717 hostkey_callback (void *cls, const struct GNUNET_PeerIdentity *id,
718                   struct GNUNET_TESTING_Daemon *d, const char *emsg)
719 {
720   if (emsg != NULL)
721   {
722     fprintf (stderr,
723              "Hostkey callback received error: %s\n", emsg);
724     return;
725   }
726
727 #if VERBOSE > 1
728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
729               "Hostkey (%d/%d) created for peer `%s'\n", num_peers - peers_left,
730               num_peers, GNUNET_i2s (id));
731 #endif
732
733
734   peers_left--;
735   if (peers_left == 0)
736   {
737 #if VERBOSE
738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
739                 "All %d hostkeys created, now creating topology!\n", num_peers);
740 #endif
741     GNUNET_SCHEDULER_cancel (die_task);
742     /* Set up task in case topology creation doesn't finish
743      * within a reasonable amount of time */
744     ok = 0;
745     die_task =
746         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
747                                       "from create_topology");
748     peers_left = num_peers;       /* Reset counter */
749     GNUNET_SCHEDULER_cancel (die_task);
750     if (GNUNET_TESTING_create_topology
751         (pg, topology, blacklist_topology, blacklist_transports) != GNUNET_SYSERR)
752       {
753 #if VERBOSE
754         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755                     "Topology set up, now starting peers!\n");
756 #endif
757         GNUNET_TESTING_daemons_continue_startup (pg);
758         die_task =
759           GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
760                                         "from continue startup (timeout)");
761       }
762     else
763       {
764         die_task =
765           GNUNET_SCHEDULER_add_now (&end_badly,
766                                     "from create topology (bad return)");
767       }
768   }
769 }
770
771
772 static void
773 run (void *cls, char *const *args, const char *cfgfile,
774      const struct GNUNET_CONFIGURATION_Handle *cfg)
775 {
776   char *topology_str;
777   char *connect_topology_str;
778   char *blacklist_topology_str;
779   char *connect_topology_option_str;
780   char *connect_topology_option_modifier_string;
781
782 #if PATH_TRACKING
783   route_option = GNUNET_DHT_RO_RECORD_ROUTE;
784 #else
785   route_option = GNUNET_DHT_RO_NONE;
786 #endif
787
788   /* Get path from configuration file */
789   if (GNUNET_YES !=
790       GNUNET_CONFIGURATION_get_value_string (cfg, "paths", "servicehome",
791                                              &test_directory))
792   {
793     GNUNET_break (0);
794     ok = 404;
795     return;
796   }
797
798   if ((GNUNET_YES ==
799        GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "topology",
800                                               &topology_str)) &&
801       (GNUNET_NO == GNUNET_TESTING_topology_get (&topology, topology_str)))
802   {
803     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
804                 "Invalid topology `%s' given for section %s option %s\n",
805                 topology_str, "TESTING", "TOPOLOGY");
806     topology = GNUNET_TESTING_TOPOLOGY_CLIQUE;  /* Defaults to NONE, so set better default here */
807   }
808
809   if ((GNUNET_YES ==
810        GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
811                                               "connect_topology",
812                                               &connect_topology_str)) &&
813       (GNUNET_NO ==
814        GNUNET_TESTING_topology_get (&connection_topology,
815                                     connect_topology_str)))
816   {
817     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
818                 "Invalid connect topology `%s' given for section %s option %s\n",
819                 connect_topology_str, "TESTING", "CONNECT_TOPOLOGY");
820   }
821   GNUNET_free_non_null (connect_topology_str);
822   if ((GNUNET_YES ==
823        GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
824                                               "connect_topology_option",
825                                               &connect_topology_option_str)) &&
826       (GNUNET_NO ==
827        GNUNET_TESTING_topology_option_get (&connect_topology_option,
828                                            connect_topology_option_str)))
829   {
830     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
831                 "Invalid connect topology option `%s' given for section %s option %s\n",
832                 connect_topology_option_str, "TESTING",
833                 "CONNECT_TOPOLOGY_OPTION");
834     connect_topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_ALL;       /* Defaults to NONE, set to ALL */
835   }
836   GNUNET_free_non_null (connect_topology_option_str);
837   if (GNUNET_YES ==
838       GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
839                                              "connect_topology_option_modifier",
840                                              &connect_topology_option_modifier_string))
841   {
842     if (sscanf
843         (connect_topology_option_modifier_string, "%lf",
844          &connect_topology_option_modifier) != 1)
845     {
846       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
847                   _
848                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
849                   connect_topology_option_modifier_string,
850                   "connect_topology_option_modifier", "TESTING");
851     }
852     GNUNET_free (connect_topology_option_modifier_string);
853   }
854
855   if (GNUNET_YES !=
856       GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
857                                              "blacklist_transports",
858                                              &blacklist_transports))
859     blacklist_transports = NULL;
860
861   if ((GNUNET_YES ==
862        GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
863                                               "blacklist_topology",
864                                               &blacklist_topology_str)) &&
865       (GNUNET_NO ==
866        GNUNET_TESTING_topology_get (&blacklist_topology,
867                                     blacklist_topology_str)))
868   {
869     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
870                 "Invalid topology `%s' given for section %s option %s\n",
871                 topology_str, "TESTING", "BLACKLIST_TOPOLOGY");
872   }
873   GNUNET_free_non_null (topology_str);
874   GNUNET_free_non_null (blacklist_topology_str);
875
876   /* Get number of peers to start from configuration */
877   if (GNUNET_SYSERR ==
878       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
879                                              &num_peers))
880     num_peers = DEFAULT_NUM_PEERS;
881
882   if (GNUNET_SYSERR ==
883       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_puts",
884                                              &num_puts))
885     num_puts = DEFAULT_NUM_PEERS;
886
887   if (GNUNET_SYSERR ==
888       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_gets",
889                                              &num_gets))
890     num_gets = DEFAULT_NUM_PEERS;
891
892   /* Set peers_left so we know when all peers started */
893   peers_left = num_peers;
894
895   /* Set up a task to end testing if peer start fails */
896   die_task =
897       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
898                                     (GNUNET_TIME_UNIT_SECONDS,
899                                      SECONDS_PER_PEER_START * num_peers),
900                                     &end_badly,
901                                     "didn't generate all hostkeys within a reasonable amount of time!!!");
902   fprintf (stderr, 
903            "Starting P2P network with %llu peers\n",
904            peers_left);
905   pg = GNUNET_TESTING_daemons_start (cfg, peers_left,   /* Total number of peers */
906                                      peers_left,        /* Number of outstanding connections */
907                                      peers_left,        /* Number of parallel ssh connections, or peers being started at once */
908                                      GNUNET_TIME_relative_multiply
909                                      (GNUNET_TIME_UNIT_SECONDS,
910                                       SECONDS_PER_PEER_START * num_peers),
911                                      &hostkey_callback, NULL,
912                                      &peers_started_callback, NULL,
913                                      &topology_callback, NULL, NULL);
914
915 }
916
917
918 static int
919 check ()
920 {
921   int ret;
922
923   /* Arguments for GNUNET_PROGRAM_run */
924   char *const argv[] = { "test-dht-multipeer",  /* Name to give running binary */
925     "-c",
926     "test_dht_multipeer_data.conf",     /* Config file to use */
927 #if VERBOSE
928     "-L", "DEBUG",
929 #endif
930     NULL
931   };
932   struct GNUNET_GETOPT_CommandLineOption options[] = {
933     GNUNET_GETOPT_OPTION_END
934   };
935   /* Run the run function as a new program */
936   ret =
937       GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, argv,
938                           "test-dht-multipeer", "nohelp", options, &run, &ok);
939   if (ret != GNUNET_OK)
940   {
941     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
942                 "`test-dht-multipeer': Failed with error code %d\n", ret);
943   }
944   return ok;
945 }
946
947 int
948 main (int argc, char *argv[])
949 {
950   int ret;
951
952   GNUNET_log_setup ("test-dht-multipeer",
953 #if VERBOSE
954                     "DEBUG",
955 #else
956                     "WARNING",
957 #endif
958                     NULL);
959   ret = check ();
960   /**
961    * Need to remove base directory, subdirectories taken care
962    * of by the testing framework.
963    */
964   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
965   {
966     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
967                 "Failed to remove testing directory %s\n", test_directory);
968   }
969   return ret;
970 }
971
972 /* end of test_dht_multipeer.c */