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