10 #include <sys/ioctl.h>
12 #include <sys/socket.h>
18 #include "dinit-log.h"
19 #include "dinit-socket.h"
22 * service.cc - Service management.
23 * See service.h for details.
27 void open_control_socket(bool report_ro_failure = true) noexcept;
28 void setup_external_log() noexcept;
29 extern eventloop_t eventLoop;
31 // Find the requested service by name
32 static service_record * find_service(const std::list<service_record *> & records,
33 const char *name) noexcept
36 list<service_record *>::const_iterator i = records.begin();
37 for ( ; i != records.end(); i++ ) {
38 if (strcmp((*i)->getServiceName().c_str(), name) == 0) {
42 return (service_record *)0;
45 service_record * service_set::find_service(const std::string &name) noexcept
47 return ::find_service(records, name.c_str());
50 void service_set::stopService(const std::string & name) noexcept
52 service_record *record = find_service(name);
53 if (record != nullptr) {
59 // Called when a service has actually stopped; dependents have stopped already, unless this stop
60 // is due to an unexpected process termination.
61 void service_record::stopped() noexcept
63 if (onstart_flags.runs_on_console) {
64 tcsetpgrp(0, getpgrp());
65 discard_console_log_buffer();
71 // If we are a soft dependency of another target, break the acquisition from that target now:
72 for (auto dependent : soft_dpts) {
73 if (dependent->holding_acq) {
74 dependent->holding_acq = false;
79 bool will_restart = (desired_state == service_state_t::STARTED)
80 && services->get_auto_restart();
82 for (auto dependency : depends_on) {
83 // we signal dependencies in case they are waiting for us to stop:
84 dependency->dependent_stopped();
87 service_state = service_state_t::STOPPED;
90 // Desired state is "started".
95 if (socket_fd != -1) {
100 if (start_explicit) {
101 start_explicit = false;
104 else if (required_by == 0) {
105 services->service_inactive(this);
109 logServiceStopped(service_name);
110 notify_listeners(service_event::STOPPED);
113 dasynq::rearm service_child_watcher::status_change(eventloop_t &loop, pid_t child, int status) noexcept
115 base_process_service *sr = service;
118 sr->exit_status = status;
120 // Ok, for a process service, any process death which we didn't rig
121 // ourselves is a bit... unexpected. Probably, the child died because
122 // we asked it to (sr->service_state == STOPPING). But even if
123 // we didn't, there's not much we can do.
125 if (sr->waiting_for_execstat) {
126 // We still don't have an exec() status from the forked child, wait for that
127 // before doing any further processing.
128 return rearm::REMOVE;
131 // Must deregister now since handle_exit_status might result in re-launch:
132 deregister(loop, child);
134 sr->handle_exit_status(status);
135 return rearm::REMOVED;
138 bool service_record::do_auto_restart() noexcept
141 return services->get_auto_restart();
146 void service_record::emergency_stop() noexcept
148 if (! do_auto_restart() && start_explicit) {
149 start_explicit = false;
157 void process_service::handle_exit_status(int exit_status) noexcept
159 bool did_exit = WIFEXITED(exit_status);
160 bool was_signalled = WIFSIGNALED(exit_status);
162 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
164 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
166 else if (was_signalled) {
167 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
171 if (service_state == service_state_t::STARTING) {
172 if (did_exit && WEXITSTATUS(exit_status) == 0) {
179 else if (service_state == service_state_t::STOPPING) {
180 // We won't log a non-zero exit status or termination due to signal here -
181 // we assume that the process died because we signalled it.
184 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
185 // TODO if we are pinned-started then we should probably check
186 // that dependencies have started before trying to re-start the
188 if (! restart_ps_process()) {
190 services->process_queues();
197 services->process_queues();
200 void bgproc_service::handle_exit_status(int exit_status) noexcept
203 bool did_exit = WIFEXITED(exit_status);
204 bool was_signalled = WIFSIGNALED(exit_status);
206 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
208 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
210 else if (was_signalled) {
211 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
215 if (doing_recovery) {
216 doing_recovery = false;
217 bool need_stop = false;
218 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
222 // We need to re-read the PID, since it has now changed.
223 if (pid_file.length() != 0) {
224 auto pid_result = read_pid_file(&exit_status);
225 switch (pid_result) {
226 case pid_result_t::FAILED:
227 // Failed startup: no auto-restart.
230 case pid_result_t::TERMINATED:
232 case pid_result_t::OK:
239 // Failed startup: no auto-restart.
241 services->process_queues();
247 if (service_state == service_state_t::STARTING) {
248 // POSIX requires that if the process exited clearly with a status code of 0,
249 // the exit status value will be 0:
250 if (exit_status == 0) {
251 auto pid_result = read_pid_file(&exit_status);
252 switch (pid_result) {
253 case pid_result_t::FAILED:
254 // Failed startup: no auto-restart.
257 case pid_result_t::TERMINATED:
258 // started, but immediately terminated
261 case pid_result_t::OK:
270 else if (service_state == service_state_t::STOPPING) {
271 // We won't log a non-zero exit status or termination due to signal here -
272 // we assume that the process died because we signalled it.
275 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
276 // TODO if we are pinned-started then we should probably check
277 // that dependencies have started before trying to re-start the
279 doing_recovery = true;
280 if (! restart_ps_process()) {
282 services->process_queues();
287 // we must be STARTED
288 if (! do_auto_restart() && start_explicit) {
289 start_explicit = false;
296 services->process_queues();
299 void scripted_service::handle_exit_status(int exit_status) noexcept
301 bool did_exit = WIFEXITED(exit_status);
302 bool was_signalled = WIFSIGNALED(exit_status);
304 if (service_state == service_state_t::STOPPING) {
305 if (did_exit && WEXITSTATUS(exit_status) == 0) {
309 // ??? failed to stop! Let's log it as info:
311 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
313 else if (was_signalled) {
314 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
316 // Just assume that we stopped, so that any dependencies
320 services->process_queues();
323 if (exit_status == 0) {
329 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
331 else if (was_signalled) {
332 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
336 services->process_queues();
340 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
342 base_process_service *sr = service;
343 sr->waiting_for_execstat = false;
346 int r = read(get_watched_fd(), &exec_status, sizeof(int));
348 close(get_watched_fd());
351 // We read an errno code; exec() failed, and the service startup failed.
353 sr->child_listener.deregister(eventLoop, sr->pid);
354 sr->reserved_child_watch = false;
357 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
358 if (sr->service_state == service_state_t::STARTING) {
359 sr->failed_to_start();
361 else if (sr->service_state == service_state_t::STOPPING) {
362 // Must be a scripted service. We've logged the failure, but it's probably better
363 // not to leave the service in STARTED state:
369 if (sr->record_type == service_type::PROCESS) {
370 // This could be a smooth recovery (state already STARTED). Even more, the process
371 // might be stopped (and killed via a signal) during smooth recovery. We don't to
372 // process startup again in either case, so we check for state STARTING:
373 if (sr->service_state == service_state_t::STARTING) {
379 // Somehow the process managed to complete before we even saw the status.
380 sr->handle_exit_status(sr->exit_status);
384 sr->services->process_queues();
386 return rearm::REMOVED;
389 void service_record::require() noexcept
391 if (required_by++ == 0) {
392 prop_require = !prop_release;
393 prop_release = false;
394 services->addToPropQueue(this);
398 void service_record::release() noexcept
400 if (--required_by == 0) {
401 desired_state = service_state_t::STOPPED;
403 // Can stop, and can release dependencies now. We don't need to issue a release if
404 // the require was pending though:
405 prop_release = !prop_require;
406 prop_require = false;
407 services->addToPropQueue(this);
409 if (service_state == service_state_t::STOPPED) {
410 services->service_inactive(this);
418 void service_record::release_dependencies() noexcept
420 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
424 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
425 service_record * to = i->getTo();
426 if (i->holding_acq) {
428 i->holding_acq = false;
433 void service_record::start(bool activate) noexcept
435 if (activate && ! start_explicit) {
437 start_explicit = true;
440 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
442 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
443 desired_state = service_state_t::STARTED;
445 if (service_state != service_state_t::STOPPED) {
446 // We're already starting/started, or we are stopping and need to wait for
447 // that the complete.
448 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
451 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
452 // but if so they are waiting (for us), so they too can be instantly returned to
454 notify_listeners(service_event::STOPCANCELLED);
456 else if (! was_active) {
457 services->service_active(this);
460 service_state = service_state_t::STARTING;
461 waiting_for_deps = true;
463 if (start_check_dependencies(true)) {
464 services->addToStartQueue(this);
468 void service_record::do_propagation() noexcept
471 // Need to require all our dependencies
472 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
476 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
477 service_record * to = i->getTo();
479 i->holding_acq = true;
482 prop_require = false;
486 release_dependencies();
487 prop_release = false;
491 prop_failure = false;
492 failed_to_start(true);
506 void service_record::execute_transition() noexcept
508 if (service_state == service_state_t::STARTING) {
509 if (start_check_dependencies(false)) {
510 all_deps_started(false);
513 else if (service_state == service_state_t::STOPPING) {
514 if (stop_check_dependents()) {
520 void service_record::do_start() noexcept
522 if (pinned_stopped) return;
524 if (service_state != service_state_t::STARTING) {
528 service_state = service_state_t::STARTING;
530 waiting_for_deps = true;
532 // Ask dependencies to start, mark them as being waited on.
533 if (start_check_dependencies(false)) {
534 // Once all dependencies are started, we start properly:
539 void service_record::dependencyStarted() noexcept
541 if (service_state == service_state_t::STARTING && waiting_for_deps) {
542 services->addToStartQueue(this);
546 bool service_record::start_check_dependencies(bool start_deps) noexcept
548 bool all_deps_started = true;
550 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
551 if ((*i)->service_state != service_state_t::STARTED) {
553 all_deps_started = false;
554 (*i)->prop_start = true;
555 services->addToPropQueue(*i);
563 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
564 service_record * to = i->getTo();
566 if (to->service_state != service_state_t::STARTED) {
567 to->prop_start = true;
568 services->addToPropQueue(to);
569 i->waiting_on = true;
570 all_deps_started = false;
573 i->waiting_on = false;
576 else if (i->waiting_on) {
577 if (to->service_state != service_state_t::STARTING) {
578 // Service has either started or is no longer starting
579 i->waiting_on = false;
582 // We are still waiting on this service
588 return all_deps_started;
591 bool service_record::open_socket() noexcept
593 if (socket_path.empty() || socket_fd != -1) {
594 // No socket, or already open
598 const char * saddrname = socket_path.c_str();
599 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
601 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
602 if (name == nullptr) {
603 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
607 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
610 name->sun_family = AF_UNIX;
611 strcpy(name->sun_path, saddrname);
613 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
615 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
620 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
621 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
629 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
630 // use chown and chmod instead.
631 if (chown(saddrname, socket_uid, socket_gid)) {
632 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
637 if (chmod(saddrname, socket_perms) == -1) {
638 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
643 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
644 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
653 void service_record::all_deps_started(bool has_console) noexcept
655 if (onstart_flags.starts_on_console && ! has_console) {
656 waiting_for_deps = true;
661 waiting_for_deps = false;
663 // We overload can_interrupt_start to check whether there is any other
664 // process (eg restart timer) that needs to finish before starting.
665 if (can_interrupt_start()) {
666 waiting_for_deps = true;
670 if (! open_socket()) {
674 bool start_success = start_ps_process();
675 if (! start_success) {
680 void service_record::acquiredConsole() noexcept
682 if (service_state != service_state_t::STARTING) {
683 // We got the console but no longer want it.
686 else if (start_check_dependencies(false)) {
687 all_deps_started(true);
690 // We got the console but can't use it yet.
695 bgproc_service::pid_result_t
696 bgproc_service::read_pid_file(int *exit_status) noexcept
698 const char *pid_file_c = pid_file.c_str();
699 int fd = open(pid_file_c, O_CLOEXEC);
701 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
702 return pid_result_t::FAILED;
705 char pidbuf[21]; // just enough to hold any 64-bit integer
706 int r = read(fd, pidbuf, 20); // TODO signal-safe read
708 // Could not read from PID file
709 log(LogLevel::ERROR, service_name, ": could not read from pidfile; ", strerror(errno));
711 return pid_result_t::FAILED;
715 pidbuf[r] = 0; // store nul terminator
716 // TODO may need stoull; what if int isn't big enough...
717 pid = std::atoi(pidbuf);
718 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
719 if (wait_r == -1 && errno == ECHILD) {
720 // We can't track this child - check process exists:
721 if (kill(pid, 0) == 0) {
722 tracking_child = false;
723 return pid_result_t::OK;
726 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
728 return pid_result_t::FAILED;
731 else if (wait_r == pid) {
733 return pid_result_t::TERMINATED;
735 else if (wait_r == 0) {
736 // We can track the child
737 child_listener.add_reserved(eventLoop, pid, DEFAULT_PRIORITY - 10);
738 tracking_child = true;
739 reserved_child_watch = true;
740 return pid_result_t::OK;
743 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
745 return pid_result_t::FAILED;
749 void service_record::started() noexcept
751 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
752 tcsetpgrp(0, getpgrp());
756 logServiceStarted(service_name);
757 service_state = service_state_t::STARTED;
758 notify_listeners(service_event::STARTED);
760 if (onstart_flags.rw_ready) {
761 open_control_socket();
763 if (onstart_flags.log_ready) {
764 setup_external_log();
767 if (force_stop || desired_state == service_state_t::STOPPED) {
773 // Notify any dependents whose desired state is STARTED:
774 for (auto i = dependents.begin(); i != dependents.end(); i++) {
775 (*i)->dependencyStarted();
777 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
778 (*i)->getFrom()->dependencyStarted();
782 void service_record::failed_to_start(bool depfailed) noexcept
784 if (!depfailed && onstart_flags.starts_on_console) {
785 tcsetpgrp(0, getpgrp());
789 logServiceFailed(service_name);
790 service_state = service_state_t::STOPPED;
791 if (start_explicit) {
792 start_explicit = false;
795 notify_listeners(service_event::FAILEDSTART);
797 // Cancel start of dependents:
798 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
799 if ((*i)->service_state == service_state_t::STARTING) {
800 (*i)->prop_failure = true;
801 services->addToPropQueue(*i);
804 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
805 // We can send 'start', because this is only a soft dependency.
806 // Our startup failure means that they don't have to wait for us.
807 if ((*i)->waiting_on) {
808 (*i)->holding_acq = false;
809 (*i)->waiting_on = false;
810 (*i)->getFrom()->dependencyStarted();
816 bool service_record::start_ps_process() noexcept
818 // default implementation: there is no process, so we are started.
823 bool base_process_service::start_ps_process() noexcept
826 return restart_ps_process();
829 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
830 restart_interval_count = 0;
831 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
835 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
837 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
838 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
839 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
840 // is written to the pipe, and the parent can read it.
842 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
845 if (pipe2(pipefd, O_CLOEXEC)) {
846 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
850 const char * logfile = this->logfile.c_str();
852 logfile = "/dev/null";
855 bool child_status_registered = false;
856 control_conn_t *control_conn = nullptr;
858 int control_socket[2] = {-1, -1};
859 if (onstart_flags.pass_cs_fd) {
860 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
861 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
865 // Make the server side socket close-on-exec:
866 int fdflags = fcntl(control_socket[0], F_GETFD);
867 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
870 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
872 catch (std::exception &exc) {
873 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
878 // Set up complete, now fork and exec:
883 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
884 child_status_registered = true;
886 // We specify a high priority (i.e. low priority value) so that process termination is
887 // handled early. This means we have always recorded that the process is terminated by the
888 // time that we handle events that might otherwise cause us to signal the process, so we
889 // avoid sending a signal to an invalid (and possibly recycled) process ID.
890 forkpid = child_listener.fork(eventLoop, reserved_child_watch, DEFAULT_PRIORITY - 10);
891 reserved_child_watch = true;
893 catch (std::exception &e) {
894 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
899 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
903 close(pipefd[1]); // close the 'other end' fd
904 if (control_socket[1] != -1) {
905 close(control_socket[1]);
909 waiting_for_execstat = true;
916 if (child_status_registered) {
917 child_status_listener.deregister(eventLoop);
920 if (onstart_flags.pass_cs_fd) {
924 close(control_socket[0]);
925 close(control_socket[1]);
935 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
936 int wpipefd, int csfd) noexcept
938 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
939 // from here until exit().
941 // If the console already has a session leader, presumably it is us. On the other hand
942 // if it has no session leader, and we don't create one, then control inputs such as
943 // ^C will have no effect.
944 bool do_set_ctty = (tcgetsid(0) == -1);
946 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
947 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
948 sigset_t sigwait_set;
950 sigfillset(&sigall_set);
951 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
952 sigdelset(&sigwait_set, SIGCHLD);
953 sigdelset(&sigwait_set, SIGINT);
954 sigdelset(&sigwait_set, SIGTERM);
955 sigdelset(&sigwait_set, SIGQUIT);
957 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
958 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
959 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
960 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
963 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
964 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
965 char csenvbuf[csenvbufsz];
967 int minfd = (socket_fd == -1) ? 3 : 4;
969 // Move wpipefd/csfd to another fd if necessary
970 if (wpipefd < minfd) {
971 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
972 if (wpipefd == -1) goto failure_out;
975 if (csfd != -1 && csfd < minfd) {
976 csfd = fcntl(csfd, F_DUPFD, minfd);
977 if (csfd == -1) goto failure_out;
980 if (socket_fd != -1) {
982 if (dup2(socket_fd, 3) == -1) goto failure_out;
983 if (socket_fd != 3) {
987 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
988 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
989 if (putenv(nbuf)) goto failure_out;
993 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
994 if (putenv(csenvbuf)) goto failure_out;
998 // Re-set stdin, stdout, stderr
999 close(0); close(1); close(2);
1001 if (open("/dev/null", O_RDONLY) == 0) {
1002 // stdin = 0. That's what we should have; proceed with opening
1003 // stdout and stderr.
1004 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1007 if (dup2(1, 2) != 2) {
1011 else goto failure_out;
1013 // We have the option of creating a session and process group, or just a new process
1014 // group. If we just create a new process group, the child process cannot make itself
1015 // a session leader if it wants to do that (eg getty/login will generally want this).
1016 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1017 // will also affect the child process (which probably isn't so bad, though since we
1018 // will handle the shutdown ourselves it's not necessary). Creating a new session
1019 // (and a new process group as part of that) seems like a safe bet, and has the
1020 // advantage of letting us signal the process as part of a process group.
1024 // "run on console" - run as a foreground job on the terminal/console device
1026 // if do_set_ctty is false, we are the session leader; we are probably running
1027 // as a user process. Don't create a new session leader in that case, and run
1028 // as part of the parent session. Otherwise, the new session cannot claim the
1029 // terminal as a controlling terminal (it is already claimed), meaning that it
1030 // will not see control signals from ^C etc.
1033 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1034 signal(SIGTSTP, SIG_IGN);
1036 // Become session leader
1038 ioctl(0, TIOCSCTTY, 0);
1041 tcsetpgrp(0, getpgrp());
1044 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1046 execvp(args[0], const_cast<char **>(args));
1048 // If we got here, the exec failed:
1050 int exec_status = errno;
1051 write(wpipefd, &exec_status, sizeof(int));
1055 // Mark this and all dependent services as force-stopped.
1056 void service_record::forceStop() noexcept
1058 if (service_state != service_state_t::STOPPED) {
1060 services->addToStopQueue(this);
1064 void service_record::dependent_stopped() noexcept
1066 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1067 services->addToStopQueue(this);
1071 void service_record::stop(bool bring_down) noexcept
1073 if (start_explicit) {
1074 start_explicit = false;
1083 void service_record::do_stop() noexcept
1085 if (pinned_started) return;
1087 if (start_explicit && ! do_auto_restart()) {
1088 start_explicit = false;
1090 if (required_by == 0) return; // release will re-call us anyway
1093 if (service_state != service_state_t::STARTED) {
1094 if (service_state == service_state_t::STARTING) {
1095 if (! can_interrupt_start()) {
1096 // Well this is awkward: we're going to have to continue
1097 // starting, but we don't want any dependents to think that
1098 // they are still waiting to start.
1099 // Make sure they remain stopped:
1104 // We must have had desired_state == STARTED.
1105 notify_listeners(service_event::STARTCANCELLED);
1109 // Reaching this point, we are starting interruptibly - so we
1110 // stop now (by falling through to below).
1113 // If we're starting we need to wait for that to complete.
1114 // If we're already stopping/stopped there's nothing to do.
1119 service_state = service_state_t::STOPPING;
1120 waiting_for_deps = true;
1121 if (stop_dependents()) {
1122 services->addToStopQueue(this);
1126 bool service_record::stop_check_dependents() noexcept
1128 bool all_deps_stopped = true;
1129 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1130 if (! (*i)->is_stopped()) {
1131 all_deps_stopped = false;
1136 return all_deps_stopped;
1139 bool service_record::stop_dependents() noexcept
1141 bool all_deps_stopped = true;
1142 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1143 if (! (*i)->is_stopped()) {
1144 // Note we check *first* since if the dependent service is not stopped,
1145 // 1. We will issue a stop to it shortly and
1146 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1147 // check is run anyway.
1148 all_deps_stopped = false;
1152 // If this service is to be forcefully stopped, dependents must also be.
1156 (*i)->prop_stop = true;
1157 services->addToPropQueue(*i);
1160 return all_deps_stopped;
1163 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1164 void service_record::all_deps_stopped() noexcept
1166 waiting_for_deps = false;
1170 void base_process_service::all_deps_stopped() noexcept
1172 waiting_for_deps = false;
1174 // The process is still kicking on - must actually kill it. We signal the process
1175 // group (-pid) rather than just the process as there's less risk then of creating
1176 // an orphaned process group:
1177 if (! onstart_flags.no_sigterm) {
1178 kill(-pid, SIGTERM);
1180 if (term_signal != -1) {
1181 kill(-pid, term_signal);
1184 // In most cases, the rest is done in handle_exit_status.
1185 // If we are a BGPROCESS and the process is not our immediate child, however, that
1186 // won't work - check for this now:
1187 if (record_type == service_type::BGPROCESS) {
1188 // TODO use 'tracking_child' instead
1190 pid_t r = waitpid(pid, &status, WNOHANG);
1191 if (r == -1 && errno == ECHILD) {
1192 // We can't track this child (or it's terminated already)
1195 else if (r == pid) {
1196 // Process may have died due to signal since we explicitly requested it to
1197 // stop by signalling it; no need to log any termination status.
1203 // The process is already dead.
1208 void scripted_service::all_deps_stopped() noexcept
1210 waiting_for_deps = false;
1211 if (stop_command.length() == 0) {
1214 else if (! start_ps_process(stop_arg_parts, false)) {
1215 // Couldn't execute stop script, but there's not much we can do:
1220 void service_record::unpin() noexcept
1222 if (pinned_started) {
1223 pinned_started = false;
1224 if (desired_state == service_state_t::STOPPED) {
1226 services->process_queues();
1229 if (pinned_stopped) {
1230 pinned_stopped = false;
1231 if (desired_state == service_state_t::STARTED) {
1233 services->process_queues();
1238 void service_record::queue_for_console() noexcept
1240 services->append_console_queue(this);
1243 void service_record::release_console() noexcept
1245 services->pull_console_queue();
1248 void service_record::interrupt_start() noexcept
1250 services->unqueue_console(this);
1253 void service_set::service_active(service_record *sr) noexcept
1258 void service_set::service_inactive(service_record *sr) noexcept
1263 base_process_service::base_process_service(service_set *sset, string name, service_type service_type_p, string &&command,
1264 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1265 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1266 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1267 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1269 restart_interval_count = 0;
1270 restart_interval_time = {0, 0};
1271 restart_timer.service = this;
1272 restart_timer.add_timer(eventLoop);
1274 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1275 restart_interval.tv_sec = 10;
1276 restart_interval.tv_nsec = 0;
1277 max_restart_interval_count = 3;
1279 waiting_restart_timer = false;
1280 reserved_child_watch = false;
1283 void base_process_service::do_restart() noexcept
1286 waiting_restart_timer = false;
1287 restart_interval_count++;
1289 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1290 // the process should be granted access to the console:
1291 bool on_console = service_state == service_state_t::STARTING
1292 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1294 if (! start_ps_process(exec_arg_parts, on_console)) {
1295 if (service_state == service_state_t::STARTING) {
1299 desired_state = service_state_t::STOPPED;
1302 services->process_queues();
1306 bool base_process_service::restart_ps_process() noexcept
1308 using time_val = eventloop_t::time_val;
1310 time_val current_time;
1311 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1313 if (max_restart_interval_count != 0) {
1314 // Check whether we're still in the most recent restart check interval:
1315 time_val int_diff = current_time - restart_interval_time;
1316 if (int_diff < restart_interval) {
1317 if (restart_interval_count >= max_restart_interval_count) {
1318 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1323 restart_interval_time = current_time;
1324 restart_interval_count = 0;
1328 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1329 time_val tdiff = current_time - last_start_time;
1330 if (restart_delay <= tdiff) {
1331 // > restart delay (normally 200ms)
1335 time_val timeout = restart_delay - tdiff;
1336 restart_timer.arm_timer_rel(eventLoop, timeout);
1337 waiting_restart_timer = true;
1342 void base_process_service::interrupt_start() noexcept
1344 // overridden in subclasses
1345 if (waiting_restart_timer) {
1346 restart_timer.stop_timer(eventLoop);
1347 waiting_restart_timer = false;
1349 service_record::interrupt_start();
1352 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1354 service->do_restart();
1355 return dasynq::rearm::DISARM;