topology option support for GNUNET_TESTBED_run() via configuration
[oweals/gnunet.git] / src / testbed / gnunet-helper-testbed.c
1 /*
2       This file is part of GNUnet
3       (C) 2012 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 /**
22  * @file testbed/gnunet-helper-testbed.c
23  * @brief Helper binary that is started from a remote controller to start
24  *          gnunet-service-testbed. This binary also receives configuration
25  *          from the remove controller which is put in a temporary location
26  *          with ports and paths fixed so that gnunet-service-testbed runs
27  *          without any hurdles. This binary also kills the testbed service
28  *          should the connection from the remote controller is dropped
29  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
30  */
31
32
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_testing_lib-new.h"
36 #include "gnunet_testbed_service.h"
37 #include "testbed_helper.h"
38 #include "testbed_api.h"
39 #include <zlib.h>
40
41 /**
42  * Generic logging shortcut
43  */
44 #define LOG(kind, ...)                                   \
45   GNUNET_log (kind, __VA_ARGS__)
46
47 /**
48  * Debug logging shorthand
49  */
50 #define LOG_DEBUG(...)                          \
51   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
52
53
54 /**
55  * Context for a single write on a chunk of memory
56  */
57 struct WriteContext
58 {
59   /**
60    * The data to write
61    */
62   void *data;
63
64   /**
65    * The length of the data
66    */
67   size_t length;
68
69   /**
70    * The current position from where the write operation should begin
71    */
72   size_t pos;
73 };
74
75
76 /**
77  * Handle to the testing system
78  */
79 static struct GNUNET_TESTING_System *test_system;
80
81 /**
82  * Our message stream tokenizer
83  */
84 struct GNUNET_SERVER_MessageStreamTokenizer *tokenizer;
85
86 /**
87  * Disk handle from stdin
88  */
89 static struct GNUNET_DISK_FileHandle *stdin_fd;
90
91 /**
92  * Disk handle for stdout
93  */
94 static struct GNUNET_DISK_FileHandle *stdout_fd;
95
96 /**
97  * The process handle to the testbed service
98  */
99 static struct GNUNET_OS_Process *testbed;
100
101 /**
102  * Task identifier for the read task
103  */
104 static GNUNET_SCHEDULER_TaskIdentifier read_task_id;
105
106 /**
107  * Task identifier for the write task
108  */
109 static GNUNET_SCHEDULER_TaskIdentifier write_task_id;
110
111 /**
112  * Are we done reading messages from stdin?
113  */
114 static int done_reading;
115
116 /**
117  * Result to return in case we fail
118  */
119 static int status;
120
121
122 /**
123  * Are we shutting down
124  */
125 static int in_shutdown;
126
127
128 /**
129  * Task to shutting down nicely
130  *
131  * @param cls NULL
132  * @param tc the task context
133  */
134 static void
135 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
136 {
137   LOG_DEBUG ("Shutting down\n");
138   in_shutdown = GNUNET_YES;
139   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
140   {
141     GNUNET_SCHEDULER_cancel (read_task_id);
142     read_task_id = GNUNET_SCHEDULER_NO_TASK;
143   }
144   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
145   {
146     GNUNET_SCHEDULER_cancel (write_task_id);
147     write_task_id = GNUNET_SCHEDULER_NO_TASK;
148   }
149   if (NULL != stdin_fd)
150     (void) GNUNET_DISK_file_close (stdin_fd);
151   if (NULL != stdout_fd)
152     (void) GNUNET_DISK_file_close (stdout_fd);
153   GNUNET_SERVER_mst_destroy (tokenizer);
154   tokenizer = NULL;
155   if (NULL != testbed)
156   {
157     LOG_DEBUG ("Killing testbed\n");
158     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, SIGTERM));
159     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
160     GNUNET_OS_process_destroy (testbed);
161     testbed = NULL;
162   }
163   if (NULL != test_system)
164   {
165     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
166     test_system = NULL;
167   }
168 }
169
170
171 /**
172  * Task to write to the standard out
173  *
174  * @param cls the WriteContext
175  * @param tc the TaskContext
176  */
177 static void
178 write_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
179 {
180   struct WriteContext *wc = cls;
181   ssize_t bytes_wrote;
182
183   GNUNET_assert (NULL != wc);
184   write_task_id = GNUNET_SCHEDULER_NO_TASK;
185   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
186   {
187     GNUNET_free (wc->data);
188     GNUNET_free (wc);
189     return;
190   }
191   bytes_wrote =
192       GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
193                               wc->length - wc->pos);
194   if (GNUNET_SYSERR == bytes_wrote)
195   {
196     LOG (GNUNET_ERROR_TYPE_WARNING, "Cannot reply back configuration\n");
197     GNUNET_free (wc->data);
198     GNUNET_free (wc);
199     return;
200   }
201   wc->pos += bytes_wrote;
202   if (wc->pos == wc->length)
203   {
204     GNUNET_free (wc->data);
205     GNUNET_free (wc);
206     return;
207   }
208   write_task_id =
209       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
210                                        &write_task, wc);
211 }
212
213
214 /**
215  * Functions with this signature are called whenever a
216  * complete message is received by the tokenizer.
217  *
218  * Do not call GNUNET_SERVER_mst_destroy in callback
219  *
220  * @param cls closure
221  * @param client identification of the client
222  * @param message the actual message
223  *
224  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
225  */
226 static int
227 tokenizer_cb (void *cls, void *client,
228               const struct GNUNET_MessageHeader *message)
229 {
230   const struct GNUNET_TESTBED_HelperInit *msg;
231   struct GNUNET_TESTBED_HelperReply *reply;
232   struct GNUNET_CONFIGURATION_Handle *cfg;
233   struct WriteContext *wc;
234   char *binary;
235   char *controller;
236   char *hostname;
237   char *config;
238   char *xconfig;
239   size_t config_size;
240   uLongf ul_config_size;
241   size_t xconfig_size;
242   uint16_t cname_size;
243   uint16_t hostname_size;
244   uint16_t msize;
245   
246   msize = ntohs (message->size);
247   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
248       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
249   {
250     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
251     goto error;
252   }
253   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
254   cname_size = ntohs (msg->cname_size);
255   controller = (char *) &msg[1];
256   if ('\0' != controller[cname_size])
257   {
258     LOG (GNUNET_ERROR_TYPE_WARNING,
259          "Controller name cannot be empty -- exiting\n");
260     goto error;
261   }
262   hostname_size = ntohs (msg->hostname_size);
263   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + cname_size + 1 +
264        hostname_size) >= msize)
265   {
266     GNUNET_break (0);
267     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
268     goto error;
269   }  
270   ul_config_size = (uLongf) ntohs (msg->config_size);
271   config = GNUNET_malloc (ul_config_size);
272   xconfig_size =
273       ntohs (message->size) - (cname_size + 1 +
274                                sizeof (struct GNUNET_TESTBED_HelperInit));
275   if (Z_OK !=
276       uncompress ((Bytef *) config, &ul_config_size,
277                   (const Bytef *) (controller + cname_size + 1 + hostname_size),
278                   (uLongf) xconfig_size))
279   {
280     LOG (GNUNET_ERROR_TYPE_WARNING,
281          "Error while uncompressing config -- exiting\n");
282     GNUNET_free (config);
283     goto error;
284   }
285   cfg = GNUNET_CONFIGURATION_create ();
286   if (GNUNET_OK !=
287       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
288   {
289     LOG (GNUNET_ERROR_TYPE_WARNING,
290          "Unable to deserialize config -- exiting\n");
291     GNUNET_free (config);
292     goto error;
293   }
294   GNUNET_free (config);
295   hostname = NULL;
296   if (0 != hostname_size)
297   {
298     hostname = GNUNET_malloc (hostname_size + 1);
299     (void) strncpy (hostname, ((char *) &msg[1]) + cname_size + 1, hostname_size);
300     hostname[hostname_size] = '\0';
301   }
302   test_system = GNUNET_TESTING_system_create ("testbed-helper", controller,
303                                               hostname);
304   GNUNET_free_non_null (hostname);
305   hostname = NULL;
306   GNUNET_assert (NULL != test_system);
307   GNUNET_assert (GNUNET_OK ==
308                  GNUNET_TESTING_configuration_create (test_system, cfg));
309   GNUNET_assert (GNUNET_OK ==
310                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
311                                                         "DEFAULTCONFIG",
312                                                         &config));
313   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
314   {
315     LOG (GNUNET_ERROR_TYPE_WARNING,
316          "Unable to write config file: %s -- exiting\n", config);
317     GNUNET_CONFIGURATION_destroy (cfg);
318     GNUNET_free (config);
319     goto error;
320   }
321   LOG_DEBUG ("Staring testbed with config: %s\n", config);
322   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
323   testbed =
324       GNUNET_OS_start_process (GNUNET_YES,
325                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ , NULL,
326                                NULL, 
327                                binary,
328                                "gnunet-service-testbed", "-c", config, NULL);
329   GNUNET_free (binary);
330   GNUNET_free (config);
331   if (NULL == testbed)
332   {
333     LOG (GNUNET_ERROR_TYPE_WARNING,
334          "Error staring gnunet-service-testbed -- exiting\n");
335     GNUNET_CONFIGURATION_destroy (cfg);
336     goto error;
337   }
338   done_reading = GNUNET_YES;
339   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
340   GNUNET_CONFIGURATION_destroy (cfg);
341   cfg = NULL;
342   xconfig_size =
343       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
344   GNUNET_free (config);
345   wc = GNUNET_malloc (sizeof (struct WriteContext));
346   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
347   reply = GNUNET_realloc (xconfig, wc->length);
348   memmove (&reply[1], reply, xconfig_size);
349   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
350   reply->header.size = htons ((uint16_t) wc->length);
351   reply->config_size = htons ((uint16_t) config_size);
352   wc->data = reply;
353   write_task_id =
354       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
355                                        &write_task, wc);
356   return GNUNET_OK;
357
358 error:
359   status = GNUNET_SYSERR;
360   GNUNET_SCHEDULER_shutdown ();
361   return GNUNET_SYSERR;
362 }
363
364
365 /**
366  * Task to read from stdin
367  *
368  * @param cls NULL
369  * @param tc the task context
370  */
371 static void
372 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
373 {
374   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
375   ssize_t sread;
376
377   read_task_id = GNUNET_SCHEDULER_NO_TASK;
378   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
379     return;
380   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
381   if ((GNUNET_SYSERR == sread) || (0 == sread))
382   {
383     GNUNET_SCHEDULER_shutdown ();
384     return;
385   }
386   if (GNUNET_YES == done_reading)
387   {
388     /* didn't expect any more data! */
389     GNUNET_SCHEDULER_shutdown ();
390     return;
391   }
392   LOG_DEBUG ("Read %u bytes\n", sread);
393   if (GNUNET_OK !=
394       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
395                                  GNUNET_NO))
396   {
397     GNUNET_break (0);
398     GNUNET_SCHEDULER_shutdown ();
399     return;
400   }
401   read_task_id =                /* No timeout while reading */
402       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
403                                       &read_task, NULL);
404 }
405
406
407 /**
408  * Main function that will be run.
409  *
410  * @param cls closure
411  * @param args remaining command-line arguments
412  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
413  * @param cfg configuration
414  */
415 static void
416 run (void *cls, char *const *args, const char *cfgfile,
417      const struct GNUNET_CONFIGURATION_Handle *cfg)
418 {
419   LOG_DEBUG ("Starting testbed helper...\n");
420   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
421   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
422   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
423   read_task_id =
424       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
425                                       &read_task, NULL);
426   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
427                                 NULL);
428 }
429
430
431 /**
432  * Signal handler called for SIGCHLD.
433  */
434 static void
435 sighandler_child_death ()
436 {
437   if ((NULL != testbed) && (GNUNET_NO == in_shutdown))
438   {
439     LOG_DEBUG ("Child died\n");
440     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (testbed));
441     GNUNET_OS_process_destroy (testbed);
442     testbed = NULL;
443     GNUNET_SCHEDULER_shutdown ();       /* We are done too! */
444   }
445 }
446
447
448 /**
449  * Main function
450  *
451  * @param argc the number of command line arguments
452  * @param argv command line arg array
453  * @return return code
454  */
455 int
456 main (int argc, char **argv)
457 {
458   struct GNUNET_SIGNAL_Context *shc_chld;
459
460   struct GNUNET_GETOPT_CommandLineOption options[] = {
461     GNUNET_GETOPT_OPTION_END
462   };
463   int ret;
464
465   status = GNUNET_OK;
466   in_shutdown = GNUNET_NO;
467   shc_chld =
468       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
469   ret =
470       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
471                           "Helper for starting gnunet-service-testbed", options,
472                           &run, NULL);
473   GNUNET_SIGNAL_handler_uninstall (shc_chld);
474   shc_chld = NULL;
475   if (GNUNET_OK != ret)
476     return 1;
477   return (GNUNET_OK == status) ? 0 : 1;
478 }
479
480 /* end of gnunet-helper-testbed.c */