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