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