-fix
[oweals/gnunet.git] / src / dht / test_dht_twopeer_path_tracking.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_twopeer_path_tracking.c
22  * @brief testcase for testing DHT service with
23  *        two running peers, logging the path of the dht requests.
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, 30)
38
39 /* If number of peers not in config file, use this number */
40 #define DEFAULT_NUM_PEERS 2
41
42 /* Globals */
43
44 /**
45  * Directory to store temp data in, defined in config file
46  */
47 static char *test_directory;
48
49 /**
50  * Variable used to store the number of connections we should wait for.
51  */
52 static unsigned int expected_connections;
53
54 /**
55  * Variable used to keep track of how many peers aren't yet started.
56  */
57 static unsigned long long peers_left;
58
59 /**
60  * Handle to the set of all peers run for this test.
61  */
62 static struct GNUNET_TESTING_PeerGroup *pg;
63
64 /**
65  * Global handle we will use for GET requests.
66  */
67 struct GNUNET_DHT_GetHandle *global_get_handle;
68
69
70 /**
71  * Total number of peers to run, set based on config file.
72  */
73 static unsigned long long num_peers;
74
75 /**
76  * Global used to count how many connections we have currently
77  * been notified about (how many times has topology_callback been called
78  * with success?)
79  */
80 static unsigned int total_connections;
81
82 /**
83  * Global used to count how many failed connections we have
84  * been notified about (how many times has topology_callback
85  * been called with failure?)
86  */
87 static unsigned int failed_connections;
88
89 /**
90  * Task handle to use to schedule test failure
91  */
92 GNUNET_SCHEDULER_TaskIdentifier die_task;
93
94 /**
95  * Global return value (0 for success, anything else for failure)
96  */
97 static int ok;
98
99 /**
100  * Peer identity of the first peer started.
101  */
102 static struct GNUNET_PeerIdentity peer1id;
103
104 /**
105  * Peer identity of the second peer started.
106  */
107 static struct GNUNET_PeerIdentity peer2id;
108
109 /**
110  * Handle to the first peers DHT service (via the API)
111  */
112 static struct GNUNET_DHT_Handle *peer1dht;
113
114 /**
115  * Handle to the second peers DHT service (via the API)
116  */
117 static struct GNUNET_DHT_Handle *peer2dht;
118
119 /**
120  * Check whether peers successfully shut down.
121  */
122 void
123 shutdown_callback (void *cls, const char *emsg)
124 {
125   if (emsg != NULL)
126   {
127     if (ok == 0)
128       ok = 2;
129   }
130 }
131
132 /**
133  * Function scheduled to be run on the successful completion of this
134  * testcase.  Specifically, called when our get request completes.
135  */
136 static void
137 finish_testing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
138 {
139   GNUNET_assert (pg != NULL);
140   GNUNET_assert (peer1dht != NULL);
141   GNUNET_assert (peer2dht != NULL);
142   GNUNET_DHT_disconnect (peer1dht);
143   GNUNET_DHT_disconnect (peer2dht);
144   GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
145   ok = 0;
146 }
147
148 /**
149  * Continuation for the GNUNET_DHT_get_stop call, so that we don't shut
150  * down the peers without freeing memory associated with GET request.
151  */
152 static void
153 end_badly_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
154 {
155   if (peer1dht != NULL)
156     GNUNET_DHT_disconnect (peer1dht);
157
158   if (peer2dht != NULL)
159     GNUNET_DHT_disconnect (peer2dht);
160
161   if (pg != NULL)
162     GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
163 }
164
165 /**
166  * Check if the get_handle is being used, if so stop the request.  Either
167  * way, schedule the end_badly_cont function which actually shuts down the
168  * test.
169  */
170 static void
171 end_badly (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
172 {
173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failing test with error: `%s'!\n",
174               (char *) cls);
175   if (global_get_handle != NULL)
176   {
177     GNUNET_DHT_get_stop (global_get_handle);
178     global_get_handle = NULL;
179   }
180   GNUNET_SCHEDULER_add_now (&end_badly_cont, NULL);
181   ok = 1;
182 }
183
184 /**
185  * Iterator called if the GET request initiated returns a response.
186  *
187  * @param cls closure
188  * @param exp when will this value expire
189  * @param key key of the result
190  * @param type type of the result
191  * @param size number of bytes in data
192  * @param data pointer to the result data
193  */
194 static void
195 get_result_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
196                      const GNUNET_HashCode * key,
197                      const struct GNUNET_PeerIdentity *get_path,
198                      unsigned int get_path_length,
199                      const struct GNUNET_PeerIdentity *put_path,
200                      unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
201                      size_t size, const void *data)
202 {
203   GNUNET_HashCode original_key; /* Key data was stored data under */
204   char original_data[4];        /* Made up data that was stored */
205
206   memset (&original_key, 42, sizeof (GNUNET_HashCode)); /* Set the key to what it was set to previously */
207   memset (original_data, 43, sizeof (original_data));
208 #if VERBOSE
209   unsigned int i;
210 #endif
211
212   if ((0 != memcmp (&original_key, key, sizeof (GNUNET_HashCode))) ||
213       (0 != memcmp (original_data, data, sizeof (original_data))))
214   {
215     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
216                 "Key or data is not the same as was inserted!\n");
217     GNUNET_SCHEDULER_cancel (die_task);
218     GNUNET_SCHEDULER_add_now (&end_badly,
219                               "key or data mismatch in get response!\n");
220     return;
221   }
222
223 #if VERBOSE
224   if (put_path != NULL)
225   {
226     FPRINTF (stderr, "%s",  "PUT Path: ");
227     for (i = 0; i < put_path_length; i++)
228       FPRINTF (stderr, "%s%s", i == 0 ? "" : "->", GNUNET_i2s (&put_path[i]));
229     FPRINTF (stderr, "%s",  "\n");
230   }
231   if (get_path != NULL)
232   {
233     FPRINTF (stderr, "%s",  "GET Path: ");
234     for (i = 0; i < get_path_length; i++)
235       FPRINTF (stderr, "%s%s", i == 0 ? "" : "->", GNUNET_i2s (&get_path[i]));
236     FPRINTF (stderr, "%s",  "\n");
237   }
238 #endif
239
240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received correct GET response!\n");
241   GNUNET_SCHEDULER_cancel (die_task);
242   GNUNET_DHT_get_stop (global_get_handle);
243   GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
244 }
245
246
247 /**
248  * Called when the PUT request has been transmitted to the DHT service.
249  * Schedule the GET request for some time in the future.
250  */
251 static void
252 put_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
253 {
254   GNUNET_HashCode key;          /* Key for data lookup */
255
256   GNUNET_SCHEDULER_cancel (die_task);
257   die_task =
258       GNUNET_SCHEDULER_add_delayed (GET_TIMEOUT, &end_badly,
259                                     "waiting for get response (data not found)");
260   memset (&key, 42, sizeof (GNUNET_HashCode));  /* Set the key to the same thing as when data was inserted */
261   global_get_handle =
262       GNUNET_DHT_get_start (peer2dht, GNUNET_TIME_relative_get_forever (),
263                             GNUNET_BLOCK_TYPE_TEST, &key, 1,
264                             GNUNET_DHT_RO_RECORD_ROUTE, NULL, 0,
265                             &get_result_iterator, NULL);
266 }
267
268 /**
269  * Set up some data, and call API PUT function
270  */
271 static void
272 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
273 {
274   GNUNET_HashCode key;          /* Made up key to store data under */
275   char data[4];                 /* Made up data to store */
276
277   memset (&key, 42, sizeof (GNUNET_HashCode));  /* Set the key to something simple so we can issue GET request */
278   memset (data, 43, sizeof (data));
279
280   /* Insert the data at the first peer */
281   GNUNET_DHT_put (peer1dht, &key, 1, GNUNET_DHT_RO_RECORD_ROUTE,
282                   GNUNET_BLOCK_TYPE_TEST, sizeof (data), data,
283                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
284                   &put_finished, NULL);
285 }
286
287 /**
288  * This function is called whenever a connection attempt is finished between two of
289  * the started peers (started with GNUNET_TESTING_daemons_start).  The total
290  * number of times this function is called should equal the number returned
291  * from the GNUNET_TESTING_connect_topology call.
292  *
293  * The emsg variable is NULL on success (peers connected), and non-NULL on
294  * failure (peers failed to connect).
295  */
296 static void
297 topology_callback (void *cls, const struct GNUNET_PeerIdentity *first,
298                    const struct GNUNET_PeerIdentity *second, uint32_t distance,
299                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
300                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
301                    struct GNUNET_TESTING_Daemon *first_daemon,
302                    struct GNUNET_TESTING_Daemon *second_daemon,
303                    const char *emsg)
304 {
305   if (emsg == NULL)
306   {
307     total_connections++;
308 #if VERBOSE
309     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
310                 "connected peer %s to peer %s, distance %u\n",
311                 first_daemon->shortname, second_daemon->shortname, distance);
312 #endif
313   }
314 #if VERBOSE
315   else
316   {
317     failed_connections++;
318     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
319                 "Failed to connect peer %s to peer %s with error :\n%s\n",
320                 first_daemon->shortname, second_daemon->shortname, emsg);
321   }
322 #endif
323
324   if (total_connections == expected_connections)
325   {
326 #if VERBOSE
327     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
328                 "Created %d total connections, which is our target number!  Starting next phase of testing.\n",
329                 total_connections);
330 #endif
331     GNUNET_SCHEDULER_cancel (die_task);
332     die_task =
333         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly, "from test gets");
334
335     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
336                                   (GNUNET_TIME_UNIT_SECONDS, 2), &do_put, NULL);
337   }
338   else if (total_connections + failed_connections == expected_connections)
339   {
340     GNUNET_SCHEDULER_cancel (die_task);
341     die_task =
342         GNUNET_SCHEDULER_add_now (&end_badly,
343                                   "from topology_callback (too many failed connections)");
344   }
345 }
346
347
348 /**
349  * Callback which is called whenever a peer is started (as a result of the
350  * GNUNET_TESTING_daemons_start call.
351  *
352  * @param cls closure argument given to GNUNET_TESTING_daemons_start
353  * @param id the GNUNET_PeerIdentity of the started peer
354  * @param cfg the configuration for this specific peer (needed to connect
355  *            to the DHT)
356  * @param d the handle to the daemon started
357  * @param emsg NULL if peer started, non-NULL on error
358  */
359 static void
360 peers_started_callback (void *cls, const struct GNUNET_PeerIdentity *id,
361                         const struct GNUNET_CONFIGURATION_Handle *cfg,
362                         struct GNUNET_TESTING_Daemon *d, const char *emsg)
363 {
364   if (emsg != NULL)
365   {
366     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
367                 "Failed to start daemon with error: `%s'\n", emsg);
368     return;
369   }
370   GNUNET_assert (id != NULL);
371
372   /* This is the first peer started */
373   if (peers_left == num_peers)
374   {
375     memcpy (&peer1id, id, sizeof (struct GNUNET_PeerIdentity)); /* Save the peer id */
376     peer1dht = GNUNET_DHT_connect (cfg, 100);   /* Connect to the first peers DHT service */
377     if (peer1dht == NULL)       /* If DHT connect failed */
378     {
379       GNUNET_SCHEDULER_cancel (die_task);
380       GNUNET_SCHEDULER_add_now (&end_badly, "Failed to get dht handle!\n");
381     }
382   }
383   else                          /* This is the second peer started */
384   {
385     memcpy (&peer2id, id, sizeof (struct GNUNET_PeerIdentity)); /* Same as for first peer... */
386     peer2dht = GNUNET_DHT_connect (cfg, 100);
387     if (peer2dht == NULL)
388     {
389       GNUNET_SCHEDULER_cancel (die_task);
390       GNUNET_SCHEDULER_add_now (&end_badly, "Failed to get dht handle!\n");
391     }
392   }
393
394   /* Decrement number of peers left to start */
395   peers_left--;
396
397   if (peers_left == 0)          /* Indicates all peers started */
398   {
399 #if VERBOSE
400     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
401                 "All %d daemons started, now connecting peers!\n", num_peers);
402 #endif
403     expected_connections = -1;
404     if ((pg != NULL))           /* Sanity check */
405     {
406       /* Connect peers in a "straight line" topology, return the number of expected connections */
407       expected_connections =
408           GNUNET_TESTING_connect_topology (pg, GNUNET_TESTING_TOPOLOGY_LINE,
409                                            GNUNET_TESTING_TOPOLOGY_OPTION_ALL,
410                                            0.0, TIMEOUT, 2, NULL, NULL);
411     }
412
413     /* Cancel current timeout fail task */
414     GNUNET_SCHEDULER_cancel (die_task);
415     if (expected_connections == GNUNET_SYSERR)  /* Some error happened */
416       die_task =
417           GNUNET_SCHEDULER_add_now (&end_badly,
418                                     "from connect topology (bad return)");
419
420     /* Schedule timeout on failure task */
421     die_task =
422         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
423                                       "from connect topology (timeout)");
424     ok = 0;
425   }
426 }
427
428 static void
429 run (void *cls, char *const *args, const char *cfgfile,
430      const struct GNUNET_CONFIGURATION_Handle *cfg)
431 {
432
433   /* Get path from configuration file */
434   if (GNUNET_YES !=
435       GNUNET_CONFIGURATION_get_value_string (cfg, "paths", "servicehome",
436                                              &test_directory))
437   {
438     ok = 404;
439     return;
440   }
441
442   /* Get number of peers to start from configuration (should be two) */
443   if (GNUNET_SYSERR ==
444       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
445                                              &num_peers))
446     num_peers = DEFAULT_NUM_PEERS;
447
448   /* Set peers_left so we know when all peers started */
449   peers_left = num_peers;
450
451   /* Set up a task to end testing if peer start fails */
452   die_task =
453       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
454                                     "didn't start all daemons in reasonable amount of time!!!");
455
456   /* Start num_peers peers, call peers_started_callback on peer start, topology_callback on peer connect */
457   /* Read the API documentation for other parameters! */
458   pg = GNUNET_TESTING_daemons_start (cfg, peers_left,   /* Total number of peers */
459                                      peers_left,        /* Number of outstanding connections */
460                                      peers_left,        /* Number of parallel ssh connections, or peers being started at once */
461                                      TIMEOUT, NULL, NULL,
462                                      &peers_started_callback, NULL,
463                                      &topology_callback, NULL, NULL);
464
465 }
466
467 static int
468 check ()
469 {
470   int ret;
471
472   /* Arguments for GNUNET_PROGRAM_run */
473   char *const argv[] = { "test-dht-twopeer-put-get",    /* Name to give running binary */
474     "-c",
475     "test_dht_twopeer_data.conf",       /* Config file to use */
476 #if VERBOSE
477     "-L", "DEBUG",
478 #endif
479     NULL
480   };
481   struct GNUNET_GETOPT_CommandLineOption options[] = {
482     GNUNET_GETOPT_OPTION_END
483   };
484   /* Run the run function as a new program */
485   ret =
486       GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, argv,
487                           "test-dht-twopeer-put-get", "nohelp", options, &run,
488                           &ok);
489   if (ret != GNUNET_OK)
490   {
491     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
492                 "`test-dht-twopeer': Failed with error code %d\n", ret);
493   }
494   return ok;
495 }
496
497 int
498 main (int argc, char *argv[])
499 {
500   int ret;
501
502   GNUNET_log_setup ("test-dht-twopeer",
503 #if VERBOSE
504                     "DEBUG",
505 #else
506                     "WARNING",
507 #endif
508                     NULL);
509   ret = check ();
510   /**
511    * Need to remove base directory, subdirectories taken care
512    * of by the testing framework.
513    */
514   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
515   {
516     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
517                 "Failed to remove testing directory %s\n", test_directory);
518   }
519   return ret;
520 }
521
522 /* end of test_dht_twopeer_put_get.c */