big scheduler refactoring, expect some issues
[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                                            GNUNET_DHT_RO_NONE,
243                                            NULL, 0,
244                                            NULL, 0,
245                                            &get_result_iterator, NULL);
246 }
247
248 /**
249  * Called when the PUT request has been transmitted to the DHT service.
250  * Schedule the GET request for some time in the future.
251  */
252 static void
253 put_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
254 {
255   GNUNET_SCHEDULER_cancel (die_task);
256   die_task = GNUNET_SCHEDULER_add_delayed (GET_TIMEOUT,
257                                            &end_badly, "waiting for get response (data not found)");
258   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10), &do_get, NULL);
259 }
260
261 /**
262  * Set up some data, and call API PUT function
263  */
264 static void
265 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
266 {
267   GNUNET_HashCode key; /* Made up key to store data under */
268   char data[4]; /* Made up data to store */
269   memset(&key, 42, sizeof(GNUNET_HashCode)); /* Set the key to something simple so we can issue GET request */
270   memset(data, 43, sizeof(data));
271
272   /* Insert the data at the first peer */
273   GNUNET_DHT_put(peer1dht,
274                  &key,
275                  GNUNET_DHT_RO_NONE,
276                  GNUNET_BLOCK_TYPE_TEST,
277                  sizeof(data), data,
278                  GNUNET_TIME_UNIT_FOREVER_ABS,
279                  GNUNET_TIME_UNIT_FOREVER_REL,
280                  &put_finished, NULL);
281 }
282
283 /**
284  * This function is called whenever a connection attempt is finished between two of
285  * the started peers (started with GNUNET_TESTING_daemons_start).  The total
286  * number of times this function is called should equal the number returned
287  * from the GNUNET_TESTING_connect_topology call.
288  *
289  * The emsg variable is NULL on success (peers connected), and non-NULL on
290  * failure (peers failed to connect).
291  */
292 void
293 topology_callback (void *cls,
294                    const struct GNUNET_PeerIdentity *first,
295                    const struct GNUNET_PeerIdentity *second,
296                    uint32_t distance,
297                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
298                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
299                    struct GNUNET_TESTING_Daemon *first_daemon,
300                    struct GNUNET_TESTING_Daemon *second_daemon,
301                    const char *emsg)
302 {
303   if (emsg == NULL)
304     {
305       total_connections++;
306 #if VERBOSE
307       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connected peer %s to peer %s, distance %u\n",
308                  first_daemon->shortname,
309                  second_daemon->shortname,
310                  distance);
311 #endif
312     }
313 #if VERBOSE
314   else
315     {
316       failed_connections++;
317       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to connect peer %s to peer %s with error :\n%s\n",
318                   first_daemon->shortname,
319                   second_daemon->shortname, emsg);
320     }
321 #endif
322
323   if (total_connections == expected_connections)
324     {
325 #if VERBOSE
326       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
327                   "Created %d total connections, which is our target number!  Starting next phase of testing.\n",
328                   total_connections);
329 #endif
330       GNUNET_SCHEDULER_cancel (die_task);
331       die_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
332                                                &end_badly, "from test gets");
333
334       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 2), &do_put, NULL);
335     }
336   else if (total_connections + failed_connections == expected_connections)
337     {
338       GNUNET_SCHEDULER_cancel (die_task);
339       die_task = GNUNET_SCHEDULER_add_now (&end_badly, "from topology_callback (too many failed connections)");
340     }
341 }
342
343
344 /**
345  * Callback which is called whenever a peer is started (as a result of the
346  * GNUNET_TESTING_daemons_start call.
347  *
348  * @param cls closure argument given to GNUNET_TESTING_daemons_start
349  * @param id the GNUNET_PeerIdentity of the started peer
350  * @param cfg the configuration for this specific peer (needed to connect
351  *            to the DHT)
352  * @param d the handle to the daemon started
353  * @param emsg NULL if peer started, non-NULL on error
354  */
355 static void
356 peers_started_callback (void *cls,
357        const struct GNUNET_PeerIdentity *id,
358        const struct GNUNET_CONFIGURATION_Handle *cfg,
359        struct GNUNET_TESTING_Daemon *d, const char *emsg)
360 {
361   if (emsg != NULL)
362     {
363       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failed to start daemon with error: `%s'\n",
364                   emsg);
365       return;
366     }
367   GNUNET_assert (id != NULL);
368
369   /* This is the first peer started */
370   if (peers_left == num_peers)
371   {
372     memcpy(&peer1id, id, sizeof(struct GNUNET_PeerIdentity)); /* Save the peer id */
373     peer1dht = GNUNET_DHT_connect(cfg, 100); /* Connect to the first peers DHT service */
374     if (peer1dht == NULL) /* If DHT connect failed */
375     {
376       GNUNET_SCHEDULER_cancel (die_task);
377       GNUNET_SCHEDULER_add_now(&end_badly, "Failed to get dht handle!\n");
378     }
379   }
380   else /* This is the second peer started */
381   {
382     memcpy(&peer2id, id, sizeof(struct GNUNET_PeerIdentity)); /* Same as for first peer... */
383     peer2dht = GNUNET_DHT_connect(cfg, 100);
384     if (peer2dht == NULL)
385     {
386       GNUNET_SCHEDULER_cancel (die_task);
387       GNUNET_SCHEDULER_add_now(&end_badly, "Failed to get dht handle!\n");
388     }
389   }
390
391   /* Decrement number of peers left to start */
392   peers_left--;
393
394   if (peers_left == 0) /* Indicates all peers started */
395     {
396 #if VERBOSE
397       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
398                   "All %d daemons started, now connecting peers!\n",
399                   num_peers);
400 #endif
401       expected_connections = -1;
402       if ((pg != NULL)) /* Sanity check */
403         {
404           /* Connect peers in a "straight line" topology, return the number of expected connections */
405           expected_connections = GNUNET_TESTING_connect_topology (pg, GNUNET_TESTING_TOPOLOGY_LINE, GNUNET_TESTING_TOPOLOGY_OPTION_ALL, 0.0, NULL, NULL);
406         }
407
408       /* Cancel current timeout fail task */
409       GNUNET_SCHEDULER_cancel (die_task);
410       if (expected_connections == GNUNET_SYSERR) /* Some error happened */
411         die_task = GNUNET_SCHEDULER_add_now (&end_badly, "from connect topology (bad return)");
412
413       /* Schedule timeout on failure task */
414       die_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
415                                                &end_badly, "from connect topology (timeout)");
416       ok = 0;
417     }
418 }
419
420 static void
421 run (void *cls,
422      char *const *args,
423      const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg)
424 {
425
426   /* Get path from configuration file */
427   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_string(cfg, "paths", "servicehome", &test_directory))
428     {
429       ok = 404;
430       return;
431     }
432
433   /* Get number of peers to start from configuration (should be two) */
434   if (GNUNET_SYSERR ==
435       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
436                                              &num_peers))
437     num_peers = DEFAULT_NUM_PEERS;
438
439   /* Set peers_left so we know when all peers started */
440   peers_left = num_peers;
441
442   /* Set up a task to end testing if peer start fails */
443   die_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
444                                            &end_badly, "didn't start all daemons in reasonable amount of time!!!");
445
446   /* Start num_peers peers, call peers_started_callback on peer start, topology_callback on peer connect */
447   /* Read the API documentation for other parameters! */
448   pg = GNUNET_TESTING_daemons_start (cfg,
449                                      num_peers, TIMEOUT, NULL, NULL, &peers_started_callback, NULL,
450                                      &topology_callback, NULL, NULL);
451
452 }
453
454 static int
455 check ()
456 {
457   int ret;
458   /* Arguments for GNUNET_PROGRAM_run */
459   char *const argv[] = {"test-dht-twopeer-put-get", /* Name to give running binary */
460     "-c",
461     "test_dht_twopeer_data.conf", /* Config file to use */
462 #if VERBOSE
463     "-L", "DEBUG",
464 #endif
465     NULL
466   };
467   struct GNUNET_GETOPT_CommandLineOption options[] = {
468     GNUNET_GETOPT_OPTION_END
469   };
470   /* Run the run function as a new program */
471   ret = GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
472                       argv, "test-dht-twopeer-put-get", "nohelp",
473                       options, &run, &ok);
474   if (ret != GNUNET_OK)
475     {
476       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "`test-dht-twopeer': Failed with error code %d\n", ret);
477     }
478   return ok;
479 }
480
481 int
482 main (int argc, char *argv[])
483 {
484   int ret;
485
486   GNUNET_log_setup ("test-dht-twopeer",
487 #if VERBOSE
488                     "DEBUG",
489 #else
490                     "WARNING",
491 #endif
492                     NULL);
493   ret = check ();
494   /**
495    * Need to remove base directory, subdirectories taken care
496    * of by the testing framework.
497    */
498   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
499     {
500       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to remove testing directory %s\n", test_directory);
501     }
502   return ret;
503 }
504
505 /* end of test_dht_twopeer_put_get.c */