2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 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 #include "gnunet_util_lib.h"
28 #include "gnunet_arm_service.h"
29 #include "gnunet_protocols.h"
33 * How many messages do we queue up at most for optional
34 * notifications to a client? (this can cause notifications
35 * about outgoing messages to be dropped).
37 #define MAX_NOTIFY_QUEUE 1024
41 * List of our services.
47 * Record with information about a listen socket we have open.
49 struct ServiceListeningInfo
52 * This is a linked list.
54 struct ServiceListeningInfo *next;
57 * This is a linked list.
59 struct ServiceListeningInfo *prev;
62 * Address this socket is listening on.
64 struct sockaddr *service_addr;
67 * Service this listen socket is for.
69 struct ServiceList *sl;
72 * Number of bytes in 'service_addr'
74 socklen_t service_addr_len;
77 * Our listening socket.
79 struct GNUNET_NETWORK_Handle *listen_socket;
82 * Task doing the accepting.
84 GNUNET_SCHEDULER_TaskIdentifier accept_task;
90 * List of our services.
95 * This is a doubly-linked list.
97 struct ServiceList *next;
100 * This is a doubly-linked list.
102 struct ServiceList *prev;
105 * Linked list of listen sockets associated with this service.
107 struct ServiceListeningInfo *listen_head;
110 * Linked list of listen sockets associated with this service.
112 struct ServiceListeningInfo *listen_tail;
115 * Name of the service.
120 * Name of the binary used.
125 * Name of the configuration file used.
130 * Client to notify upon kill completion (waitpid), NULL
131 * if we should simply restart the process.
133 struct GNUNET_SERVER_Client *killing_client;
136 * ID of the request that killed the service (for reporting back).
138 uint64_t killing_client_request_id;
141 * Process structure pointer of the child.
143 struct GNUNET_OS_Process *proc;
146 * Process exponential backoff time
148 struct GNUNET_TIME_Relative backoff;
151 * Absolute time at which the process is scheduled to restart in case of death
153 struct GNUNET_TIME_Absolute restart_at;
156 * Time we asked the service to shut down (used to calculate time it took
157 * the service to terminate).
159 struct GNUNET_TIME_Absolute killed_at;
162 * Is this service to be started by default (or did a client tell us explicitly
163 * to start it)? #GNUNET_NO if the service is started only upon 'accept' on a
164 * listen socket or possibly explicitly by a client changing the value.
169 * Should we use pipes to signal this process? (YES for Java binaries and if we
176 * List of running services.
178 static struct ServiceList *running_head;
181 * List of running services.
183 static struct ServiceList *running_tail;
188 static const struct GNUNET_CONFIGURATION_Handle *cfg;
191 * Command to prepend to each actual command.
193 static char *prefix_command;
196 * Option to append to each actual command.
198 static char *final_option;
201 * ID of task called whenever we get a SIGCHILD.
203 static GNUNET_SCHEDULER_TaskIdentifier child_death_task;
206 * ID of task called whenever the timeout for restarting a child
209 static GNUNET_SCHEDULER_TaskIdentifier child_restart_task;
212 * Pipe used to communicate shutdown via signal.
214 static struct GNUNET_DISK_PipeHandle *sigpipe;
217 * Are we in shutdown mode?
219 static int in_shutdown;
222 * Are we starting user services?
224 static int start_user = GNUNET_YES;
227 * Are we starting system services?
229 static int start_system = GNUNET_YES;
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 * Context for notifications we need to send to our clients.
246 static struct GNUNET_SERVER_NotificationContext *notifier;
250 * Transmit a status result message.
252 * @param cls a `unit16_t *` with message type
253 * @param size number of bytes available in @a buf
254 * @param buf where to copy the message, NULL on error
255 * @return number of bytes copied to @a buf
258 write_result (void *cls, size_t size, void *buf)
260 struct GNUNET_ARM_ResultMessage *msg = cls;
265 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
266 _("Could not send status result to client\n"));
268 return 0; /* error, not much we can do */
270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
271 "Sending status response %u to client\n",
272 (unsigned int) msg->result);
273 msize = msg->arm_msg.header.size;
274 GNUNET_assert (size >= msize);
275 msg->arm_msg.header.size = htons (msg->arm_msg.header.size);
276 msg->arm_msg.header.type = htons (msg->arm_msg.header.type);
277 msg->result = htonl (msg->result);
278 msg->arm_msg.request_id = GNUNET_htonll (msg->arm_msg.request_id);
279 memcpy (buf, msg, msize);
286 * Transmit the list of running services.
288 * @param cls pointer to `struct GNUNET_ARM_ListResultMessage` with the message
289 * @param size number of bytes available in @a buf
290 * @param buf where to copy the message, NULL on error
291 * @return number of bytes copied to @a buf
294 write_list_result (void *cls, size_t size, void *buf)
296 struct GNUNET_ARM_ListResultMessage *msg = cls;
301 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
302 _("Could not send list result to client\n"));
304 return 0; /* error, not much we can do */
307 rslt_size = msg->arm_msg.header.size;
308 GNUNET_assert (size >= rslt_size);
309 msg->arm_msg.header.size = htons (msg->arm_msg.header.size);
310 msg->arm_msg.header.type = htons (msg->arm_msg.header.type);
311 msg->arm_msg.request_id = GNUNET_htonll (msg->arm_msg.request_id);
312 msg->count = htons (msg->count);
314 memcpy (buf, msg, rslt_size);
321 * Signal our client that we will start or stop the
324 * @param client who is being signalled
325 * @param name name of the service
326 * @param request_id id of the request that is being responded to.
327 * @param result message type to send
328 * @return NULL if it was not found
331 signal_result (struct GNUNET_SERVER_Client *client,
334 enum GNUNET_ARM_Result result)
336 struct GNUNET_ARM_ResultMessage *msg;
339 msize = sizeof (struct GNUNET_ARM_ResultMessage);
340 msg = GNUNET_malloc (msize);
341 msg->arm_msg.header.size = msize;
342 msg->arm_msg.header.type = GNUNET_MESSAGE_TYPE_ARM_RESULT;
343 msg->result = result;
344 msg->arm_msg.request_id = request_id;
346 GNUNET_SERVER_notify_transmit_ready (client, msize,
347 GNUNET_TIME_UNIT_FOREVER_REL,
353 * Tell all clients about status change of a service.
355 * @param name name of the service
356 * @param status message type to send
357 * @param unicast if not NULL, send to this client only.
358 * otherwise, send to all clients in the notifier
361 broadcast_status (const char *name,
362 enum GNUNET_ARM_ServiceStatus status,
363 struct GNUNET_SERVER_Client *unicast)
365 struct GNUNET_ARM_StatusMessage *msg;
368 if (NULL == notifier)
370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
371 "Sending status %u of service `%s' to client\n",
372 (unsigned int) status, name);
373 namelen = strlen (name);
374 msg = GNUNET_malloc (sizeof (struct GNUNET_ARM_StatusMessage) + namelen + 1);
375 msg->header.size = htons (sizeof (struct GNUNET_ARM_StatusMessage) + namelen + 1);
376 msg->header.type = htons (GNUNET_MESSAGE_TYPE_ARM_STATUS);
377 msg->status = htonl ((uint32_t) (status));
378 memcpy ((char *) &msg[1], name, namelen + 1);
381 GNUNET_SERVER_notification_context_broadcast (notifier,
382 (struct GNUNET_MessageHeader *) msg, GNUNET_YES);
384 GNUNET_SERVER_notification_context_unicast (notifier, unicast,
385 (const struct GNUNET_MessageHeader *) msg, GNUNET_NO);
391 * Actually start the process for the given service.
393 * @param sl identifies service to start
394 * @param client that asked to start the service (may be NULL)
395 * @param request_id id of the request in response to which the process is
396 * being started. 0 if starting was not requested.
399 start_process (struct ServiceList *sl,
400 struct GNUNET_SERVER_Client *client,
411 struct ServiceListeningInfo *sli;
417 /* calculate listen socket list */
420 for (sli = sl->listen_head; NULL != sli; sli = sli->next)
422 GNUNET_array_append (lsocks, ls,
423 GNUNET_NETWORK_get_fd (sli->listen_socket));
424 if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
426 GNUNET_SCHEDULER_cancel (sli->accept_task);
427 sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
431 GNUNET_array_append (lsocks, ls, INVALID_SOCKET);
433 GNUNET_array_append (lsocks, ls, -1);
436 /* obtain configuration */
438 GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "PREFIX",
440 loprefix = GNUNET_strdup (prefix_command);
442 GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "OPTIONS",
445 options = GNUNET_strdup (final_option);
446 if (NULL == strstr (options, "%"))
448 /* replace '{}' with service name */
449 while (NULL != (optpos = strstr (options, "{}")))
453 GNUNET_asprintf (&optpos, options, sl->name);
454 GNUNET_free (options);
457 /* replace '$PATH' with value associated with "PATH" */
458 while (NULL != (optpos = strstr (options, "$")))
461 while (isupper ((unsigned char) *optend))
470 GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
472 val = GNUNET_strdup ("");
474 GNUNET_asprintf (&optpos, "%s%s%c%s", options, val, b, next);
475 GNUNET_free (options);
481 use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "DEBUG");
483 /* actually start process */
484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485 "Starting service `%s' using binary `%s' and configuration `%s'\n",
486 sl->name, sl->binary, sl->config);
487 binary = GNUNET_OS_get_libexec_binary_path (sl->binary);
488 GNUNET_asprintf ("edbinary,
492 GNUNET_assert (NULL == sl->proc);
493 if (GNUNET_YES == use_debug)
495 if (NULL == sl->config)
497 GNUNET_OS_start_process_s (sl->pipe_control,
498 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
499 lsocks, loprefix, quotedbinary, "-L",
500 "DEBUG", options, NULL);
503 GNUNET_OS_start_process_s (sl->pipe_control,
504 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
505 lsocks, loprefix, quotedbinary, "-c",
507 "DEBUG", options, NULL);
511 if (NULL == sl->config)
513 GNUNET_OS_start_process_s (sl->pipe_control,
514 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
515 lsocks, loprefix, quotedbinary,
519 GNUNET_OS_start_process_s (sl->pipe_control,
520 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
521 lsocks, loprefix, quotedbinary, "-c",
522 sl->config, options, NULL);
524 GNUNET_free (binary);
525 GNUNET_free (quotedbinary);
526 if (sl->proc == NULL)
528 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
529 _("Failed to start service `%s'\n"),
532 signal_result (client,
535 GNUNET_ARM_RESULT_START_FAILED);
539 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
540 _("Starting service `%s'\n"),
542 broadcast_status (sl->name, GNUNET_ARM_SERVICE_STARTING, NULL);
544 signal_result (client, sl->name, request_id, GNUNET_ARM_RESULT_STARTING);
547 GNUNET_free (loprefix);
548 GNUNET_free (options);
549 GNUNET_array_grow (lsocks, ls, 0);
554 * Find the process with the given service
555 * name in the given list and return it.
557 * @param name which service entry to look up
558 * @return NULL if it was not found
560 static struct ServiceList *
561 find_service (const char *name)
563 struct ServiceList *sl;
568 if (0 == strcasecmp (sl->name, name))
577 * First connection has come to the listening socket associated with the service,
578 * create the service in order to relay the incoming connection to it
580 * @param cls callback data, `struct ServiceListeningInfo` describing a listen socket
584 accept_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
586 struct ServiceListeningInfo *sli = cls;
587 struct ServiceList *sl = sli->sl;
589 sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
590 GNUNET_assert (GNUNET_NO == in_shutdown);
591 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
593 start_process (sl, NULL, 0);
598 * Creating a listening socket for each of the service's addresses and
599 * wait for the first incoming connection to it
601 * @param sa address associated with the service
602 * @param addr_len length of @a sa
603 * @param sl service entry for the service in question
606 create_listen_socket (struct sockaddr *sa, socklen_t addr_len,
607 struct ServiceList *sl)
610 struct GNUNET_NETWORK_Handle *sock;
611 struct ServiceListeningInfo *sli;
617 switch (sa->sa_family)
620 sock = GNUNET_NETWORK_socket_create (PF_INET, SOCK_STREAM, 0);
623 sock = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
626 if (strcmp (GNUNET_a2s (sa, addr_len), "@") == 0) /* Do not bind to blank UNIX path! */
628 sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
633 errno = EAFNOSUPPORT;
638 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
639 _("Unable to create socket for service `%s': %s\n"),
640 sl->name, STRERROR (errno));
644 if (GNUNET_NETWORK_socket_setsockopt
645 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
646 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
649 if ((sa->sa_family == AF_INET6) &&
650 (GNUNET_NETWORK_socket_setsockopt
651 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
652 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
657 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) sa, addr_len))
659 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
661 ("Unable to bind listening socket for service `%s' to address `%s': %s\n"),
662 sl->name, GNUNET_a2s (sa, addr_len), STRERROR (errno));
663 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
668 if ((AF_UNIX == sa->sa_family)
670 /* Permission settings are not required when abstract sockets are used */
671 && ('\0' != ((const struct sockaddr_un *)sa)->sun_path[0])
676 GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name,
679 GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name,
681 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sa)->sun_path,
687 if (GNUNET_NETWORK_socket_listen (sock, 5) != GNUNET_OK)
689 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
690 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
694 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
695 _("ARM now monitors connections to service `%s' at `%s'\n"),
696 sl->name, GNUNET_a2s (sa, addr_len));
697 sli = GNUNET_new (struct ServiceListeningInfo);
698 sli->service_addr = sa;
699 sli->service_addr_len = addr_len;
700 sli->listen_socket = sock;
703 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
704 &accept_connection, sli);
705 GNUNET_CONTAINER_DLL_insert (sl->listen_head, sl->listen_tail, sli);
710 * Remove and free an entry in the service list. Listen sockets
711 * must have already been cleaned up. Only to be called during shutdown.
713 * @param sl entry to free
716 free_service (struct ServiceList *sl)
718 GNUNET_assert (GNUNET_YES == in_shutdown);
719 GNUNET_CONTAINER_DLL_remove (running_head, running_tail, sl);
720 GNUNET_assert (NULL == sl->listen_head);
721 GNUNET_free_non_null (sl->config);
722 GNUNET_free_non_null (sl->binary);
723 GNUNET_free (sl->name);
729 * Handle START-message.
731 * @param cls closure (always NULL)
732 * @param client identification of the client
733 * @param message the actual message
734 * @return #GNUNET_OK to keep the connection open,
735 * #GNUNET_SYSERR to close it (signal serious error)
738 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
739 const struct GNUNET_MessageHeader *message)
741 const char *servicename;
742 struct ServiceList *sl;
745 struct GNUNET_ARM_Message *amsg;
747 amsg = (struct GNUNET_ARM_Message *) message;
748 request_id = GNUNET_ntohll (amsg->request_id);
749 size = ntohs (amsg->header.size);
750 size -= sizeof (struct GNUNET_ARM_Message);
751 servicename = (const char *) &amsg[1];
752 if ((size == 0) || (servicename[size - 1] != '\0'))
755 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
758 if (GNUNET_YES == in_shutdown)
760 signal_result (client, servicename, request_id,
761 GNUNET_ARM_RESULT_IN_SHUTDOWN);
762 GNUNET_SERVER_receive_done (client, GNUNET_OK);
765 sl = find_service (servicename);
768 signal_result (client, servicename, request_id,
769 GNUNET_ARM_RESULT_IS_NOT_KNOWN);
770 GNUNET_SERVER_receive_done (client, GNUNET_OK);
773 sl->is_default = GNUNET_YES;
774 if (NULL != sl->proc)
776 signal_result (client, servicename, request_id,
777 GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
778 GNUNET_SERVER_receive_done (client, GNUNET_OK);
781 start_process (sl, client, request_id);
782 GNUNET_SERVER_receive_done (client, GNUNET_OK);
787 * Start a shutdown sequence.
789 * @param cls closure (refers to service)
790 * @param tc task context
793 trigger_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Triggering shutdown\n");
796 GNUNET_SCHEDULER_shutdown ();
801 * Handle STOP-message.
803 * @param cls closure (always NULL)
804 * @param client identification of the client
805 * @param message the actual message
806 * @return #GNUNET_OK to keep the connection open,
807 * #GNUNET_SYSERR to close it (signal serious error)
810 handle_stop (void *cls, struct GNUNET_SERVER_Client *client,
811 const struct GNUNET_MessageHeader *message)
813 struct ServiceList *sl;
814 const char *servicename;
817 struct GNUNET_ARM_Message *amsg;
819 amsg = (struct GNUNET_ARM_Message *) message;
820 request_id = GNUNET_ntohll (amsg->request_id);
821 size = ntohs (amsg->header.size);
822 size -= sizeof (struct GNUNET_ARM_Message);
823 servicename = (const char *) &amsg[1];
824 if ((size == 0) || (servicename[size - 1] != '\0'))
827 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
830 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
831 _("Preparing to stop `%s'\n"),
833 if (0 == strcasecmp (servicename, "arm"))
835 broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL);
836 signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_STOPPING);
837 GNUNET_SERVER_client_persist_ (client);
838 GNUNET_SCHEDULER_add_now (trigger_shutdown, NULL);
839 GNUNET_SERVER_receive_done (client, GNUNET_OK);
842 sl = find_service (servicename);
845 signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_IS_NOT_KNOWN);
846 GNUNET_SERVER_receive_done (client, GNUNET_OK);
849 sl->is_default = GNUNET_NO;
850 if (GNUNET_YES == in_shutdown)
852 /* shutdown in progress */
853 signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_IN_SHUTDOWN);
854 GNUNET_SERVER_receive_done (client, GNUNET_OK);
857 if (NULL != sl->killing_client)
859 /* killing already in progress */
860 signal_result (client, servicename, request_id,
861 GNUNET_ARM_RESULT_IS_STOPPING_ALREADY);
862 GNUNET_SERVER_receive_done (client, GNUNET_OK);
865 if (NULL == sl->proc)
867 /* process is down */
868 signal_result (client, servicename, request_id,
869 GNUNET_ARM_RESULT_IS_STOPPED_ALREADY);
870 GNUNET_SERVER_receive_done (client, GNUNET_OK);
873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
874 "Sending kill signal to service `%s', waiting for process to die.\n",
876 broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL);
877 /* no signal_start - only when it's STOPPED */
878 sl->killed_at = GNUNET_TIME_absolute_get ();
879 if (0 != GNUNET_OS_process_kill (sl->proc, GNUNET_TERM_SIG))
880 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
881 sl->killing_client = client;
882 sl->killing_client_request_id = request_id;
883 GNUNET_SERVER_client_keep (client);
884 GNUNET_SERVER_receive_done (client, GNUNET_OK);
889 * Handle LIST-message.
891 * @param cls closure (always NULL)
892 * @param client identification of the client
893 * @param message the actual message
896 handle_list (void *cls, struct GNUNET_SERVER_Client *client,
897 const struct GNUNET_MessageHeader *message)
899 struct GNUNET_ARM_ListResultMessage *msg;
900 struct GNUNET_ARM_Message *request;
901 size_t string_list_size;
903 struct ServiceList *sl;
909 request = (struct GNUNET_ARM_Message *) message;
910 GNUNET_break (0 == ntohl (request->reserved));
912 string_list_size = 0;
913 /* first count the running processes get their name's size */
914 for (sl = running_head; NULL != sl; sl = sl->next)
916 if (NULL != sl->proc)
918 string_list_size += strlen (sl->name);
919 string_list_size += strlen (sl->binary);
920 string_list_size += 4;
925 total_size = sizeof (struct GNUNET_ARM_ListResultMessage)
927 msg = GNUNET_malloc (total_size);
928 msg->arm_msg.header.size = total_size;
929 msg->arm_msg.header.type = GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT;
930 msg->arm_msg.reserved = htonl (0);
931 msg->arm_msg.request_id = GNUNET_ntohll (request->request_id);
934 char *pos = (char *)&msg[1];
935 for (sl = running_head; NULL != sl; sl = sl->next)
937 if (NULL != sl->proc)
939 size_t s = strlen (sl->name) + strlen (sl->binary) + 4;
940 GNUNET_snprintf (pos, s, "%s (%s)", sl->name, sl->binary);
944 GNUNET_SERVER_notify_transmit_ready (client,
946 GNUNET_TIME_UNIT_FOREVER_REL,
947 &write_list_result, msg);
948 GNUNET_SERVER_receive_done (client, GNUNET_OK);
953 * We are done with everything. Stop remaining
954 * tasks, signal handler and the server.
959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last shutdown phase\n");
960 if (NULL != notifier)
962 GNUNET_SERVER_notification_context_destroy (notifier);
967 GNUNET_SERVER_destroy (server);
970 if (GNUNET_SCHEDULER_NO_TASK != child_death_task)
972 GNUNET_SCHEDULER_cancel (child_death_task);
973 child_death_task = GNUNET_SCHEDULER_NO_TASK;
979 * Count how many services are still active.
981 * @param running_head list of services
982 * @return number of active services found
985 list_count (struct ServiceList *running_head)
987 struct ServiceList *i;
988 unsigned int res = 0;
990 for (res = 0, i = running_head; i; i = i->next, res++)
991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
999 * Task run for shutdown.
1001 * @param cls closure, NULL if we need to self-restart
1005 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1007 struct ServiceList *pos;
1008 struct ServiceList *nxt;
1009 struct ServiceListeningInfo *sli;
1011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1012 "First shutdown phase\n");
1013 if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1015 GNUNET_SCHEDULER_cancel (child_restart_task);
1016 child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1018 in_shutdown = GNUNET_YES;
1019 /* first, stop listening */
1020 for (pos = running_head; NULL != pos; pos = pos->next)
1022 while (NULL != (sli = pos->listen_head))
1024 GNUNET_CONTAINER_DLL_remove (pos->listen_head,
1025 pos->listen_tail, sli);
1026 if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
1028 GNUNET_SCHEDULER_cancel (sli->accept_task);
1029 sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
1031 GNUNET_break (GNUNET_OK ==
1032 GNUNET_NETWORK_socket_close (sli->listen_socket));
1033 GNUNET_free (sli->service_addr);
1037 /* then, shutdown all existing service processes */
1039 while (NULL != (pos = nxt))
1042 if (pos->proc != NULL)
1044 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1045 "Stopping service `%s'\n",
1047 pos->killed_at = GNUNET_TIME_absolute_get ();
1048 if (0 != GNUNET_OS_process_kill (pos->proc, GNUNET_TERM_SIG))
1049 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
1056 /* finally, should all service processes be already gone, terminate for real */
1057 if (running_head == NULL)
1060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061 "Delaying shutdown, have %u childs still running\n",
1062 list_count (running_head));
1067 * Task run whenever it is time to restart a child that died.
1069 * @param cls closure, always NULL
1073 delayed_restart_task (void *cls,
1074 const struct GNUNET_SCHEDULER_TaskContext *tc)
1076 struct ServiceList *sl;
1077 struct GNUNET_TIME_Relative lowestRestartDelay;
1078 struct ServiceListeningInfo *sli;
1080 child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1081 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1083 GNUNET_assert (GNUNET_NO == in_shutdown);
1084 lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
1086 /* check for services that need to be restarted due to
1087 * configuration changes or because the last restart failed */
1088 for (sl = running_head; NULL != sl; sl = sl->next)
1090 if (NULL != sl->proc)
1092 /* service is currently not running */
1093 if (0 == GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value_us)
1095 /* restart is now allowed */
1098 /* process should run by default, start immediately */
1099 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1100 _("Restarting service `%s'.\n"), sl->name);
1101 start_process (sl, NULL, 0);
1105 /* process is run on-demand, ensure it is re-started if there is demand */
1106 for (sli = sl->listen_head; NULL != sli; sli = sli->next)
1107 if (GNUNET_SCHEDULER_NO_TASK == sli->accept_task)
1109 /* accept was actually paused, so start it again */
1111 GNUNET_SCHEDULER_add_read_net
1112 (GNUNET_TIME_UNIT_FOREVER_REL, sli->listen_socket,
1113 &accept_connection, sli);
1119 /* update calculation for earliest time to reactivate a service */
1120 lowestRestartDelay =
1121 GNUNET_TIME_relative_min (lowestRestartDelay,
1122 GNUNET_TIME_absolute_get_remaining
1126 if (lowestRestartDelay.rel_value_us != GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1129 "Will restart process in %s\n",
1130 GNUNET_STRINGS_relative_time_to_string (lowestRestartDelay, GNUNET_YES));
1131 child_restart_task =
1132 GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay,
1133 GNUNET_SCHEDULER_PRIORITY_IDLE,
1134 &delayed_restart_task, NULL);
1140 * Task triggered whenever we receive a SIGCHLD (child
1143 * @param cls closure, NULL if we need to self-restart
1147 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1149 struct ServiceList *pos;
1150 struct ServiceList *next;
1151 struct ServiceListeningInfo *sli;
1152 const char *statstr;
1156 enum GNUNET_OS_ProcessStatusType statusType;
1157 unsigned long statusCode;
1158 const struct GNUNET_DISK_FileHandle *pr;
1160 pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
1161 child_death_task = GNUNET_SCHEDULER_NO_TASK;
1162 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1164 /* shutdown scheduled us, ignore! */
1166 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1167 pr, &maint_child_death, NULL);
1170 /* consume the signal */
1171 GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
1173 /* check for services that died (WAITPID) */
1174 next = running_head;
1175 while (NULL != (pos = next))
1179 if (pos->proc == NULL)
1181 if (GNUNET_YES == in_shutdown)
1185 if ((GNUNET_SYSERR ==
1187 GNUNET_OS_process_status (pos->proc, &statusType, &statusCode)))
1188 || ((ret == GNUNET_NO) || (statusType == GNUNET_OS_PROCESS_STOPPED)
1189 || (statusType == GNUNET_OS_PROCESS_RUNNING)))
1191 if (statusType == GNUNET_OS_PROCESS_EXITED)
1193 statstr = _( /* process termination method */ "exit");
1194 statcode = statusCode;
1196 else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
1198 statstr = _( /* process termination method */ "signal");
1199 statcode = statusCode;
1203 statstr = _( /* process termination method */ "unknown");
1206 if (0 != pos->killed_at.abs_value_us)
1208 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1209 _("Service `%s' took %s to terminate\n"),
1211 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->killed_at), GNUNET_YES));
1213 GNUNET_OS_process_destroy (pos->proc);
1215 broadcast_status (pos->name, GNUNET_ARM_SERVICE_STOPPED, NULL);
1216 if (NULL != pos->killing_client)
1218 signal_result (pos->killing_client, pos->name,
1219 pos->killing_client_request_id, GNUNET_ARM_RESULT_STOPPED);
1220 GNUNET_SERVER_client_drop (pos->killing_client);
1221 pos->killing_client = NULL;
1222 pos->killing_client_request_id = 0;
1224 if (GNUNET_YES != in_shutdown)
1226 if ((statusType == GNUNET_OS_PROCESS_EXITED) && (statcode == 0))
1228 /* process terminated normally, allow restart at any time */
1229 pos->restart_at.abs_value_us = 0;
1230 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1231 _("Service `%s' terminated normally, will restart at any time\n"),
1233 /* process can still be re-started on-demand, ensure it is re-started if there is demand */
1234 for (sli = pos->listen_head; NULL != sli; sli = sli->next)
1236 GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sli->accept_task);
1238 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1239 sli->listen_socket, &accept_connection, sli);
1244 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1245 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1246 _("Service `%s' terminated with status %s/%d, will restart in %s\n"),
1247 pos->name, statstr, statcode,
1248 GNUNET_STRINGS_relative_time_to_string (pos->backoff, GNUNET_YES));
1249 /* schedule restart */
1250 pos->restart_at = GNUNET_TIME_relative_to_absolute (pos->backoff);
1251 pos->backoff = GNUNET_TIME_STD_BACKOFF (pos->backoff);
1252 if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1253 GNUNET_SCHEDULER_cancel (child_restart_task);
1254 child_restart_task = GNUNET_SCHEDULER_add_with_priority (
1255 GNUNET_SCHEDULER_PRIORITY_IDLE, &delayed_restart_task, NULL);
1263 child_death_task = GNUNET_SCHEDULER_add_read_file (
1264 GNUNET_TIME_UNIT_FOREVER_REL, pr, &maint_child_death, NULL);
1265 if ((NULL == running_head) && (GNUNET_YES == in_shutdown))
1267 else if (GNUNET_YES == in_shutdown)
1268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1269 "Delaying shutdown after child's death, still have %u children\n",
1270 list_count (running_head));
1276 * Signal handler called for SIGCHLD. Triggers the
1277 * respective handler by writing to the trigger pipe.
1280 sighandler_child_death ()
1283 int old_errno = errno; /* back-up errno */
1286 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
1287 (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
1289 errno = old_errno; /* restore errno */
1294 * Setup our service record for the given section in the configuration file
1295 * (assuming the section is for a service).
1298 * @param section a section in the configuration file
1299 * @return #GNUNET_OK (continue)
1302 setup_service (void *cls, const char *section)
1304 struct ServiceList *sl;
1308 struct sockaddr **addrs;
1309 socklen_t *addr_lens;
1313 if (strcasecmp (section, "arm") == 0)
1316 GNUNET_CONFIGURATION_get_value_string (cfg, section, "BINARY", &binary))
1318 /* not a service section */
1322 GNUNET_CONFIGURATION_have_value (cfg, section, "USER_SERVICE")) &&
1324 GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "USER_SERVICE")))
1326 if (GNUNET_NO == start_user)
1328 GNUNET_free (binary);
1329 return; /* user service, and we don't deal with those */
1334 if (GNUNET_NO == start_system)
1336 GNUNET_free (binary);
1337 return; /* system service, and we don't deal with those */
1340 sl = find_service (section);
1343 /* got the same section twice!? */
1345 GNUNET_free (binary);
1350 GNUNET_CONFIGURATION_get_value_filename (cfg, section, "CONFIG",
1353 GNUNET_CONFIGURATION_get_value_filename (cfg, "PATHS", "DEFAULTCONFIG",
1355 (0 != STAT (config, &sbuf)))
1359 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1362 GNUNET_free (config);
1366 sl = GNUNET_new (struct ServiceList);
1367 sl->name = GNUNET_strdup (section);
1368 sl->binary = binary;
1369 sl->config = config;
1370 sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1371 sl->restart_at = GNUNET_TIME_UNIT_FOREVER_ABS;
1373 sl->pipe_control = GNUNET_YES;
1375 if (GNUNET_CONFIGURATION_have_value (cfg, section, "PIPECONTROL"))
1376 sl->pipe_control = GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "PIPECONTROL");
1378 GNUNET_CONTAINER_DLL_insert (running_head, running_tail, sl);
1381 GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "AUTOSTART"))
1383 if (0 >= (ret = GNUNET_SERVICE_get_server_addresses (section, cfg,
1384 &addrs, &addr_lens)))
1386 /* this will free (or capture) addrs[i] */
1387 for (i = 0; i < ret; i++)
1388 create_listen_socket (addrs[i], addr_lens[i], sl);
1389 GNUNET_free (addrs);
1390 GNUNET_free (addr_lens);
1395 * A client connected, add it to the notification context.
1397 * @param cls closure
1398 * @param client identification of the client
1401 handle_client_connecting (void *cls, struct GNUNET_SERVER_Client *client)
1403 /* All clients are considered to be of the "monitor" kind
1404 * (that is, they don't affect ARM shutdown).
1407 GNUNET_SERVER_client_mark_monitor (client);
1412 * Handle MONITOR-message.
1414 * @param cls closure (always NULL)
1415 * @param client identification of the client
1416 * @param message the actual message
1417 * @return #GNUNET_OK to keep the connection open,
1418 * #GNUNET_SYSERR to close it (signal serious error)
1421 handle_monitor (void *cls, struct GNUNET_SERVER_Client *client,
1422 const struct GNUNET_MessageHeader *message)
1424 /* Removal is handled by the server implementation, internally. */
1425 if ((NULL != client) && (NULL != notifier))
1427 GNUNET_SERVER_notification_context_add (notifier, client);
1428 broadcast_status ("arm", GNUNET_ARM_SERVICE_MONITORING_STARTED, client);
1429 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1435 * Process arm requests.
1437 * @param cls closure
1438 * @param serv the initialized server
1439 * @param c configuration to use
1442 run (void *cls, struct GNUNET_SERVER_Handle *serv,
1443 const struct GNUNET_CONFIGURATION_Handle *c)
1445 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1446 {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
1447 {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
1448 {&handle_monitor, NULL, GNUNET_MESSAGE_TYPE_ARM_MONITOR,
1449 sizeof (struct GNUNET_MessageHeader)},
1450 {&handle_list, NULL, GNUNET_MESSAGE_TYPE_ARM_LIST,
1451 sizeof (struct GNUNET_ARM_Message)},
1454 char *defaultservices;
1456 struct ServiceList *sl;
1460 GNUNET_assert (NULL != serv);
1461 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1465 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1466 GNUNET_DISK_pipe_handle (sigpipe,
1467 GNUNET_DISK_PIPE_END_READ),
1468 &maint_child_death, NULL);
1471 GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_PREFIX",
1473 prefix_command = GNUNET_strdup ("");
1475 GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_POSTFIX",
1477 final_option = GNUNET_strdup ("");
1479 GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "USER_ONLY"))
1481 GNUNET_break (GNUNET_YES == start_user);
1482 start_system = GNUNET_NO;
1485 GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "SYSTEM_ONLY"))
1487 GNUNET_break (GNUNET_YES == start_system);
1488 start_user = GNUNET_NO;
1490 GNUNET_CONFIGURATION_iterate_sections (cfg, &setup_service, NULL);
1492 /* start default services... */
1494 GNUNET_CONFIGURATION_get_value_string (cfg,
1499 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1500 _("Starting default services `%s'\n"),
1502 if (0 < strlen (defaultservices))
1504 for (pos = strtok (defaultservices, " "); NULL != pos;
1505 pos = strtok (NULL, " "))
1507 sl = find_service (pos);
1510 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1511 _("Default service `%s' not configured correctly!\n"),
1515 sl->is_default = GNUNET_YES;
1516 start_process (sl, NULL, 0);
1519 GNUNET_free (defaultservices);
1523 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1524 _("No default services configured, GNUnet will not really start right now.\n"));
1528 GNUNET_SERVER_notification_context_create (server, MAX_NOTIFY_QUEUE);
1529 GNUNET_SERVER_connect_notify (server, handle_client_connecting, NULL);
1530 /* process client requests */
1531 GNUNET_SERVER_add_handlers (server, handlers);
1536 * The main function for the arm service.
1538 * @param argc number of arguments from the command line
1539 * @param argv command line arguments
1540 * @return 0 ok, 1 on error
1543 main (int argc, char *const *argv)
1546 struct GNUNET_SIGNAL_Context *shc_chld;
1548 sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
1549 GNUNET_assert (sigpipe != NULL);
1551 GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
1554 GNUNET_SERVICE_run (argc, argv, "arm",
1555 GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN, &run, NULL)) ? 0 : 1;
1556 GNUNET_SIGNAL_handler_uninstall (shc_chld);
1558 GNUNET_DISK_pipe_close (sigpipe);
1568 * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1570 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
1572 mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1573 mallopt (M_TOP_PAD, 1 * 1024);
1579 /* end of gnunet-service-arm.c */