cleaning up code from debug session
[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       else
714         prev = pos;
715       pos = next;
716     }
717 }
718
719
720 /**
721  * We are done with everything.  Stop remaining 
722  * tasks, signal handler and the server. 
723  */
724 static void
725 do_shutdown ()
726 {
727   GNUNET_SERVER_destroy (server);
728   server = NULL;
729   GNUNET_SIGNAL_handler_uninstall (shc_chld);
730   shc_chld = NULL;
731   GNUNET_SCHEDULER_cancel (sched, child_death_task);
732   child_death_task = GNUNET_SCHEDULER_NO_TASK;
733 }
734
735
736 /**
737  * Task run for shutdown.
738  *
739  * @param cls closure, NULL if we need to self-restart
740  * @param tc context
741  */
742 static void
743 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
744 {
745   struct ServiceList *pos;
746  
747 #if DEBUG_ARM
748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Stopping all services\n"));
749 #endif
750   in_shutdown = GNUNET_YES;
751   pos = running;
752   while (NULL != pos)
753     {
754       if (pos->pid != 0)
755         {
756 #if DEBUG_ARM
757           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
758                       "Sending SIGTERM to `%s'\n", pos->name);
759 #endif
760           if (0 != PLIBC_KILL (pos->pid, SIGTERM))
761             GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
762         }
763       pos = pos->next;
764     }
765   if (running == NULL)
766     do_shutdown ();
767 }
768
769
770 /**
771  * Task run whenever it is time to restart a child that died.
772  *
773  * @param cls closure, always NULL
774  * @param tc context
775  */
776 static void
777 delayed_restart_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
778 {
779   struct ServiceList *pos;
780   struct GNUNET_TIME_Relative lowestRestartDelay;
781
782   child_restart_task = GNUNET_SCHEDULER_NO_TASK;
783   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
784     {
785       clean_up_running ();
786       if (NULL == running)
787         do_shutdown ();
788       return;
789     }
790   lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
791
792   /* check for services that need to be restarted due to
793      configuration changes or because the last restart failed */
794   pos = running;
795   while (pos != NULL)
796     {
797       if ( (pos->pid == 0) && 
798            (GNUNET_YES != in_shutdown) )
799         {
800           if (GNUNET_TIME_absolute_get_remaining (pos->restartAt).value == 0)
801             {
802               GNUNET_log (GNUNET_ERROR_TYPE_INFO,
803                           _("Restarting service `%s'.\n"), pos->name);
804               start_process (pos);
805             }
806           else
807             {
808               lowestRestartDelay 
809                 = GNUNET_TIME_relative_min (lowestRestartDelay,
810                                             GNUNET_TIME_absolute_get_remaining
811                                             (pos->restartAt));
812             }
813         }
814       pos = pos->next;
815     }  
816   if (lowestRestartDelay.value != GNUNET_TIME_UNIT_FOREVER_REL.value)
817     {
818 #if DEBUG_ARM
819       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820                   "Will restart process in %llums\n",
821                   (unsigned long long) lowestRestartDelay.value);
822 #endif
823       child_restart_task
824         = GNUNET_SCHEDULER_add_delayed (sched,
825                                         lowestRestartDelay,
826                                         &delayed_restart_task,
827                                         NULL);
828     }
829 }
830
831
832 /**
833  * 
834  *
835  * @param cls closure, NULL if we need to self-restart
836  * @param tc context
837  */
838 static void
839 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
840 {
841   struct ServiceList *pos;
842   struct ServiceList *prev;
843   struct ServiceList *next;
844   const char *statstr;
845   int statcode;
846   int ret;
847   char c;
848
849   child_death_task = GNUNET_SCHEDULER_NO_TASK;
850   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
851     {
852       child_death_task =
853         GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, pr,
854                                         &maint_child_death, NULL);
855       return;    
856     }
857   /* consume the signal */
858   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
859
860   /* check for services that died (WAITPID) */
861   prev = NULL;
862   next = running;
863   while (NULL != (pos = next))
864     {
865       enum GNUNET_OS_ProcessStatusType statusType;
866       unsigned long statusCode;
867
868       next = pos->next;
869       if (pos->pid == 0) 
870         {
871           prev = pos;
872           continue;
873         }
874       if ((GNUNET_SYSERR == (ret = GNUNET_OS_process_status (pos->pid,
875                                                              &statusType,
876                                                              &statusCode))) ||
877           ( (ret == GNUNET_NO) ||
878             (statusType == GNUNET_OS_PROCESS_STOPPED) ||
879             (statusType == GNUNET_OS_PROCESS_RUNNING)) )
880         {
881           prev = pos;
882           continue;
883         }
884       if (statusType == GNUNET_OS_PROCESS_EXITED)
885         {
886           statstr = _( /* process termination method */ "exit");
887           statcode = statusCode;
888         }
889       else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
890         {
891           statstr = _( /* process termination method */ "signal");
892           statcode = statusCode;
893         }
894       else
895         {
896           statstr = _( /* process termination method */ "unknown");
897           statcode = 0;
898         }
899       pos->pid = 0;
900       if (NULL != pos->kill_continuation) 
901         {
902           if (prev == NULL)
903             running = next;
904           else
905             prev->next = next;
906           pos->kill_continuation (pos->kill_continuation_cls, pos);
907           continue;
908         }
909       if (GNUNET_YES != in_shutdown)
910         {
911           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
912                       _
913                       ("Service `%s' terminated with status %s/%d, will try to restart it!\n"),
914                       pos->name, statstr, statcode);
915           /* schedule restart */
916           pos->restartAt
917             = GNUNET_TIME_relative_to_absolute (pos->backoff);
918           if (pos->backoff.value < EXPONENTIAL_BACKOFF_THRESHOLD)
919             pos->backoff 
920               = GNUNET_TIME_relative_multiply (pos->backoff, 2);
921           if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
922             GNUNET_SCHEDULER_cancel (sched, child_restart_task);
923           child_restart_task 
924             = GNUNET_SCHEDULER_add_with_priority (sched,
925                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
926                                                   &delayed_restart_task,
927                                                   NULL);
928         }
929 #if DEBUG_ARM
930       else
931         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932                     "Service `%s' terminated with status %s/%d\n",
933                     pos->name, statstr, statcode);
934 #endif
935       prev = pos;
936     }
937   if (in_shutdown)
938     clean_up_running ();
939   if ( (running == NULL) &&
940        (in_shutdown) )
941     {
942       GNUNET_SERVER_destroy (server);
943       GNUNET_SIGNAL_handler_uninstall (shc_chld);
944       shc_chld = NULL;
945     }
946   else
947     {
948       child_death_task =
949         GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, pr,
950                                         &maint_child_death, NULL);
951     }
952 }
953
954
955 /**
956  * List of handlers for the messages understood by this service.
957  */
958 static struct GNUNET_SERVER_MessageHandler handlers[] = {
959   {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
960   {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
961   {NULL, NULL, 0, 0}
962 };
963
964 /**
965  * Signal handler called for signals that should cause us to shutdown.
966  */
967 static void
968 sighandler_child_death ()
969 {
970   static char c;
971
972   GNUNET_break (1 == 
973                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
974                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE), &c,
975                                         sizeof (c)));
976 }
977
978
979 /**
980  * Process arm requests.
981  *
982  * @param cls closure
983  * @param s scheduler to use
984  * @param serv the initialized server
985  * @param c configuration to use
986  */
987 static void
988 run (void *cls,
989      struct GNUNET_SCHEDULER_Handle *s,
990      struct GNUNET_SERVER_Handle *serv,
991      const struct GNUNET_CONFIGURATION_Handle *c)
992 {
993   char *defaultservices;
994   char *pos;
995
996   cfg = c;
997   sched = s;
998   server = serv;
999   GNUNET_assert (serv != NULL);
1000   shc_chld = GNUNET_SIGNAL_handler_install (SIGCHLD, &sighandler_child_death);
1001   GNUNET_assert (sigpipe == NULL);
1002   sigpipe = GNUNET_DISK_pipe (GNUNET_NO);
1003   GNUNET_assert (sigpipe != NULL);
1004   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
1005   GNUNET_assert (pr != NULL);
1006   GNUNET_SERVER_ignore_shutdown (serv, GNUNET_YES);
1007   GNUNET_SCHEDULER_add_delayed (sched,
1008                                 GNUNET_TIME_UNIT_FOREVER_REL,
1009                                 &shutdown_task,
1010                                 NULL);
1011   child_death_task =
1012     GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, pr,
1013                                     &maint_child_death, NULL);
1014
1015   if (GNUNET_OK !=
1016       GNUNET_CONFIGURATION_get_value_string (cfg,
1017                                              "ARM",
1018                                              "GLOBAL_PREFIX",
1019                                              &prefix_command))
1020     prefix_command = GNUNET_strdup ("");
1021   /* start default services... */
1022   if (GNUNET_OK ==
1023       GNUNET_CONFIGURATION_get_value_string (cfg,
1024                                              "ARM",
1025                                              "DEFAULTSERVICES",
1026                                              &defaultservices))
1027     {
1028 #if DEBUG_ARM
1029       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1030                   "Starting default services `%s'\n", defaultservices);
1031 #endif
1032       pos = strtok (defaultservices, " ");
1033       while (pos != NULL)
1034         {
1035           start_service (NULL, pos);
1036           pos = strtok (NULL, " ");
1037         }
1038       GNUNET_free (defaultservices);
1039     }
1040   else
1041     {
1042 #if DEBUG_ARM
1043       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1044                   "No default services configured.\n");
1045 #endif
1046     }
1047
1048   /* process client requests */
1049   GNUNET_SERVER_add_handlers (server, handlers);
1050
1051   /* manage services */
1052   GNUNET_SCHEDULER_add_with_priority (sched,
1053                                       GNUNET_SCHEDULER_PRIORITY_IDLE,
1054                                       &config_change_task, NULL);
1055 }
1056
1057
1058 /**
1059  * The main function for the arm service.
1060  *
1061  * @param argc number of arguments from the command line
1062  * @param argv command line arguments
1063  * @return 0 ok, 1 on error
1064  */
1065 int
1066 main (int argc, char *const *argv)
1067 {
1068   return (GNUNET_OK ==
1069           GNUNET_SERVICE_run (argc,
1070                               argv, "arm", GNUNET_YES, &run, NULL)) ? 0 : 1;
1071 }
1072
1073 /* end of gnunet-service-arm.c */