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