- distribute peers equally among island nodes on SuperMUC
[oweals/gnunet.git] / src / testbed / gnunet-helper-testbed.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2013 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.  
28  * 
29  *          This helper monitors for three termination events.  They are: (1)The
30  *          stdin of the helper is closed for reading; (2)the helper received
31  *          SIGTERM/SIGINT; (3)the testbed crashed.  In case of events 1 and 2
32  *          the helper kills the testbed service.  When testbed crashed (event
33  *          3), the helper should send a SIGTERM to its own process group; this
34  *          behaviour will help terminate any child processes (peers) testbed
35  *          has started and prevents them from leaking and running forever.
36  *
37  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
38  */
39
40
41 #include "platform.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet_testing_lib.h"
44 #include "gnunet_testbed_service.h"
45 #include "testbed_helper.h"
46 #include "testbed_api.h"
47 #include <zlib.h>
48
49 /**
50  * Generic logging shortcut
51  */
52 #define LOG(kind, ...)                                   \
53   GNUNET_log (kind, __VA_ARGS__)
54
55 /**
56  * Debug logging shorthand
57  */
58 #define LOG_DEBUG(...)                          \
59   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
60
61 /**
62  * Log an error message at log-level 'level' that indicates a failure of the
63  * command 'cmd' with the message given by gai_strerror(rc).
64  */
65 #define LOG_GAI(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gai_strerror(rc)); } while(0)
66
67
68 /**
69  * We need pipe control only on WINDOWS
70  */
71 #if WINDOWS
72 #define PIPE_CONTROL GNUNET_YES
73 #else
74 #define PIPE_CONTROL GNUNET_NO
75 #endif
76
77
78 /**
79  * Context for a single write on a chunk of memory
80  */
81 struct WriteContext
82 {
83   /**
84    * The data to write
85    */
86   void *data;
87
88   /**
89    * The length of the data
90    */
91   size_t length;
92
93   /**
94    * The current position from where the write operation should begin
95    */
96   size_t pos;
97 };
98
99
100 /**
101  * Handle to the testing system
102  */
103 static struct GNUNET_TESTING_System *test_system;
104
105 /**
106  * Our message stream tokenizer
107  */
108 struct GNUNET_SERVER_MessageStreamTokenizer *tokenizer;
109
110 /**
111  * Disk handle from stdin
112  */
113 static struct GNUNET_DISK_FileHandle *stdin_fd;
114
115 /**
116  * Disk handle for stdout
117  */
118 static struct GNUNET_DISK_FileHandle *stdout_fd;
119
120 /**
121  * The process handle to the testbed service
122  */
123 static struct GNUNET_OS_Process *testbed;
124
125 /**
126  * Pipe used to communicate shutdown via signal.
127  */
128 static struct GNUNET_DISK_PipeHandle *sigpipe;
129
130 /**
131  * Task identifier for the read task
132  */
133 static GNUNET_SCHEDULER_TaskIdentifier read_task_id;
134
135 /**
136  * Task identifier for the write task
137  */
138 static GNUNET_SCHEDULER_TaskIdentifier write_task_id;
139
140 /**
141  * Task to kill the child
142  */
143 static GNUNET_SCHEDULER_TaskIdentifier child_death_task_id;
144
145 /**
146  * shutdown task id
147  */
148 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task_id;
149
150 /**
151  * Are we done reading messages from stdin?
152  */
153 static int done_reading;
154
155 /**
156  * Result to return in case we fail
157  */
158 static int status;
159
160
161 /**
162  * Task to shut down cleanly
163  *
164  * @param cls NULL
165  * @param tc the task context
166  */
167 static void
168 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
169 {
170   LOG_DEBUG ("Shutting down\n");  
171   shutdown_task_id = GNUNET_SCHEDULER_NO_TASK;
172   if (NULL != testbed)
173   {
174     LOG_DEBUG ("Killing testbed\n");
175     GNUNET_break (0 == GNUNET_OS_process_kill (testbed, SIGTERM));
176   }  
177   if (GNUNET_SCHEDULER_NO_TASK != read_task_id)
178   {
179     GNUNET_SCHEDULER_cancel (read_task_id);
180     read_task_id = GNUNET_SCHEDULER_NO_TASK;
181   }
182   if (GNUNET_SCHEDULER_NO_TASK != write_task_id)
183   {
184     GNUNET_SCHEDULER_cancel (write_task_id);
185     write_task_id = GNUNET_SCHEDULER_NO_TASK;
186   }
187   if (GNUNET_SCHEDULER_NO_TASK != child_death_task_id)
188   {
189     GNUNET_SCHEDULER_cancel (child_death_task_id);
190     child_death_task_id = GNUNET_SCHEDULER_NO_TASK;
191   }
192   if (NULL != stdin_fd)
193     (void) GNUNET_DISK_file_close (stdin_fd);
194   if (NULL != stdout_fd)
195     (void) GNUNET_DISK_file_close (stdout_fd);
196   GNUNET_SERVER_mst_destroy (tokenizer);
197   tokenizer = NULL;
198   if (NULL != testbed)
199   {
200     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (testbed));
201     GNUNET_OS_process_destroy (testbed);
202     testbed = NULL;
203   }  
204   if (NULL != test_system)
205   {
206     GNUNET_TESTING_system_destroy (test_system, GNUNET_YES);
207     test_system = NULL;
208   }
209 }
210
211
212 /**
213  * Scheduler shutdown task to be run now.
214  */
215 static void
216 shutdown_now (void)
217 {
218   if (GNUNET_SCHEDULER_NO_TASK != shutdown_task_id)
219     GNUNET_SCHEDULER_cancel (shutdown_task_id);
220   shutdown_task_id = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
221 }
222
223
224 /**
225  * Task to write to the standard out
226  *
227  * @param cls the WriteContext
228  * @param tc the TaskContext
229  */
230 static void
231 write_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
232 {
233   struct WriteContext *wc = cls;
234   ssize_t bytes_wrote;
235
236   GNUNET_assert (NULL != wc);
237   write_task_id = GNUNET_SCHEDULER_NO_TASK;
238   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
239   {
240     GNUNET_free (wc->data);
241     GNUNET_free (wc);
242     return;
243   }
244   bytes_wrote =
245       GNUNET_DISK_file_write (stdout_fd, wc->data + wc->pos,
246                               wc->length - wc->pos);
247   if (GNUNET_SYSERR == bytes_wrote)
248   {
249     LOG (GNUNET_ERROR_TYPE_WARNING, "Cannot reply back configuration\n");
250     GNUNET_free (wc->data);
251     GNUNET_free (wc);
252     return;
253   }
254   wc->pos += bytes_wrote;
255   if (wc->pos == wc->length)
256   {
257     GNUNET_free (wc->data);
258     GNUNET_free (wc);
259     return;
260   }
261   write_task_id =
262       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
263                                        &write_task, wc);
264 }
265
266
267 /**
268  * Task triggered whenever we receive a SIGCHLD (child
269  * process died).
270  *
271  * @param cls closure, NULL if we need to self-restart
272  * @param tc context
273  */
274 static void
275 child_death_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
276 {
277   const struct GNUNET_DISK_FileHandle *pr;
278   char c[16];
279   enum GNUNET_OS_ProcessStatusType type;
280   unsigned long code;
281   int ret;
282
283   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
284   child_death_task_id = GNUNET_SCHEDULER_NO_TASK;
285   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
286   {
287     child_death_task_id =
288         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
289                                         pr, &child_death_task, NULL);
290     return;
291   }
292   /* consume the signal */
293   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
294   LOG_DEBUG ("Got SIGCHLD\n");
295   if (NULL == testbed)
296   {
297     GNUNET_break (0);
298     return;
299   }
300   GNUNET_break (GNUNET_SYSERR != 
301                 (ret = GNUNET_OS_process_status (testbed, &type, &code)));
302   if (GNUNET_NO != ret)
303   {
304     GNUNET_OS_process_destroy (testbed);
305     testbed = NULL;
306     /* Send SIGTERM to our process group */
307     if (0 != PLIBC_KILL (0, SIGTERM))
308     {
309       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "signal");
310       shutdown_now ();          /* Couldn't send the signal, we shutdown frowning */
311     }
312     return;
313   }
314   LOG_DEBUG ("Child hasn't died.  Resuming to monitor its status\n");
315   child_death_task_id =
316       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
317                                       pr, &child_death_task, NULL);
318 }
319
320
321 /**
322  * Resolves a hostname using getaddrinfo
323  *
324  * @param host the hostname
325  * @return the string representing the IPv4 address of the given host; NULL upon error
326  */
327 const char *
328 simple_resolve (const char *host)
329 {
330   struct addrinfo *res;
331   const struct sockaddr_in *in_addr; 
332   char *hostip;
333   struct addrinfo hint;
334   unsigned int rc;
335
336   hint.ai_family = AF_INET;     /* IPv4 */
337   hint.ai_socktype = 0;
338   hint.ai_protocol = 0;
339   hint.ai_addrlen = 0;
340   hint.ai_addr = NULL;
341   hint.ai_canonname = NULL;
342   hint.ai_next = NULL;
343   hint.ai_flags = AI_NUMERICSERV;
344   res = NULL;
345   LOG_DEBUG ("Resolving [%s]\n", host);
346   if (0 != (rc = getaddrinfo (host, "22", &hint, &res)))
347   {
348     LOG_GAI (GNUNET_ERROR_TYPE_ERROR, "getaddrinfo", rc);
349     return NULL;
350   }
351   GNUNET_assert (NULL != res);
352   GNUNET_assert (NULL != res->ai_addr);
353   GNUNET_assert (sizeof (struct sockaddr_in) == res->ai_addrlen);
354   in_addr = (const struct sockaddr_in *) res->ai_addr;
355   hostip = inet_ntoa (in_addr->sin_addr);
356   GNUNET_assert (NULL != hostip);
357   freeaddrinfo (res);
358   LOG_DEBUG ("Resolved [%s] to [%s]\n", host, hostip);
359   return hostip;
360 }
361
362
363 /**
364  * Functions with this signature are called whenever a
365  * complete message is received by the tokenizer.
366  *
367  * Do not call GNUNET_SERVER_mst_destroy in callback
368  *
369  * @param cls closure
370  * @param client identification of the client
371  * @param message the actual message
372  *
373  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
374  */
375 static int
376 tokenizer_cb (void *cls, void *client,
377               const struct GNUNET_MessageHeader *message)
378 {
379   const struct GNUNET_TESTBED_HelperInit *msg;
380   struct GNUNET_TESTBED_HelperReply *reply;
381   struct GNUNET_CONFIGURATION_Handle *cfg;
382   struct WriteContext *wc;
383   char *binary;
384   char *trusted_ip;
385   char *hostname;
386   const char *hostip;
387   char *config;
388   char *xconfig;
389   size_t config_size;
390   uLongf ul_config_size;
391   size_t xconfig_size;
392   uint16_t trusted_ip_size;
393   uint16_t hostname_size;
394   uint16_t msize;
395
396   msize = ntohs (message->size);
397   if ((sizeof (struct GNUNET_TESTBED_HelperInit) >= msize) ||
398       (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT != ntohs (message->type)))
399   {
400     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
401     goto error;
402   }
403   msg = (const struct GNUNET_TESTBED_HelperInit *) message;
404   trusted_ip_size = ntohs (msg->trusted_ip_size);
405   trusted_ip = (char *) &msg[1];
406   if ('\0' != trusted_ip[trusted_ip_size])
407   {
408     LOG (GNUNET_ERROR_TYPE_WARNING, "Trusted IP cannot be empty -- exiting\n");
409     goto error;
410   }
411   hostname_size = ntohs (msg->hostname_size);
412   if ((sizeof (struct GNUNET_TESTBED_HelperInit) + trusted_ip_size + 1 +
413        hostname_size) >= msize)
414   {
415     GNUNET_break (0);
416     LOG (GNUNET_ERROR_TYPE_WARNING, "Received unexpected message -- exiting\n");
417     goto error;
418   }
419   ul_config_size = (uLongf) ntohs (msg->config_size);
420   config = GNUNET_malloc (ul_config_size);
421   xconfig_size =
422       ntohs (message->size) - (trusted_ip_size + 1 +
423                                sizeof (struct GNUNET_TESTBED_HelperInit));
424   if (Z_OK !=
425       uncompress ((Bytef *) config, &ul_config_size,
426                   (const Bytef *) (trusted_ip + trusted_ip_size + 1 +
427                                    hostname_size), (uLongf) xconfig_size))
428   {
429     LOG (GNUNET_ERROR_TYPE_WARNING,
430          "Error while uncompressing config -- exiting\n");
431     GNUNET_free (config);
432     goto error;
433   }
434   cfg = GNUNET_CONFIGURATION_create ();
435   if (GNUNET_OK !=
436       GNUNET_CONFIGURATION_deserialize (cfg, config, ul_config_size, GNUNET_NO))
437   {
438     LOG (GNUNET_ERROR_TYPE_WARNING,
439          "Unable to deserialize config -- exiting\n");
440     GNUNET_free (config);
441     goto error;
442   }
443   GNUNET_free (config);
444   hostname = NULL;
445   if (0 != hostname_size)
446   {
447     hostname = GNUNET_malloc (hostname_size + 1);
448     (void) strncpy (hostname, ((char *) &msg[1]) + trusted_ip_size + 1,
449                     hostname_size);
450     hostname[hostname_size] = '\0';
451   }
452   hostip = NULL;
453   if ( (NULL != hostname) && (NULL == (hostip = simple_resolve (hostname))) )
454   {
455     GNUNET_free (hostname);
456     hostname = NULL;
457   }  
458   test_system =
459       GNUNET_TESTING_system_create ("testbed-helper", trusted_ip, hostip, NULL);
460   GNUNET_free_non_null (hostname);
461   hostname = NULL;
462   hostip = NULL;
463   GNUNET_assert (NULL != test_system);
464   GNUNET_assert (GNUNET_OK ==
465                  GNUNET_TESTING_configuration_create (test_system, cfg));
466   GNUNET_assert (GNUNET_OK ==
467                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
468                                                         "DEFAULTCONFIG",
469                                                         &config));
470   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config))
471   {
472     LOG (GNUNET_ERROR_TYPE_WARNING,
473          "Unable to write config file: %s -- exiting\n", config);
474     GNUNET_CONFIGURATION_destroy (cfg);
475     GNUNET_free (config);
476     goto error;
477   }
478   LOG_DEBUG ("Staring testbed with config: %s\n", config);
479   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-testbed");
480   testbed =
481       GNUNET_OS_start_process (PIPE_CONTROL,
482                                GNUNET_OS_INHERIT_STD_ERR /*verbose? */ , NULL,
483                                NULL, binary, "gnunet-service-testbed", "-c",
484                                config, NULL);
485   GNUNET_free (binary);
486   GNUNET_free (config);
487   if (NULL == testbed)
488   {
489     LOG (GNUNET_ERROR_TYPE_WARNING,
490          "Error starting gnunet-service-testbed -- exiting\n");
491     GNUNET_CONFIGURATION_destroy (cfg);
492     goto error;
493   }
494   done_reading = GNUNET_YES;
495   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
496   GNUNET_CONFIGURATION_destroy (cfg);
497   cfg = NULL;
498   xconfig_size =
499       GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
500   GNUNET_free (config);
501   wc = GNUNET_malloc (sizeof (struct WriteContext));
502   wc->length = xconfig_size + sizeof (struct GNUNET_TESTBED_HelperReply);
503   reply = GNUNET_realloc (xconfig, wc->length);
504   memmove (&reply[1], reply, xconfig_size);
505   reply->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY);
506   reply->header.size = htons ((uint16_t) wc->length);
507   reply->config_size = htons ((uint16_t) config_size);
508   wc->data = reply;
509   write_task_id =
510       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, stdout_fd,
511                                        &write_task, wc);  
512   child_death_task_id =
513       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
514                                       GNUNET_DISK_pipe_handle (sigpipe,
515                                                                GNUNET_DISK_PIPE_END_READ),
516                                       &child_death_task, NULL);
517   return GNUNET_OK;
518
519 error:
520   status = GNUNET_SYSERR;
521   shutdown_now ();
522   return GNUNET_SYSERR;
523 }
524
525
526 /**
527  * Task to read from stdin
528  *
529  * @param cls NULL
530  * @param tc the task context
531  */
532 static void
533 read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
534 {
535   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
536   ssize_t sread;
537
538   read_task_id = GNUNET_SCHEDULER_NO_TASK;
539   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
540     return;
541   sread = GNUNET_DISK_file_read (stdin_fd, buf, sizeof (buf));
542   if ((GNUNET_SYSERR == sread) || (0 == sread))
543   {
544     LOG_DEBUG ("STDIN closed\n");
545     shutdown_now ();
546     return;
547   }
548   if (GNUNET_YES == done_reading)
549   {
550     /* didn't expect any more data! */
551     GNUNET_break_op (0);
552     shutdown_now ();
553     return;
554   }
555   LOG_DEBUG ("Read %u bytes\n", sread);
556   if (GNUNET_OK !=
557       GNUNET_SERVER_mst_receive (tokenizer, NULL, buf, sread, GNUNET_NO,
558                                  GNUNET_NO))
559   {
560     GNUNET_break (0);
561     shutdown_now ();
562     return;
563   }
564   read_task_id =                /* No timeout while reading */
565       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
566                                       &read_task, NULL);
567 }
568
569
570 /**
571  * Main function that will be run.
572  *
573  * @param cls closure
574  * @param args remaining command-line arguments
575  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
576  * @param cfg configuration
577  */
578 static void
579 run (void *cls, char *const *args, const char *cfgfile,
580      const struct GNUNET_CONFIGURATION_Handle *cfg)
581 {
582   LOG_DEBUG ("Starting testbed helper...\n");
583   tokenizer = GNUNET_SERVER_mst_create (&tokenizer_cb, NULL);
584   stdin_fd = GNUNET_DISK_get_handle_from_native (stdin);
585   stdout_fd = GNUNET_DISK_get_handle_from_native (stdout);
586   read_task_id =
587       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, stdin_fd,
588                                       &read_task, NULL);
589   shutdown_task_id = 
590       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
591                                     NULL);
592 }
593
594
595 /**
596  * Signal handler called for SIGCHLD.
597  */
598 static void
599 sighandler_child_death ()
600 {
601   static char c;
602   int old_errno;        /* back-up errno */
603
604   old_errno = errno;
605   GNUNET_break (1 ==
606                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
607                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
608                                         &c, sizeof (c)));
609   errno = old_errno;
610 }
611
612
613 /**
614  * Main function
615  *
616  * @param argc the number of command line arguments
617  * @param argv command line arg array
618  * @return return code
619  */
620 int
621 main (int argc, char **argv)
622 {
623   struct GNUNET_SIGNAL_Context *shc_chld;
624
625   struct GNUNET_GETOPT_CommandLineOption options[] = {
626     GNUNET_GETOPT_OPTION_END
627   };
628   int ret;
629
630   status = GNUNET_OK;
631   if (NULL == (sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, 
632                                            GNUNET_NO, GNUNET_NO)))
633   {
634     GNUNET_break (0);
635     ret = GNUNET_SYSERR;
636     return 1;
637   }
638   shc_chld =
639       GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
640   ret =
641       GNUNET_PROGRAM_run (argc, argv, "gnunet-helper-testbed",
642                           "Helper for starting gnunet-service-testbed", options,
643                           &run, NULL);
644   GNUNET_SIGNAL_handler_uninstall (shc_chld);
645   shc_chld = NULL;
646   GNUNET_DISK_pipe_close (sigpipe);
647   if (GNUNET_OK != ret)
648     return 1;
649   return (GNUNET_OK == status) ? 0 : 1;
650 }
651
652 /* end of gnunet-helper-testbed.c */