2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file arm/gnunet-service-arm.c
23 * @brief the automated restart manager service
24 * @author Christian Grothoff
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
33 * + install handler for disconnecting clients!?
36 #include "gnunet_util_lib.h"
37 #include "gnunet_protocols.h"
42 * Check for configuration file changes every 5s.
44 #define MAINT_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
47 * Threshold after which exponential backoff shouldn't increase (in ms); 30m
49 #define EXPONENTIAL_BACKOFF_THRESHOLD (1000 * 60 * 30)
52 * List of our services.
58 * List of our services.
63 * This is a doubly-linked list.
65 struct ServiceList *next;
68 * This is a doubly-linked list.
70 struct ServiceList *prev;
73 * Name of the service.
78 * Name of the binary used.
83 * Name of the configuration file used.
88 * Client to notify upon kill completion (waitpid), NULL
89 * if we should simply restart the process.
91 struct GNUNET_SERVER_Client *killing_client;
94 * Process structure pointer of the child.
96 struct GNUNET_OS_Process *proc;
99 * Last time the config of this service was
105 * Process exponential backoff time
107 struct GNUNET_TIME_Relative backoff;
110 * Absolute time at which the process is scheduled to restart in case of death
112 struct GNUNET_TIME_Absolute restartAt;
117 * List of running services.
119 static struct ServiceList *running_head;
122 * List of running services.
124 static struct ServiceList *running_tail;
129 static const struct GNUNET_CONFIGURATION_Handle *cfg;
132 * Command to prepend to each actual command.
134 static char *prefix_command;
137 * Option to append to each actual command.
139 static char *final_option;
142 * ID of task called whenever we get a SIGCHILD.
144 static GNUNET_SCHEDULER_TaskIdentifier child_death_task;
147 * ID of task called whenever the timeout for restarting a child
150 static GNUNET_SCHEDULER_TaskIdentifier child_restart_task;
155 struct ServiceListeningInfo
158 * This is a linked list.
160 struct ServiceListeningInfo *next;
163 * This is a linked list.
165 struct ServiceListeningInfo *prev;
168 * Name of the service being forwarded.
175 struct sockaddr *service_addr;
180 socklen_t service_addr_len;
183 * Our listening socket.
185 struct GNUNET_NETWORK_Handle *listeningSocket;
188 * Task doing the accepting.
190 GNUNET_SCHEDULER_TaskIdentifier acceptTask;
195 * Array with the names of the services started by default.
197 static char **defaultServicesList;
200 * Size of the defaultServicesList array.
202 static unsigned int numDefaultServices;
207 static struct ServiceListeningInfo *serviceListeningInfoList_head;
212 static struct ServiceListeningInfo *serviceListeningInfoList_tail;
216 * Pipe used to communicate shutdown via signal.
218 static struct GNUNET_DISK_PipeHandle *sigpipe;
221 * Reading end of the signal pipe.
223 static const struct GNUNET_DISK_FileHandle *pr;
226 * Are we in shutdown mode?
228 static int in_shutdown;
232 * Handle to our server instance. Our server is a bit special in that
233 * its service is not immediately stopped once we get a shutdown
234 * request (since we need to continue service until all of our child
235 * processes are dead). This handle is used to shut down the server
236 * (and thus trigger process termination) once all child processes are
237 * also dead. A special option in the ARM configuration modifies the
238 * behaviour of the service implementation to not do the shutdown
241 static struct GNUNET_SERVER_Handle *server;
244 #include "do_start_process.c"
248 * Actually start the process for the given service.
250 * @param sl identifies service to start
251 * @param lsocks -1 terminated list of listen sockets to pass (systemd style), or NULL
254 start_process (struct ServiceList *sl, const SOCKTYPE *lsocks)
267 GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "PREFIX",
269 loprefix = GNUNET_strdup (prefix_command);
271 GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "OPTIONS",
274 options = GNUNET_strdup (final_option);
275 if (NULL == strstr (options, "%"))
277 /* replace '{}' with service name */
278 while (NULL != (optpos = strstr (options, "{}")))
282 GNUNET_asprintf (&optpos, options, sl->name);
283 GNUNET_free (options);
286 /* replace '$PATH' with value associated with "PATH" */
287 while (NULL != (optpos = strstr (options, "$")))
290 while (isupper ((unsigned char) *optend))
299 GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", optpos + 1,
301 val = GNUNET_strdup ("");
303 GNUNET_asprintf (&optpos, "%s%s%c%s", options, val, b, next);
304 GNUNET_free (options);
310 use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "DEBUG");
313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
314 "Starting service `%s' using binary `%s' and configuration `%s'\n",
315 sl->name, sl->binary, sl->config);
317 if (GNUNET_YES == use_debug)
319 do_start_process (lsocks, loprefix, sl->binary, "-c", sl->config, "-L",
320 "DEBUG", options, NULL);
323 do_start_process (lsocks, loprefix, sl->binary, "-c", sl->config,
325 if (sl->proc == NULL)
326 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to start service `%s'\n"),
329 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Starting service `%s'\n"), sl->name);
330 GNUNET_free (loprefix);
331 GNUNET_free (options);
336 * Put the default services represented by a space separated string into an array of strings
338 * @param services space separated string of default services
341 addDefaultServicesToList (const char *services)
347 if (strlen (services) == 0)
349 s = GNUNET_strdup (services);
350 token = strtok (s, " ");
351 while (NULL != token)
353 numDefaultServices++;
354 token = strtok (NULL, " ");
358 defaultServicesList = GNUNET_malloc (numDefaultServices * sizeof (char *));
360 s = GNUNET_strdup (services);
361 token = strtok (s, " ");
362 while (NULL != token)
364 defaultServicesList[i++] = GNUNET_strdup (token);
365 token = strtok (NULL, " ");
368 GNUNET_assert (i == numDefaultServices);
373 * Checks whether the serviceName is in the list of default services
375 * @param serviceName string to check its existance in the list
376 * @return GNUNET_YES if the service is started by default
379 isInDefaultList (const char *serviceName)
383 for (i = 0; i < numDefaultServices; i++)
384 if (strcmp (serviceName, defaultServicesList[i]) == 0)
394 stop_listening (const char *serviceName)
396 struct ServiceListeningInfo *pos;
397 struct ServiceListeningInfo *next;
401 next = serviceListeningInfoList_head;
402 while (NULL != (pos = next))
405 if ((serviceName != NULL) && (strcmp (pos->serviceName, serviceName) != 0))
407 if (pos->acceptTask != GNUNET_SCHEDULER_NO_TASK)
408 GNUNET_SCHEDULER_cancel (pos->acceptTask);
409 GNUNET_break (GNUNET_OK ==
410 GNUNET_NETWORK_socket_close (pos->listeningSocket));
411 GNUNET_CONTAINER_DLL_remove (serviceListeningInfoList_head,
412 serviceListeningInfoList_tail, pos);
413 GNUNET_free (pos->serviceName);
414 GNUNET_free (pos->service_addr);
423 * Transmit a status result message.
425 * @param cls pointer to "unit16_t*" with message type
426 * @param size number of bytes available in buf
427 * @param buf where to copy the message, NULL on error
428 * @return number of bytes copied to buf
431 write_result (void *cls, size_t size, void *buf)
434 struct GNUNET_MessageHeader *msg;
438 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
439 _("Could not send status result to client\n"));
440 return 0; /* error, not much we can do */
443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending status response %u to client\n",
444 (unsigned int) *res);
446 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
448 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
449 msg->type = htons (*res);
451 return sizeof (struct GNUNET_MessageHeader);
456 * Signal our client that we will start or stop the
459 * @param client who is being signalled
460 * @param name name of the service
461 * @param result message type to send
462 * @return NULL if it was not found
465 signal_result (struct GNUNET_SERVER_Client *client, const char *name,
472 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
473 _("Not sending status result to client: no client known\n"));
477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
478 "Telling client that service `%s' is now %s\n", name,
479 result == GNUNET_MESSAGE_TYPE_ARM_IS_DOWN ? "down" : "up");
481 res = GNUNET_malloc (sizeof (uint16_t));
483 GNUNET_SERVER_notify_transmit_ready (client,
484 sizeof (struct GNUNET_MessageHeader),
485 GNUNET_TIME_UNIT_FOREVER_REL,
491 * Find the process with the given service
492 * name in the given list and return it.
494 * @param name which service entry to look up
495 * @return NULL if it was not found
497 static struct ServiceList *
498 find_service (const char *name)
500 struct ServiceList *pos;
505 if (0 == strcmp (pos->name, name))
514 * Start the specified service.
516 * @param client who is asking for this
517 * @param servicename name of the service to start
518 * @param lsocks -1 terminated list of listen sockets to pass (systemd style), or NULL
519 * @return GNUNET_OK on success, GNUNET_SYSERR on error
522 start_service (struct GNUNET_SERVER_Client *client, const char *servicename,
523 const SOCKTYPE *lsocks)
525 struct ServiceList *sl;
530 if (GNUNET_YES == in_shutdown)
532 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
533 _("ARM is shutting down, service `%s' not started.\n"),
535 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
536 return GNUNET_SYSERR;
538 sl = find_service (servicename);
541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Service `%s' already running.\n"),
543 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UP);
544 return GNUNET_SYSERR;
547 GNUNET_CONFIGURATION_get_value_string (cfg, servicename, "BINARY",
550 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
551 _("Binary implementing service `%s' not known!\n"),
553 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
554 return GNUNET_SYSERR;
557 GNUNET_CONFIGURATION_get_value_filename (cfg, servicename, "CONFIG",
559 (0 != STAT (config, &sbuf)))
561 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
562 _("Configuration file `%s' for service `%s' not known!\n"),
563 config, servicename);
564 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
565 GNUNET_free (binary);
566 GNUNET_free_non_null (config);
567 return GNUNET_SYSERR;
569 (void) stop_listening (servicename);
570 sl = GNUNET_malloc (sizeof (struct ServiceList));
571 sl->name = GNUNET_strdup (servicename);
574 sl->mtime = sbuf.st_mtime;
575 sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
576 sl->restartAt = GNUNET_TIME_UNIT_FOREVER_ABS;
577 GNUNET_CONTAINER_DLL_insert (running_head, running_tail, sl);
578 start_process (sl, lsocks);
580 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UP);
586 * First connection has come to the listening socket associated with the service,
587 * create the service in order to relay the incoming connection to it
589 * @param cls callback data, struct ServiceListeningInfo describing a listen socket
593 acceptConnection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
595 struct ServiceListeningInfo *sli = cls;
596 struct ServiceListeningInfo *pos;
597 struct ServiceListeningInfo *next;
601 sli->acceptTask = GNUNET_SCHEDULER_NO_TASK;
602 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
604 GNUNET_CONTAINER_DLL_remove (serviceListeningInfoList_head,
605 serviceListeningInfoList_tail, sli);
608 next = serviceListeningInfoList_head;
609 while (NULL != (pos = next))
612 if (0 == strcmp (pos->serviceName, sli->serviceName))
614 GNUNET_array_append (lsocks, ls,
615 GNUNET_NETWORK_get_fd (pos->listeningSocket));
616 GNUNET_free (pos->listeningSocket); /* deliberately no closing! */
617 GNUNET_free (pos->service_addr);
618 GNUNET_free (pos->serviceName);
619 GNUNET_SCHEDULER_cancel (pos->acceptTask);
620 GNUNET_CONTAINER_DLL_remove (serviceListeningInfoList_head,
621 serviceListeningInfoList_tail, pos);
625 GNUNET_array_append (lsocks, ls,
626 GNUNET_NETWORK_get_fd (sli->listeningSocket));
627 GNUNET_free (sli->listeningSocket); /* deliberately no closing! */
628 GNUNET_free (sli->service_addr);
630 GNUNET_array_append (lsocks, ls, INVALID_SOCKET);
632 GNUNET_array_append (lsocks, ls, -1);
634 start_service (NULL, sli->serviceName, lsocks);
636 while (lsocks[ls] != -1)
638 GNUNET_break (0 == closesocket (lsocks[ls++]));
640 GNUNET_break (0 == close (lsocks[ls++]));
642 GNUNET_array_grow (lsocks, ls, 0);
643 GNUNET_free (sli->serviceName);
649 * Creating a listening socket for each of the service's addresses and
650 * wait for the first incoming connection to it
652 * @param sa address associated with the service
653 * @param addr_len length of sa
654 * @param serviceName the name of the service in question
657 createListeningSocket (struct sockaddr *sa, socklen_t addr_len,
658 const char *serviceName)
660 const static int on = 1;
661 struct GNUNET_NETWORK_Handle *sock;
662 struct ServiceListeningInfo *serviceListeningInfo;
664 switch (sa->sa_family)
667 sock = GNUNET_NETWORK_socket_create (PF_INET, SOCK_STREAM, 0);
670 sock = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
673 if (strcmp (GNUNET_a2s (sa, addr_len), "@") == 0) /* Do not bind to blank UNIX path! */
675 sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
680 errno = EAFNOSUPPORT;
685 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
686 _("Unable to create socket for service `%s': %s\n"),
687 serviceName, STRERROR (errno));
691 if (GNUNET_NETWORK_socket_setsockopt
692 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
693 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
696 if ((sa->sa_family == AF_INET6) &&
697 (GNUNET_NETWORK_socket_setsockopt
698 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
699 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
703 if (GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) sa, addr_len)
706 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
708 ("Unable to bind listening socket for service `%s' to address `%s': %s\n"),
709 serviceName, GNUNET_a2s (sa, addr_len), STRERROR (errno));
710 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
714 if (GNUNET_NETWORK_socket_listen (sock, 5) != GNUNET_OK)
716 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
717 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
721 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
722 _("ARM now monitors connections to service `%s' at `%s'\n"),
723 serviceName, GNUNET_a2s (sa, addr_len));
724 serviceListeningInfo = GNUNET_malloc (sizeof (struct ServiceListeningInfo));
725 serviceListeningInfo->serviceName = GNUNET_strdup (serviceName);
726 serviceListeningInfo->service_addr = sa;
727 serviceListeningInfo->service_addr_len = addr_len;
728 serviceListeningInfo->listeningSocket = sock;
729 serviceListeningInfo->acceptTask =
730 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
731 &acceptConnection, serviceListeningInfo);
732 GNUNET_CONTAINER_DLL_insert (serviceListeningInfoList_head,
733 serviceListeningInfoList_tail,
734 serviceListeningInfo);
739 * Callback function, checks whether the current tokens are representing a service,
740 * gets its addresses and create listening socket for it.
742 * @param cls callback data, not used
743 * @param section configuration section
744 * @param option configuration option
745 * @param value the option's value
748 checkPortNumberCB (void *cls, const char *section, const char *option,
751 struct sockaddr **addrs;
752 socklen_t *addr_lens;
756 if ((strcasecmp (section, "arm") == 0) ||
757 (strcasecmp (option, "AUTOSTART") != 0) ||
758 (strcasecmp (value, "YES") != 0) ||
759 (isInDefaultList (section) == GNUNET_YES))
763 GNUNET_SERVICE_get_server_addresses (section, cfg, &addrs, &addr_lens)))
765 /* this will free (or capture) addrs[i] */
766 for (i = 0; i < ret; i++)
767 createListeningSocket (addrs[i], addr_lens[i], section);
769 GNUNET_free (addr_lens);
774 * Entry point to the Service Manager
776 * @param configurationHandle configuration to use to get services
779 prepare_services (const struct GNUNET_CONFIGURATION_Handle *configurationHandle)
781 char *defaultServicesString;
783 cfg = configurationHandle;
784 /* Split the default services into a list */
786 GNUNET_CONFIGURATION_get_value_string (cfg, "arm", "DEFAULTSERVICES",
787 &defaultServicesString))
789 addDefaultServicesToList (defaultServicesString);
790 GNUNET_free (defaultServicesString);
792 /* Spot the services from the configuration and create a listening
794 GNUNET_CONFIGURATION_iterate (cfg, &checkPortNumberCB, NULL);
800 * If the configuration file changes, restart tasks that depended on that
803 * @param cls closure, NULL if we need to self-restart
807 config_change_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
809 struct ServiceList *pos;
815 /* FIXME: this test for config change may be a bit too coarse grained */
816 if ((0 == STAT (pos->config, &sbuf)) && (pos->mtime < sbuf.st_mtime) &&
819 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
821 ("Restarting service `%s' due to configuration file change.\n"));
822 if (0 != GNUNET_OS_process_kill (pos->proc, SIGTERM))
823 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
825 pos->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
833 * Remove and free an entry in the service list.
835 * @param pos entry to free
838 free_service (struct ServiceList *pos)
840 GNUNET_CONTAINER_DLL_remove (running_head, running_tail, pos);
841 GNUNET_free_non_null (pos->config);
842 GNUNET_free_non_null (pos->binary);
843 GNUNET_free (pos->name);
849 * Stop the specified service.
851 * @param client who is asking for this
852 * @param servicename name of the service to stop
855 stop_service (struct GNUNET_SERVER_Client *client, const char *servicename)
857 struct ServiceList *pos;
859 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Preparing to stop `%s'\n"),
861 pos = find_service (servicename);
864 if (GNUNET_OK == stop_listening (servicename))
865 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
867 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_UNKNOWN);
868 GNUNET_SERVER_receive_done (client, GNUNET_OK);
871 if (pos->killing_client != NULL)
873 /* killing already in progress */
875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' is already down\n",
878 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
879 GNUNET_SERVER_receive_done (client, GNUNET_OK);
883 if (GNUNET_YES == in_shutdown)
886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887 "Termination request already sent to `%s' (since ARM is in shutdown).\n",
890 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
891 GNUNET_SERVER_receive_done (client, GNUNET_OK);
894 if (pos->proc == NULL)
896 /* process is in delayed restart, simply remove it! */
898 signal_result (client, servicename, GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
899 GNUNET_SERVER_receive_done (client, GNUNET_OK);
903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904 "Sending kill signal to service `%s', waiting for process to die.\n",
907 if (0 != GNUNET_OS_process_kill (pos->proc, SIGTERM))
908 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
909 pos->killing_client = client;
910 GNUNET_SERVER_client_keep (client);
915 * Handle START-message.
917 * @param cls closure (always NULL)
918 * @param client identification of the client
919 * @param message the actual message
920 * @return GNUNET_OK to keep the connection open,
921 * GNUNET_SYSERR to close it (signal serious error)
924 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
925 const struct GNUNET_MessageHeader *message)
927 const char *servicename;
930 size = ntohs (message->size);
931 size -= sizeof (struct GNUNET_MessageHeader);
932 servicename = (const char *) &message[1];
933 if ((size == 0) || (servicename[size - 1] != '\0'))
936 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
939 start_service (client, servicename, NULL);
940 GNUNET_SERVER_receive_done (client, GNUNET_OK);
945 * Handle STOP-message.
947 * @param cls closure (always NULL)
948 * @param client identification of the client
949 * @param message the actual message
950 * @return GNUNET_OK to keep the connection open,
951 * GNUNET_SYSERR to close it (signal serious error)
954 handle_stop (void *cls, struct GNUNET_SERVER_Client *client,
955 const struct GNUNET_MessageHeader *message)
957 const char *servicename;
960 size = ntohs (message->size);
961 size -= sizeof (struct GNUNET_MessageHeader);
962 servicename = (const char *) &message[1];
963 if ((size == 0) || (servicename[size - 1] != '\0'))
966 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
969 stop_service (client, servicename);
974 * Remove all entries for tasks that are not running
975 * (proc = NULL) from the running list (they will no longer
976 * be restarted since we are shutting down).
981 struct ServiceList *pos;
982 struct ServiceList *next;
985 while (NULL != (pos = next))
988 if (pos->proc == NULL)
995 * We are done with everything. Stop remaining
996 * tasks, signal handler and the server.
1003 GNUNET_SERVER_destroy (server);
1006 if (GNUNET_SCHEDULER_NO_TASK != child_death_task)
1008 GNUNET_SCHEDULER_cancel (child_death_task);
1009 child_death_task = GNUNET_SCHEDULER_NO_TASK;
1015 * Task run for shutdown.
1017 * @param cls closure, NULL if we need to self-restart
1021 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1023 struct ServiceList *pos;
1024 struct ServiceList *nxt;
1027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Stopping all services\n"));
1029 if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1031 GNUNET_SCHEDULER_cancel (child_restart_task);
1032 child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1034 in_shutdown = GNUNET_YES;
1035 stop_listening (NULL);
1040 if (pos->proc != NULL)
1042 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Stopping service `%s'\n", pos->name);
1043 if (0 != GNUNET_OS_process_kill (pos->proc, SIGTERM))
1044 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
1052 if (running_head == NULL)
1058 * Task run whenever it is time to restart a child that died.
1060 * @param cls closure, always NULL
1064 delayed_restart_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1066 struct ServiceList *pos;
1067 struct GNUNET_TIME_Relative lowestRestartDelay;
1069 child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1070 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1072 GNUNET_assert (GNUNET_NO == in_shutdown);
1073 lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
1075 /* check for services that need to be restarted due to
1076 * configuration changes or because the last restart failed */
1080 if (pos->proc == NULL)
1082 if (GNUNET_TIME_absolute_get_remaining (pos->restartAt).rel_value == 0)
1084 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Restarting service `%s'.\n"),
1086 start_process (pos, NULL);
1090 lowestRestartDelay =
1091 GNUNET_TIME_relative_min (lowestRestartDelay,
1092 GNUNET_TIME_absolute_get_remaining
1098 if (lowestRestartDelay.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will restart process in %llums\n",
1102 (unsigned long long) lowestRestartDelay.rel_value);
1104 child_restart_task =
1105 GNUNET_SCHEDULER_add_delayed (lowestRestartDelay, &delayed_restart_task,
1112 * Task triggered whenever we receive a SIGCHLD (child
1115 * @param cls closure, NULL if we need to self-restart
1119 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1121 struct ServiceList *pos;
1122 struct ServiceList *next;
1123 const char *statstr;
1127 enum GNUNET_OS_ProcessStatusType statusType;
1128 unsigned long statusCode;
1130 child_death_task = GNUNET_SCHEDULER_NO_TASK;
1131 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1133 /* shutdown scheduled us, ignore! */
1135 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, pr,
1136 &maint_child_death, NULL);
1139 /* consume the signal */
1140 GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
1142 /* check for services that died (WAITPID) */
1143 next = running_head;
1144 while (NULL != (pos = next))
1147 if (pos->proc == NULL)
1149 if ((GNUNET_SYSERR ==
1150 (ret = GNUNET_OS_process_status (pos->proc, &statusType, &statusCode)))
1151 || ((ret == GNUNET_NO) || (statusType == GNUNET_OS_PROCESS_STOPPED) ||
1152 (statusType == GNUNET_OS_PROCESS_RUNNING)))
1155 if (statusType == GNUNET_OS_PROCESS_EXITED)
1157 statstr = _( /* process termination method */ "exit");
1158 statcode = statusCode;
1160 else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
1162 statstr = _( /* process termination method */ "signal");
1163 statcode = statusCode;
1167 statstr = _( /* process termination method */ "unknown");
1170 GNUNET_OS_process_close (pos->proc);
1172 if (NULL != pos->killing_client)
1174 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Service `%s' stopped\n"),
1176 signal_result (pos->killing_client, pos->name,
1177 GNUNET_MESSAGE_TYPE_ARM_IS_DOWN);
1178 GNUNET_SERVER_receive_done (pos->killing_client, GNUNET_OK);
1179 GNUNET_SERVER_client_drop (pos->killing_client);
1183 if (GNUNET_YES != in_shutdown)
1185 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1186 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1188 ("Service `%s' terminated with status %s/%d, will try to restart it!\n"),
1189 pos->name, statstr, statcode);
1190 /* schedule restart */
1191 pos->restartAt = GNUNET_TIME_relative_to_absolute (pos->backoff);
1192 if (pos->backoff.rel_value < EXPONENTIAL_BACKOFF_THRESHOLD)
1193 pos->backoff = GNUNET_TIME_relative_multiply (pos->backoff, 2);
1194 if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1195 GNUNET_SCHEDULER_cancel (child_restart_task);
1196 child_restart_task =
1197 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1198 &delayed_restart_task, NULL);
1202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203 "Service `%s' terminated with status %s/%d\n", pos->name,
1208 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, pr,
1209 &maint_child_death, NULL);
1210 if (GNUNET_YES == in_shutdown)
1211 clean_up_running ();
1212 if ((NULL == running_head) && (GNUNET_YES == in_shutdown))
1218 transmit_shutdown_ack (void *cls, size_t size, void *buf)
1220 struct GNUNET_SERVER_Client *client = cls;
1221 struct GNUNET_MessageHeader *msg;
1223 if (size < sizeof (struct GNUNET_MessageHeader))
1225 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1226 _("Failed to transmit shutdown ACK.\n"));
1227 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1228 return 0; /* client disconnected */
1231 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transmitting shutdown ACK.\n"));
1233 /* Make the connection flushing for the purpose of ACK transmitting,
1234 * needed on W32 to ensure that the message is even received, harmless
1235 * on other platforms... */
1236 GNUNET_break (GNUNET_OK == GNUNET_SERVER_client_disable_corking (client));
1237 msg = (struct GNUNET_MessageHeader *) buf;
1238 msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN_ACK);
1239 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
1240 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1241 GNUNET_SERVER_client_drop (client);
1242 return sizeof (struct GNUNET_MessageHeader);
1247 * Handler for SHUTDOWN message.
1249 * @param cls closure (refers to service)
1250 * @param client identification of the client
1251 * @param message the actual message
1254 handle_shutdown (void *cls, struct GNUNET_SERVER_Client *client,
1255 const struct GNUNET_MessageHeader *message)
1257 GNUNET_SERVER_client_keep (client);
1258 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1259 _("Initiating shutdown as requested by client.\n"));
1260 GNUNET_SERVER_notify_transmit_ready (client,
1261 sizeof (struct GNUNET_MessageHeader),
1262 GNUNET_TIME_UNIT_FOREVER_REL,
1263 &transmit_shutdown_ack, client);
1264 GNUNET_SERVER_client_persist_ (client);
1265 GNUNET_SCHEDULER_shutdown ();
1270 * Signal handler called for SIGCHLD. Triggers the
1271 * respective handler by writing to the trigger pipe.
1274 sighandler_child_death ()
1277 int old_errno = errno; /* back-up errno */
1280 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
1281 (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
1283 errno = old_errno; /* restore errno */
1288 * Process arm requests.
1290 * @param cls closure
1291 * @param serv the initialized server
1292 * @param c configuration to use
1295 run (void *cls, struct GNUNET_SERVER_Handle *serv,
1296 const struct GNUNET_CONFIGURATION_Handle *c)
1298 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1299 {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
1300 {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
1301 {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN,
1302 sizeof (struct GNUNET_MessageHeader)},
1305 char *defaultservices;
1310 GNUNET_assert (serv != NULL);
1311 pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
1312 GNUNET_assert (pr != NULL);
1313 GNUNET_SERVER_ignore_shutdown (serv, GNUNET_YES);
1314 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1317 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, pr,
1318 &maint_child_death, NULL);
1321 GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_PREFIX",
1323 prefix_command = GNUNET_strdup ("");
1325 GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_POSTFIX",
1327 final_option = GNUNET_strdup ("");
1328 /* start default services... */
1330 GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "DEFAULTSERVICES",
1334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting default services `%s'\n",
1337 if (0 < strlen (defaultservices))
1339 pos = strtok (defaultservices, " ");
1342 start_service (NULL, pos, NULL);
1343 pos = strtok (NULL, " ");
1346 GNUNET_free (defaultservices);
1351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No default services configured.\n");
1355 /* create listening sockets for future services */
1356 prepare_services (cfg);
1358 /* process client requests */
1359 GNUNET_SERVER_add_handlers (server, handlers);
1361 /* manage services */
1362 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1363 &config_change_task, NULL);
1368 * The main function for the arm service.
1370 * @param argc number of arguments from the command line
1371 * @param argv command line arguments
1372 * @return 0 ok, 1 on error
1375 main (int argc, char *const *argv)
1378 struct GNUNET_SIGNAL_Context *shc_chld;
1380 sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO);
1381 GNUNET_assert (sigpipe != NULL);
1383 GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
1386 GNUNET_SERVICE_run (argc, argv, "arm", GNUNET_YES, &run, NULL)) ? 0 : 1;
1387 GNUNET_SIGNAL_handler_uninstall (shc_chld);
1389 GNUNET_DISK_pipe_close (sigpipe);
1398 * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1400 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
1402 mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1403 mallopt (M_TOP_PAD, 1 * 1024);
1409 /* end of gnunet-service-arm.c */