doxygen additions
[oweals/gnunet.git] / src / arm / gnunet-service-arm.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 2, 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 arm/gnunet-service-arm.c
23  * @brief the automated restart manager service
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - multiple start-stop requests with RC>1 can result
28  *   in UP/DOWN signals based on "pending" that are inaccurate...
29  *   => have list of clients waiting for a resolution instead of
30  *      giving instant (but incorrect) replies
31  * - need to test auto-restart code on configuration changes;
32  * - should refine restart code to check if *relevant* parts of the
33  *   configuration were changed (anything in the section for the service)
34  * - should have a way to specify dependencies between services and
35  *   manage restarts of groups of services
36  */
37 #include "platform.h"
38 #include "gnunet_client_lib.h"
39 #include "gnunet_getopt_lib.h"
40 #include "gnunet_os_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_service_lib.h"
43 #include "gnunet_signal_lib.h"
44 #include "arm.h"
45
46
47 /**
48  * Check for configuration file changes every 5s.
49  */
50 #define MAINT_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
51
52 /**
53  * Threshold after which exponential backoff shouldn't increase (in ms); 30m
54  */
55 #define EXPONENTIAL_BACKOFF_THRESHOLD (1000 * 60 * 30)
56
57
58 /**
59  * List of our services.
60  */
61 struct ServiceList;
62
63 /**
64  * List of our services.
65  */
66 struct ServiceList
67 {
68   /**
69    * This is a linked list.
70    */
71   struct ServiceList *next;
72
73   /**
74    * Name of the service.
75    */
76   char *name;
77
78   /**
79    * Name of the binary used.
80    */
81   char *binary;
82
83   /**
84    * Name of the configuration file used.
85    */
86   char *config;
87
88   /**
89    * Client to notify upon kill completion (waitpid), NULL
90    * if we should simply restart the process.
91    */
92   struct GNUNET_SERVER_Client *killing_client;
93
94   /**
95    * Process ID of the child.
96    */
97   pid_t pid;
98
99   /**
100    * Last time the config of this service was
101    * modified.
102    */
103   time_t mtime;
104
105   /**
106    * Process exponential backoff time 
107    */
108   struct GNUNET_TIME_Relative backoff;
109
110   /**
111    * Absolute time at which the process is scheduled to restart in case of death 
112    */
113   struct GNUNET_TIME_Absolute restartAt;
114
115   /**
116    * Reference counter (counts how many times we've been
117    * asked to start the service).  We only actually stop
118    * it once rc hits zero.
119    */
120   unsigned int rc;
121
122 };
123
124 /**
125  * List of running services.
126  */
127 static struct ServiceList *running;
128
129 /**
130  * Our configuration
131  */
132 static const struct GNUNET_CONFIGURATION_Handle *cfg;
133
134 /**
135  * Our scheduler.
136  */
137 static struct GNUNET_SCHEDULER_Handle *sched;
138
139 /**
140  * Command to prepend to each actual command.
141  */
142 static char *prefix_command;
143
144 /**
145  * Option to append to each actual command.
146  */
147 static char *final_option;
148
149 /**
150  * ID of task called whenever we get a SIGCHILD.
151  */
152 static GNUNET_SCHEDULER_TaskIdentifier child_death_task;
153
154 /**
155  * ID of task called whenever the timeout for restarting a child
156  * expires.
157  */
158 static GNUNET_SCHEDULER_TaskIdentifier child_restart_task;
159
160 /**
161  * Context for our SIGCHILD handler.
162  */
163 static struct GNUNET_SIGNAL_Context *shc_chld;
164
165 /**
166  * Pipe used to communicate shutdown via signal.
167  */
168 static struct GNUNET_DISK_PipeHandle *sigpipe;
169
170 /**
171  * Reading end of the signal pipe.
172  */
173 static const struct GNUNET_DISK_FileHandle *pr;
174
175 /**
176  * Are we in shutdown mode?
177  */
178 static int in_shutdown;
179
180
181 /**
182  * Handle to our server instance.  Our server is a bit special in that
183  * its service is not immediately stopped once we get a shutdown
184  * request (since we need to continue service until all of our child
185  * processes are dead).  This handle is used to shut down the server
186  * (and thus trigger process termination) once all child processes are
187  * also dead.  A special option in the ARM configuration modifies the
188  * behaviour of the service implementation to not do the shutdown
189  * immediately.
190  */
191 static struct GNUNET_SERVER_Handle *server;
192
193
194 /**
195  * If the configuration file changes, restart tasks that depended on that
196  * option.
197  *
198  * @param cls closure, NULL if we need to self-restart
199  * @param tc context
200  */
201 static void 
202 config_change_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
203 {
204   struct ServiceList *pos;
205   struct stat sbuf;
206
207   pos = running;
208   while (pos != NULL)
209     {
210       /* FIXME: this test for config change is a bit too coarse grained */
211       if ( (0 == STAT (pos->config, &sbuf)) && 
212            (pos->mtime < sbuf.st_mtime) &&
213            (pos->pid != 0) )
214         {
215           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
216                       _("Restarting service `%s' due to configuration file change.\n"));
217           if (0 != PLIBC_KILL (pos->pid, SIGTERM))
218             GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
219           else
220             pos->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
221         }
222       pos = pos->next;
223     }
224 }
225
226
227
228 /**
229  * Transmit a status result message.
230  *
231  * @param cls pointer to "unit16_t*" with message type
232  * @param size number of bytes available in buf
233  * @param buf where to copy the message, NULL on error
234  * @return number of bytes copied to buf
235  */
236 static size_t
237 write_result (void *cls, size_t size, void *buf)
238 {
239   uint16_t *res = cls;
240   struct GNUNET_MessageHeader *msg;
241
242   if (buf == NULL)
243     {
244       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
245                   _("Could not send status result to client\n"));
246       return 0;                 /* error, not much we can do */
247     }
248 #if DEBUG_ARM
249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
250               "Sending status response %u to client\n",
251               (unsigned int) *res);
252 #endif
253   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
254   msg = buf;
255   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
256   msg->type = htons (*res);
257   GNUNET_free (res);
258   return sizeof (struct GNUNET_MessageHeader);
259 }
260
261
262
263 /**
264  * Signal our client that we will start or stop the
265  * service.
266  *
267  * @param client who is being signalled
268  * @param name name of the service
269  * @param result message type to send
270  * @return NULL if it was not found
271  */
272 static void
273 signal_result (struct GNUNET_SERVER_Client *client,
274                const char *name, uint16_t result)
275 {
276   uint16_t *res;
277
278   if (NULL == client)
279     {
280       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
281                   _
282                   ("Not sending status result to client: no client known\n"));
283       return;
284     }
285 #if DEBUG_ARM
286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
287               "Telling client that service `%s' is now %s\n",
288               name,
289               result == GNUNET_MESSAGE_TYPE_ARM_IS_DOWN ? "down" : "up");
290 #endif
291   res = GNUNET_malloc (sizeof (uint16_t));
292   *res = result;
293   GNUNET_SERVER_notify_transmit_ready (client,
294                                        sizeof (struct GNUNET_MessageHeader),
295                                        GNUNET_TIME_UNIT_FOREVER_REL,
296                                        &write_result, res);
297 }
298
299
300 /**
301  * Find the process with the given service
302  * name in the given list, remove it and return it.
303  *
304  * @param name which service entry to look up
305  * @return NULL if it was not found
306  */
307 static struct ServiceList *
308 find_name (const char *name)
309 {
310   struct ServiceList *pos;
311   struct ServiceList *prev;
312
313   pos = running;
314   prev = NULL;
315   while (pos != NULL)
316     {
317       if (0 == strcmp (pos->name, name))
318         {
319           if (prev == NULL)
320             running = pos->next;
321           else
322             prev->next = pos->next;
323           pos->next = NULL;
324           return pos;
325         }
326       prev = pos;
327       pos = pos->next;
328     }
329   return NULL;
330 }
331
332
333 /**
334  * Free an entry in the service list.
335  *
336  * @param pos entry to free
337  */
338 static void
339 free_entry (struct ServiceList *pos)
340 {
341   GNUNET_free_non_null (pos->config);
342   GNUNET_free_non_null (pos->binary);
343   GNUNET_free (pos->name);
344   GNUNET_free (pos);
345 }
346
347 #include "do_start_process.c"
348
349 /**
350  * Actually start the process for the given service.
351  *
352  * @param sl identifies service to start
353  */
354 static void
355 start_process (struct ServiceList *sl)
356 {
357   char *loprefix;
358   char *options;
359   char *optpos;
360   char *optend;
361   const char *next;
362   int use_debug;
363   char b;
364   char *val;
365
366   /* start service */
367   if (GNUNET_OK !=
368       GNUNET_CONFIGURATION_get_value_string (cfg,
369                                              sl->name, "PREFIX", &loprefix))
370     loprefix = GNUNET_strdup (prefix_command);
371   if (GNUNET_OK !=
372       GNUNET_CONFIGURATION_get_value_string (cfg,
373                                              sl->name, "OPTIONS", &options))
374     {      
375       options = GNUNET_strdup (final_option);
376       if (NULL == strstr (options, "%"))
377         {
378           /* replace '{}' with service name */
379           while (NULL != (optpos = strstr (options, "{}")))
380             {
381               optpos[0] = '%';
382               optpos[1] = 's';
383               GNUNET_asprintf (&optpos,
384                                options,
385                                sl->name);
386               GNUNET_free (options);
387               options = optpos;
388             }
389           /* replace '$PATH' with value associated with "PATH" */
390           while (NULL != (optpos = strstr (options, "$")))
391             {
392               optend = optpos + 1;
393               while (isupper (*optend)) optend++;             
394               b = *optend;
395               if ('\0' == b)
396                 next = "";
397               else
398                 next = optend+1;
399               *optend = '\0';
400               if (GNUNET_OK !=
401                   GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
402                                                          optpos+1,
403                                                          &val))
404                 val = GNUNET_strdup ("");
405               *optpos = '\0';
406               GNUNET_asprintf (&optpos,
407                                "%s%s%c%s",
408                                options,
409                                val,
410                                b,
411                                next);
412               GNUNET_free (options);
413               GNUNET_free (val);
414               options = optpos;
415             }
416         }
417     }
418   use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "DEBUG");
419
420   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Starting service `%s'\n"), sl->name);
421 #if DEBUG_ARM
422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
423               "Starting service `%s' using binary `%s' and configuration `%s'\n",
424               sl->name, sl->binary, sl->config);
425 #endif
426   if (GNUNET_YES == use_debug)
427     sl->pid = do_start_process (loprefix,
428                                 sl->binary,
429                                 "-c", sl->config,
430                                 "-L", "DEBUG",
431                                 options,
432                                 NULL);
433   else
434     sl->pid = do_start_process (loprefix,
435                                 sl->binary,
436                                 "-c", sl->config,
437                                 options,
438                                 NULL);
439   GNUNET_free (loprefix);
440   GNUNET_free (options);
441   /* FIXME: should check sl->pid */
442 }
443
444
445 /**
446  * Start the specified service.
447  *
448  * @param client who is asking for this
449  * @param servicename name of the service to start
450  */
451 static void
452 start_service (struct GNUNET_SERVER_Client *client, const char *servicename)
453 {
454   struct ServiceList *sl;
455   char *binary;
456   char *config;
457   struct stat sbuf;
458
459   if (GNUNET_YES == in_shutdown)
460     {
461       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
462                   _("ARM is shutting down, service `%s' not started.\n"),
463                   servicename);
464       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
465       return;
466     }
467   sl = find_name (servicename);
468   if (sl != NULL)
469     {
470       /* already running, just increment RC */
471       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
472                   _("Service `%s' already running.\n"), servicename);
473       sl->rc++;
474       sl->next = running;
475       running = sl;
476       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UP);
477       return;
478     }
479   if (GNUNET_OK !=
480       GNUNET_CONFIGURATION_get_value_string (cfg,
481                                              servicename, "BINARY", &binary))
482     {
483       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
484                   _("Binary implementing service `%s' not known!\n"),
485                   servicename);
486       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
487       return;
488     }
489   if ((GNUNET_OK !=
490        GNUNET_CONFIGURATION_get_value_filename (cfg,
491                                                 servicename,
492                                                 "CONFIG",
493                                                 &config)) ||
494       (0 != STAT (config, &sbuf)))
495     {
496       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
497                   _("Configuration file `%s' for service `%s' not known!\n"),
498                   config, servicename);
499       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
500       GNUNET_free (binary);
501       GNUNET_free_non_null (config);
502       return;
503     }
504   sl = GNUNET_malloc (sizeof (struct ServiceList));
505   sl->name = GNUNET_strdup (servicename);
506   sl->next = running;
507   sl->rc = 1;
508   sl->binary = binary;
509   sl->config = config;
510   sl->mtime = sbuf.st_mtime;
511   sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
512   sl->restartAt = GNUNET_TIME_UNIT_FOREVER_ABS;
513
514   running = sl;
515   start_process (sl);
516   if (NULL != client)
517     signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UP);
518 }
519
520
521 /**
522  * Stop the specified service.
523  *
524  * @param client who is asking for this
525  * @param servicename name of the service to stop
526  */
527 static void
528 stop_service (struct GNUNET_SERVER_Client *client, const char *servicename)
529 {
530   struct ServiceList *pos;
531
532   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
533               _("Preparing to stop `%s'\n"), servicename);
534   pos = find_name (servicename);
535   if (pos == NULL)
536     {
537       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UNKNOWN);
538       GNUNET_SERVER_receive_done (client, GNUNET_OK);
539       return;
540     }
541   if (pos->rc > 1)
542     {
543       /* RC>1, just decrement RC */
544       pos->rc--;
545       pos->next = running;
546       running = pos;
547 #if DEBUG_ARM
548       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
549                   "Service `%s' still used by %u clients, will keep it running!\n",
550                   servicename, pos->rc);
551 #endif
552       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UP);
553       GNUNET_SERVER_receive_done (client, GNUNET_OK);
554       return;
555     }
556   if (pos->rc == 1)
557     pos->rc--;                  /* decrement RC to zero */
558   if (pos->killing_client != NULL)
559     {
560       /* killing already in progress */
561 #if DEBUG_ARM
562       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
563                   "Service `%s' is already down\n", servicename);
564 #endif
565       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
566       GNUNET_SERVER_receive_done (client, GNUNET_OK);
567       pos->next = running;
568       running = pos;
569       return;
570     }
571
572   if (GNUNET_YES == in_shutdown)
573     {
574 #if DEBUG_ARM
575       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
576                   "Termination request already sent to `%s' (since ARM is in shutdown).\n",
577                   servicename);
578 #endif
579       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
580       GNUNET_SERVER_receive_done (client, GNUNET_OK);
581       pos->next = running;
582       running = pos;
583       return;
584     }
585   if (pos->pid == 0)
586     {
587       /* process is in delayed restart, simply remove it! */
588       free_entry (pos);
589       signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
590       GNUNET_SERVER_receive_done (client, GNUNET_OK);
591       return;
592     }
593 #if DEBUG_ARM
594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
595               "Sending kill signal to service `%s', waiting for process to die.\n",
596               servicename);
597 #endif
598   if (0 != PLIBC_KILL (pos->pid, SIGTERM))
599     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
600   pos->next = running;
601   running = pos;
602   pos->killing_client = client;
603   GNUNET_SERVER_client_keep (client);
604 }
605
606
607 /**
608  * Handle START-message.
609  *
610  * @param cls closure (always NULL)
611  * @param client identification of the client
612  * @param message the actual message
613  * @return GNUNET_OK to keep the connection open,
614  *         GNUNET_SYSERR to close it (signal serious error)
615  */
616 static void
617 handle_start (void *cls,
618               struct GNUNET_SERVER_Client *client,
619               const struct GNUNET_MessageHeader *message)
620 {
621   const char *servicename;
622   uint16_t size;
623
624   size = ntohs (message->size);
625   size -= sizeof (struct GNUNET_MessageHeader);
626   servicename = (const char *) &message[1];
627   if ((size == 0) || (servicename[size - 1] != '\0'))
628     {
629       GNUNET_break (0);
630       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
631       return;
632     }
633   start_service (client, servicename);
634   GNUNET_SERVER_receive_done (client, GNUNET_OK);
635 }
636
637
638 /**
639  * Handle STOP-message.
640  *
641  * @param cls closure (always NULL)
642  * @param client identification of the client
643  * @param message the actual message
644  * @return GNUNET_OK to keep the connection open,
645  *         GNUNET_SYSERR to close it (signal serious error)
646  */
647 static void
648 handle_stop (void *cls,
649              struct GNUNET_SERVER_Client *client,
650              const struct GNUNET_MessageHeader *message)
651 {
652   const char *servicename;
653   uint16_t size;
654
655   size = ntohs (message->size);
656   size -= sizeof (struct GNUNET_MessageHeader);
657   servicename = (const char *) &message[1];
658   if ((size == 0) || (servicename[size - 1] != '\0'))
659     {
660       GNUNET_break (0);
661       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
662       return;
663     }
664   stop_service (client, servicename);
665 }
666
667
668 /**
669  * Remove all entries for tasks that are not running
670  * (pid = 0) from the running list (they will no longer
671  * be restarted since we are shutting down).
672  */
673 static void
674 clean_up_running ()
675 {
676   struct ServiceList *pos;
677   struct ServiceList *next;
678   struct ServiceList *prev;
679  
680   pos = running;
681   prev = NULL;
682   while (NULL != pos)
683     {
684       next = pos->next;
685       if (pos->pid == 0)
686         {
687           if (prev == NULL)
688             running = next;
689           else
690             prev->next = next;
691           free_entry (pos);
692         }
693       else
694         prev = pos;
695       pos = next;
696     }
697 }
698
699
700 /**
701  * We are done with everything.  Stop remaining 
702  * tasks, signal handler and the server. 
703  */
704 static void
705 do_shutdown ()
706 {
707   GNUNET_SERVER_destroy (server);
708   server = NULL;
709   GNUNET_SIGNAL_handler_uninstall (shc_chld);
710   shc_chld = NULL;
711   GNUNET_SCHEDULER_cancel (sched, child_death_task);
712   child_death_task = GNUNET_SCHEDULER_NO_TASK;
713 }
714
715
716 /**
717  * Task run for shutdown.
718  *
719  * @param cls closure, NULL if we need to self-restart
720  * @param tc context
721  */
722 static void
723 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
724 {
725   struct ServiceList *pos;
726  
727 #if DEBUG_ARM
728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Stopping all services\n"));
729 #endif
730   in_shutdown = GNUNET_YES;
731   pos = running;
732   while (NULL != pos)
733     {
734       if (pos->pid != 0)
735         {
736 #if DEBUG_ARM
737           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
738                       "Sending SIGTERM to `%s'\n", pos->name);
739 #endif
740           if (0 != PLIBC_KILL (pos->pid, SIGTERM))
741             GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
742         }
743       pos = pos->next;
744     }
745   if (running == NULL)
746     do_shutdown ();
747 }
748
749
750 /**
751  * Task run whenever it is time to restart a child that died.
752  *
753  * @param cls closure, always NULL
754  * @param tc context
755  */
756 static void
757 delayed_restart_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
758 {
759   struct ServiceList *pos;
760   struct GNUNET_TIME_Relative lowestRestartDelay;
761
762   child_restart_task = GNUNET_SCHEDULER_NO_TASK;
763   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
764     {
765       clean_up_running ();
766       if (NULL == running)
767         do_shutdown ();
768       return;
769     }
770   lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
771
772   /* check for services that need to be restarted due to
773      configuration changes or because the last restart failed */
774   pos = running;
775   while (pos != NULL)
776     {
777       if ( (pos->pid == 0) && 
778            (GNUNET_YES != in_shutdown) )
779         {
780           if (GNUNET_TIME_absolute_get_remaining (pos->restartAt).value == 0)
781             {
782               GNUNET_log (GNUNET_ERROR_TYPE_INFO,
783                           _("Restarting service `%s'.\n"), pos->name);
784               start_process (pos);
785             }
786           else
787             {
788               lowestRestartDelay 
789                 = GNUNET_TIME_relative_min (lowestRestartDelay,
790                                             GNUNET_TIME_absolute_get_remaining
791                                             (pos->restartAt));
792             }
793         }
794       pos = pos->next;
795     }  
796   if (lowestRestartDelay.value != GNUNET_TIME_UNIT_FOREVER_REL.value)
797     {
798 #if DEBUG_ARM
799       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
800                   "Will restart process in %llums\n",
801                   (unsigned long long) lowestRestartDelay.value);
802 #endif
803       child_restart_task
804         = GNUNET_SCHEDULER_add_delayed (sched,
805                                         lowestRestartDelay,
806                                         &delayed_restart_task,
807                                         NULL);
808     }
809 }
810
811
812 /**
813  * Task triggered whenever we receive a SIGCHLD (child
814  * process died).  
815  *
816  * @param cls closure, NULL if we need to self-restart
817  * @param tc context
818  */
819 static void
820 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
821 {
822   struct ServiceList *pos;
823   struct ServiceList *prev;
824   struct ServiceList *next;
825   const char *statstr;
826   int statcode;
827   int ret;
828   char c[16];
829   enum GNUNET_OS_ProcessStatusType statusType;
830   unsigned long statusCode;
831
832   child_death_task = GNUNET_SCHEDULER_NO_TASK;
833   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
834     {
835       child_death_task =
836         GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, pr,
837                                         &maint_child_death, NULL);
838       return;    
839     }
840   /* consume the signal */
841   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
842
843   /* check for services that died (WAITPID) */
844   prev = NULL;
845   next = running;
846   while (NULL != (pos = next))
847     {
848       next = pos->next;
849       if (pos->pid == 0) 
850         {
851           prev = pos;
852           continue;
853         }
854       if ((GNUNET_SYSERR == (ret = GNUNET_OS_process_status (pos->pid,
855                                                              &statusType,
856                                                              &statusCode))) ||
857           ( (ret == GNUNET_NO) ||
858             (statusType == GNUNET_OS_PROCESS_STOPPED) ||
859             (statusType == GNUNET_OS_PROCESS_RUNNING)) )
860         {
861           prev = pos;
862           continue;
863         }
864
865       if (statusType == GNUNET_OS_PROCESS_EXITED)
866         {
867           statstr = _( /* process termination method */ "exit");
868           statcode = statusCode;
869         }
870       else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
871         {
872           statstr = _( /* process termination method */ "signal");
873           statcode = statusCode;
874         }
875       else
876         {
877           statstr = _( /* process termination method */ "unknown");
878           statcode = 0;
879         }
880       pos->pid = 0;
881       if (NULL != pos->killing_client) 
882         {
883           if (prev == NULL)
884             running = next;
885           else
886             prev->next = next;
887           GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
888                       _("Service `%s' stopped\n"),
889                       pos->name);
890           signal_result (pos->killing_client, 
891                          pos->name, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
892           GNUNET_SERVER_receive_done (pos->killing_client, GNUNET_OK);
893           GNUNET_SERVER_client_drop (pos->killing_client);
894           free_entry (pos);
895           continue;
896         }
897       if (GNUNET_YES != in_shutdown)
898         {
899           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
900                       _
901                       ("Service `%s' terminated with status %s/%d, will try to restart it!\n"),
902                       pos->name, statstr, statcode);
903           /* schedule restart */
904           pos->restartAt
905             = GNUNET_TIME_relative_to_absolute (pos->backoff);
906           if (pos->backoff.value < EXPONENTIAL_BACKOFF_THRESHOLD)
907             pos->backoff 
908               = GNUNET_TIME_relative_multiply (pos->backoff, 2);
909           if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
910             GNUNET_SCHEDULER_cancel (sched, child_restart_task);
911           child_restart_task 
912             = GNUNET_SCHEDULER_add_with_priority (sched,
913                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
914                                                   &delayed_restart_task,
915                                                   NULL);
916         }
917 #if DEBUG_ARM
918       else
919         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
920                     "Service `%s' terminated with status %s/%d\n",
921                     pos->name, statstr, statcode);
922 #endif
923       prev = pos;
924     }
925   if (in_shutdown)
926     clean_up_running ();
927   if ( (running == NULL) &&
928        (in_shutdown) )
929     {
930       GNUNET_SERVER_destroy (server);
931       GNUNET_SIGNAL_handler_uninstall (shc_chld);
932       shc_chld = NULL;
933     }
934   else
935     {
936       child_death_task =
937         GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, pr,
938                                         &maint_child_death, NULL);
939     }
940 }
941
942
943 /**
944  * List of handlers for the messages understood by this service.
945  */
946 static struct GNUNET_SERVER_MessageHandler handlers[] = {
947   {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
948   {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
949   {NULL, NULL, 0, 0}
950 };
951
952 /**
953  * Signal handler called for SIGCHLD.  Triggers the
954  * respective handler by writing to the trigger pipe.
955  */
956 static void
957 sighandler_child_death ()
958 {
959   static char c;
960
961   GNUNET_break (1 == 
962                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
963                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE), &c,
964                                         sizeof (c)));
965 }
966
967
968 /**
969  * Process arm requests.
970  *
971  * @param cls closure
972  * @param s scheduler to use
973  * @param serv the initialized server
974  * @param c configuration to use
975  */
976 static void
977 run (void *cls,
978      struct GNUNET_SCHEDULER_Handle *s,
979      struct GNUNET_SERVER_Handle *serv,
980      const struct GNUNET_CONFIGURATION_Handle *c)
981 {
982   char *defaultservices;
983   char *pos;
984
985   cfg = c;
986   sched = s;
987   server = serv;
988   GNUNET_assert (serv != NULL);
989   shc_chld = GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
990   GNUNET_assert (sigpipe == NULL);
991   sigpipe = GNUNET_DISK_pipe (GNUNET_NO);
992   GNUNET_assert (sigpipe != NULL);
993   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
994   GNUNET_assert (pr != NULL);
995   GNUNET_SERVER_ignore_shutdown (serv, GNUNET_YES);
996   GNUNET_SCHEDULER_add_delayed (sched,
997                                 GNUNET_TIME_UNIT_FOREVER_REL,
998                                 &shutdown_task,
999                                 NULL);
1000   child_death_task =
1001     GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, pr,
1002                                     &maint_child_death, NULL);
1003
1004   if (GNUNET_OK !=
1005       GNUNET_CONFIGURATION_get_value_string (cfg,
1006                                              "ARM",
1007                                              "GLOBAL_PREFIX",
1008                                              &prefix_command))
1009     prefix_command = GNUNET_strdup ("");
1010   if (GNUNET_OK !=
1011       GNUNET_CONFIGURATION_get_value_string (cfg,
1012                                              "ARM",
1013                                              "GLOBAL_POSTFIX",
1014                                              &final_option))
1015     final_option = GNUNET_strdup ("");
1016   /* start default services... */
1017   if (GNUNET_OK ==
1018       GNUNET_CONFIGURATION_get_value_string (cfg,
1019                                              "ARM",
1020                                              "DEFAULTSERVICES",
1021                                              &defaultservices))
1022     {
1023 #if DEBUG_ARM
1024       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1025                   "Starting default services `%s'\n", defaultservices);
1026 #endif
1027       pos = strtok (defaultservices, " ");
1028       while (pos != NULL)
1029         {
1030           start_service (NULL, pos);
1031           pos = strtok (NULL, " ");
1032         }
1033       GNUNET_free (defaultservices);
1034     }
1035   else
1036     {
1037 #if DEBUG_ARM
1038       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1039                   "No default services configured.\n");
1040 #endif
1041     }
1042
1043   /* process client requests */
1044   GNUNET_SERVER_add_handlers (server, handlers);
1045
1046   /* manage services */
1047   GNUNET_SCHEDULER_add_with_priority (sched,
1048                                       GNUNET_SCHEDULER_PRIORITY_IDLE,
1049                                       &config_change_task, NULL);
1050 }
1051
1052
1053 /**
1054  * The main function for the arm service.
1055  *
1056  * @param argc number of arguments from the command line
1057  * @param argv command line arguments
1058  * @return 0 ok, 1 on error
1059  */
1060 int
1061 main (int argc, char *const *argv)
1062 {
1063   return (GNUNET_OK ==
1064           GNUNET_SERVICE_run (argc,
1065                               argv, "arm", GNUNET_YES, &run, NULL)) ? 0 : 1;
1066 }
1067
1068 /* end of gnunet-service-arm.c */