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->dependentStopped();
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 notifyListeners(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
202 bool did_exit = WIFEXITED(exit_status);
203 bool was_signalled = WIFSIGNALED(exit_status);
205 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
207 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
209 else if (was_signalled) {
210 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
214 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 if (! read_pid_file()) {
231 // Failed startup: no auto-restart.
233 services->process_queues();
239 if (service_state == service_state_t::STARTING) {
240 // POSIX requires that if the process exited clearly with a status code of 0,
241 // the exit status value will be 0:
242 if (exit_status == 0) {
243 if (pid_file.length() != 0 && ! read_pid_file()) {
254 else if (service_state == service_state_t::STOPPING) {
255 // We won't log a non-zero exit status or termination due to signal here -
256 // we assume that the process died because we signalled it.
259 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
260 // TODO if we are pinned-started then we should probably check
261 // that dependencies have started before trying to re-start the
263 doing_recovery = true;
264 if (! restart_ps_process()) {
266 services->process_queues();
271 // we must be STARTED
272 if (! do_auto_restart() && start_explicit) {
273 start_explicit = false;
280 services->process_queues();
283 void scripted_service::handle_exit_status(int exit_status) noexcept
285 bool did_exit = WIFEXITED(exit_status);
286 bool was_signalled = WIFSIGNALED(exit_status);
288 if (service_state == service_state_t::STOPPING) {
289 if (did_exit && WEXITSTATUS(exit_status) == 0) {
293 // ??? failed to stop! Let's log it as info:
295 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
297 else if (was_signalled) {
298 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
300 // Just assume that we stopped, so that any dependencies
304 services->process_queues();
307 if (exit_status == 0) {
313 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
315 else if (was_signalled) {
316 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
320 services->process_queues();
324 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
326 base_process_service *sr = service;
327 sr->waiting_for_execstat = false;
330 int r = read(get_watched_fd(), &exec_status, sizeof(int));
332 close(get_watched_fd());
335 // We read an errno code; exec() failed, and the service startup failed.
337 sr->child_listener.deregister(eventLoop, sr->pid);
340 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
341 if (sr->service_state == service_state_t::STARTING) {
342 sr->failed_to_start();
344 else if (sr->service_state == service_state_t::STOPPING) {
345 // Must be a scripted service. We've logged the failure, but it's probably better
346 // not to leave the service in STARTED state:
352 if (sr->record_type == service_type::PROCESS) {
353 // This could be a smooth recovery (state already STARTED). Even more, the process
354 // might be stopped (and killed via a signal) during smooth recovery. We don't to
355 // process startup again in either case, so we check for state STARTING:
356 if (sr->service_state == service_state_t::STARTING) {
362 // Somehow the process managed to complete before we even saw the status.
363 sr->handle_exit_status(sr->exit_status);
367 sr->services->process_queues();
369 return rearm::REMOVED;
372 void service_record::require() noexcept
374 if (required_by++ == 0) {
375 prop_require = !prop_release;
376 prop_release = false;
377 services->addToPropQueue(this);
381 void service_record::release() noexcept
383 if (--required_by == 0) {
384 desired_state = service_state_t::STOPPED;
386 // Can stop, and can release dependencies now. We don't need to issue a release if
387 // the require was pending though:
388 prop_release = !prop_require;
389 prop_require = false;
390 services->addToPropQueue(this);
392 if (service_state == service_state_t::STOPPED) {
393 services->service_inactive(this);
401 void service_record::release_dependencies() noexcept
403 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
407 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
408 service_record * to = i->getTo();
409 if (i->holding_acq) {
411 i->holding_acq = false;
416 void service_record::start(bool activate) noexcept
418 if (activate && ! start_explicit) {
420 start_explicit = true;
423 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
425 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
426 desired_state = service_state_t::STARTED;
428 if (service_state != service_state_t::STOPPED) {
429 // We're already starting/started, or we are stopping and need to wait for
430 // that the complete.
431 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
434 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
435 // but if so they are waiting (for us), so they too can be instantly returned to
437 notifyListeners(service_event::STOPCANCELLED);
439 else if (! was_active) {
440 services->service_active(this);
443 service_state = service_state_t::STARTING;
444 waiting_for_deps = true;
446 if (startCheckDependencies(true)) {
447 services->addToStartQueue(this);
451 void service_record::do_propagation() noexcept
454 // Need to require all our dependencies
455 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
459 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
460 service_record * to = i->getTo();
462 i->holding_acq = true;
465 prop_require = false;
469 release_dependencies();
470 prop_release = false;
474 prop_failure = false;
475 failed_to_start(true);
489 void service_record::execute_transition() noexcept
491 if (service_state == service_state_t::STARTING) {
492 if (startCheckDependencies(false)) {
493 allDepsStarted(false);
496 else if (service_state == service_state_t::STOPPING) {
497 if (stopCheckDependents()) {
503 void service_record::do_start() noexcept
505 if (pinned_stopped) return;
507 if (service_state != service_state_t::STARTING) {
511 service_state = service_state_t::STARTING;
513 waiting_for_deps = true;
515 // Ask dependencies to start, mark them as being waited on.
516 if (startCheckDependencies(false)) {
517 // Once all dependencies are started, we start properly:
522 void service_record::dependencyStarted() noexcept
524 if (service_state == service_state_t::STARTING && waiting_for_deps) {
525 services->addToStartQueue(this);
529 bool service_record::startCheckDependencies(bool start_deps) noexcept
531 bool all_deps_started = true;
533 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
534 if ((*i)->service_state != service_state_t::STARTED) {
536 all_deps_started = false;
537 (*i)->prop_start = true;
538 services->addToPropQueue(*i);
546 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
547 service_record * to = i->getTo();
549 if (to->service_state != service_state_t::STARTED) {
550 to->prop_start = true;
551 services->addToPropQueue(to);
552 i->waiting_on = true;
553 all_deps_started = false;
556 i->waiting_on = false;
559 else if (i->waiting_on) {
560 if (to->service_state != service_state_t::STARTING) {
561 // Service has either started or is no longer starting
562 i->waiting_on = false;
565 // We are still waiting on this service
571 return all_deps_started;
574 bool service_record::open_socket() noexcept
576 if (socket_path.empty() || socket_fd != -1) {
577 // No socket, or already open
581 const char * saddrname = socket_path.c_str();
582 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
584 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
585 if (name == nullptr) {
586 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
590 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
593 name->sun_family = AF_UNIX;
594 strcpy(name->sun_path, saddrname);
596 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
598 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
603 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
604 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
612 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
613 // use chown and chmod instead.
614 if (chown(saddrname, socket_uid, socket_gid)) {
615 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
620 if (chmod(saddrname, socket_perms) == -1) {
621 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
626 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
627 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
636 void service_record::allDepsStarted(bool has_console) noexcept
638 if (onstart_flags.starts_on_console && ! has_console) {
639 waiting_for_deps = true;
644 waiting_for_deps = false;
646 // We overload can_interrupt_start to check whether there is any other
647 // process (eg restart timer) that needs to finish before starting.
648 if (can_interrupt_start()) {
649 waiting_for_deps = true;
653 if (! open_socket()) {
657 bool start_success = start_ps_process();
658 if (! start_success) {
663 void service_record::acquiredConsole() noexcept
665 if (service_state != service_state_t::STARTING) {
666 // We got the console but no longer want it.
669 else if (startCheckDependencies(false)) {
670 allDepsStarted(true);
673 // We got the console but can't use it yet.
678 bool bgproc_service::read_pid_file() noexcept
680 const char *pid_file_c = pid_file.c_str();
681 int fd = open(pid_file_c, O_CLOEXEC);
683 char pidbuf[21]; // just enought to hold any 64-bit integer
684 int r = read(fd, pidbuf, 20);
686 pidbuf[r] = 0; // store nul terminator
687 pid = std::atoi(pidbuf);
688 if (kill(pid, 0) == 0) {
689 child_listener.add_watch(eventLoop, pid);
692 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
702 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
707 void service_record::started() noexcept
709 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
710 tcsetpgrp(0, getpgrp());
714 logServiceStarted(service_name);
715 service_state = service_state_t::STARTED;
716 notifyListeners(service_event::STARTED);
718 if (onstart_flags.rw_ready) {
719 open_control_socket();
721 if (onstart_flags.log_ready) {
722 setup_external_log();
725 if (force_stop || desired_state == service_state_t::STOPPED) {
731 // Notify any dependents whose desired state is STARTED:
732 for (auto i = dependents.begin(); i != dependents.end(); i++) {
733 (*i)->dependencyStarted();
735 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
736 (*i)->getFrom()->dependencyStarted();
740 void service_record::failed_to_start(bool depfailed) noexcept
742 if (!depfailed && onstart_flags.starts_on_console) {
743 tcsetpgrp(0, getpgrp());
747 logServiceFailed(service_name);
748 service_state = service_state_t::STOPPED;
749 if (start_explicit) {
750 start_explicit = false;
753 notifyListeners(service_event::FAILEDSTART);
755 // Cancel start of dependents:
756 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
757 if ((*i)->service_state == service_state_t::STARTING) {
758 (*i)->prop_failure = true;
759 services->addToPropQueue(*i);
762 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
763 // We can send 'start', because this is only a soft dependency.
764 // Our startup failure means that they don't have to wait for us.
765 if ((*i)->waiting_on) {
766 (*i)->holding_acq = false;
767 (*i)->waiting_on = false;
768 (*i)->getFrom()->dependencyStarted();
774 bool service_record::start_ps_process() noexcept
776 // default implementation: there is no process, so we are started.
781 bool base_process_service::start_ps_process() noexcept
784 return restart_ps_process();
787 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
788 restart_interval_count = 0;
789 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
793 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
795 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
796 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
797 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
798 // is written to the pipe, and the parent can read it.
800 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
803 if (pipe2(pipefd, O_CLOEXEC)) {
804 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
808 const char * logfile = this->logfile.c_str();
810 logfile = "/dev/null";
813 bool child_status_registered = false;
814 control_conn_t *control_conn = nullptr;
816 int control_socket[2] = {-1, -1};
817 if (onstart_flags.pass_cs_fd) {
818 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
819 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
823 // Make the server side socket close-on-exec:
824 int fdflags = fcntl(control_socket[0], F_GETFD);
825 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
828 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
830 catch (std::exception &exc) {
831 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
836 // Set up complete, now fork and exec:
841 // We add the status listener with a high priority (i.e. low priority value) so that process
842 // termination is handled early. This means we have always recorded that the process is
843 // terminated by the time that we handle events that might otherwise cause us to signal the
844 // process, so we avoid sending a signal to an invalid (and possibly recycled) process ID.
845 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS, true, DEFAULT_PRIORITY - 10);
846 child_status_registered = true;
848 forkpid = child_listener.fork(eventLoop);
850 catch (std::exception &e) {
851 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
856 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
860 close(pipefd[1]); // close the 'other end' fd
861 if (control_socket[1] != -1) {
862 close(control_socket[1]);
866 waiting_for_execstat = true;
873 if (child_status_registered) {
874 child_status_listener.deregister(eventLoop);
877 if (onstart_flags.pass_cs_fd) {
881 close(control_socket[0]);
882 close(control_socket[1]);
892 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
893 int wpipefd, int csfd) noexcept
895 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
896 // from here until exit().
898 // If the console already has a session leader, presumably it is us. On the other hand
899 // if it has no session leader, and we don't create one, then control inputs such as
900 // ^C will have no effect.
901 bool do_set_ctty = (tcgetsid(0) == -1);
903 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
904 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
905 sigset_t sigwait_set;
907 sigfillset(&sigall_set);
908 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
909 sigdelset(&sigwait_set, SIGCHLD);
910 sigdelset(&sigwait_set, SIGINT);
911 sigdelset(&sigwait_set, SIGTERM);
912 sigdelset(&sigwait_set, SIGQUIT);
914 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
915 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
916 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
917 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
920 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
921 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
922 char csenvbuf[csenvbufsz];
924 int minfd = (socket_fd == -1) ? 3 : 4;
926 // Move wpipefd/csfd to another fd if necessary
927 if (wpipefd < minfd) {
928 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
929 if (wpipefd == -1) goto failure_out;
932 if (csfd != -1 && csfd < minfd) {
933 csfd = fcntl(csfd, F_DUPFD, minfd);
934 if (csfd == -1) goto failure_out;
937 if (socket_fd != -1) {
939 if (dup2(socket_fd, 3) == -1) goto failure_out;
940 if (socket_fd != 3) {
944 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
945 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
946 if (putenv(nbuf)) goto failure_out;
950 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
951 if (putenv(csenvbuf)) goto failure_out;
955 // Re-set stdin, stdout, stderr
956 close(0); close(1); close(2);
958 if (open("/dev/null", O_RDONLY) == 0) {
959 // stdin = 0. That's what we should have; proceed with opening
960 // stdout and stderr.
961 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
964 if (dup2(1, 2) != 2) {
968 else goto failure_out;
970 // We have the option of creating a session and process group, or just a new process
971 // group. If we just create a new process group, the child process cannot make itself
972 // a session leader if it wants to do that (eg getty/login will generally want this).
973 // If we do neither, and we are running with a controlling terminal, a ^C or similar
974 // will also affect the child process (which probably isn't so bad, though since we
975 // will handle the shutdown ourselves it's not necessary). Creating a new session
976 // (and a new process group as part of that) seems like a safe bet, and has the
977 // advantage of letting us signal the process as part of a process group.
981 // "run on console" - run as a foreground job on the terminal/console device
983 // if do_set_ctty is false, we are the session leader; we are probably running
984 // as a user process. Don't create a new session leader in that case, and run
985 // as part of the parent session. Otherwise, the new session cannot claim the
986 // terminal as a controlling terminal (it is already claimed), meaning that it
987 // will not see control signals from ^C etc.
990 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
991 signal(SIGTSTP, SIG_IGN);
993 // Become session leader
995 ioctl(0, TIOCSCTTY, 0);
998 tcsetpgrp(0, getpgrp());
1001 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1003 execvp(args[0], const_cast<char **>(args));
1005 // If we got here, the exec failed:
1007 int exec_status = errno;
1008 write(wpipefd, &exec_status, sizeof(int));
1012 // Mark this and all dependent services as force-stopped.
1013 void service_record::forceStop() noexcept
1015 if (service_state != service_state_t::STOPPED) {
1017 services->addToStopQueue(this);
1021 void service_record::dependentStopped() noexcept
1023 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1024 services->addToStopQueue(this);
1028 void service_record::stop(bool bring_down) noexcept
1030 if (start_explicit) {
1031 start_explicit = false;
1040 void service_record::do_stop() noexcept
1042 if (pinned_started) return;
1044 if (start_explicit && ! do_auto_restart()) {
1045 start_explicit = false;
1047 if (required_by == 0) return; // release will re-call us anyway
1050 if (service_state != service_state_t::STARTED) {
1051 if (service_state == service_state_t::STARTING) {
1052 if (! can_interrupt_start()) {
1053 // Well this is awkward: we're going to have to continue
1054 // starting, but we don't want any dependents to think that
1055 // they are still waiting to start.
1056 // Make sure they remain stopped:
1061 // We must have had desired_state == STARTED.
1062 notifyListeners(service_event::STARTCANCELLED);
1066 // Reaching this point, we are starting interruptibly - so we
1067 // stop now (by falling through to below).
1070 // If we're starting we need to wait for that to complete.
1071 // If we're already stopping/stopped there's nothing to do.
1076 service_state = service_state_t::STOPPING;
1077 waiting_for_deps = true;
1078 if (stopDependents()) {
1079 services->addToStopQueue(this);
1083 bool service_record::stopCheckDependents() noexcept
1085 bool all_deps_stopped = true;
1086 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1087 if (! (*i)->is_stopped()) {
1088 all_deps_stopped = false;
1093 return all_deps_stopped;
1096 bool service_record::stopDependents() noexcept
1098 bool all_deps_stopped = true;
1099 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1100 if (! (*i)->is_stopped()) {
1101 // Note we check *first* since if the dependent service is not stopped,
1102 // 1. We will issue a stop to it shortly and
1103 // 2. It will notify us when stopped, at which point the stopCheckDependents()
1104 // check is run anyway.
1105 all_deps_stopped = false;
1109 // If this service is to be forcefully stopped, dependents must also be.
1113 (*i)->prop_stop = true;
1114 services->addToPropQueue(*i);
1117 return all_deps_stopped;
1120 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1121 void service_record::all_deps_stopped() noexcept
1123 waiting_for_deps = false;
1127 void base_process_service::all_deps_stopped() noexcept
1129 waiting_for_deps = false;
1131 // The process is still kicking on - must actually kill it. We signal the process
1132 // group (-pid) rather than just the process as there's less risk then of creating
1133 // an orphaned process group:
1134 if (! onstart_flags.no_sigterm) {
1135 kill(-pid, SIGTERM);
1137 if (term_signal != -1) {
1138 kill(-pid, term_signal);
1141 // In most cases, the rest is done in handle_exit_status.
1142 // If we are a BGPROCESS and the process is not our immediate child, however, that
1143 // won't work - check for this now:
1144 if (record_type == service_type::BGPROCESS) {
1146 pid_t r = waitpid(pid, &status, WNOHANG);
1147 if (r == -1 && errno == ECHILD) {
1148 // We can't track this child (or it's terminated already)
1151 else if (r == pid) {
1152 // Process may have died due to signal since we explicitly requested it to
1153 // stop by signalling it; no need to log any termination status.
1159 // The process is already dead.
1164 void scripted_service::all_deps_stopped() noexcept
1166 waiting_for_deps = false;
1167 if (stop_command.length() == 0) {
1170 else if (! start_ps_process(stop_arg_parts, false)) {
1171 // Couldn't execute stop script, but there's not much we can do:
1176 void service_record::unpin() noexcept
1178 if (pinned_started) {
1179 pinned_started = false;
1180 if (desired_state == service_state_t::STOPPED) {
1182 services->process_queues();
1185 if (pinned_stopped) {
1186 pinned_stopped = false;
1187 if (desired_state == service_state_t::STARTED) {
1189 services->process_queues();
1194 void service_record::queue_for_console() noexcept
1196 services->append_console_queue(this);
1199 void service_record::release_console() noexcept
1201 services->pull_console_queue();
1204 void service_record::interrupt_start() noexcept
1206 services->unqueue_console(this);
1209 void service_set::service_active(service_record *sr) noexcept
1214 void service_set::service_inactive(service_record *sr) noexcept
1219 base_process_service::base_process_service(service_set *sset, string name, service_type service_type_p, string &&command,
1220 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1221 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1222 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1223 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1225 restart_interval_count = 0;
1226 restart_interval_time = {0, 0};
1227 restart_timer.service = this;
1228 restart_timer.add_timer(eventLoop);
1230 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1231 restart_interval.tv_sec = 10;
1232 restart_interval.tv_nsec = 0;
1233 max_restart_interval_count = 3;
1236 void base_process_service::do_restart() noexcept
1239 waiting_restart_timer = false;
1240 restart_interval_count++;
1242 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1243 // the process should be granted access to the console:
1244 bool on_console = service_state == service_state_t::STARTING
1245 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1247 if (! start_ps_process(exec_arg_parts, on_console)) {
1248 if (service_state == service_state_t::STARTING) {
1252 desired_state = service_state_t::STOPPED;
1255 services->process_queues();
1259 bool base_process_service::restart_ps_process() noexcept
1261 using time_val = eventloop_t::time_val;
1263 time_val current_time;
1264 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1266 if (max_restart_interval_count != 0) {
1267 // Check whether we're still in the most recent restart check interval:
1268 time_val int_diff = current_time - restart_interval_time;
1269 if (int_diff < restart_interval) {
1270 if (restart_interval_count >= max_restart_interval_count) {
1271 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1276 restart_interval_time = current_time;
1277 restart_interval_count = 0;
1281 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1282 time_val tdiff = current_time - last_start_time;
1283 if (restart_delay < tdiff) {
1284 // > restart delay (normally 200ms)
1288 time_val timeout = restart_delay - tdiff;
1289 restart_timer.arm_timer_rel(eventLoop, timeout);
1290 waiting_restart_timer = true;
1295 void base_process_service::interrupt_start() noexcept
1297 // overridden in subclasses
1298 if (waiting_restart_timer) {
1299 restart_timer.stop_timer(eventLoop);
1300 waiting_restart_timer = false;
1302 service_record::interrupt_start();
1305 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1307 service->do_restart();
1308 return dasynq::rearm::DISARM;