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