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 ServiceRecord * find_service(const std::list<ServiceRecord *> & records,
33 const char *name) noexcept
36 list<ServiceRecord *>::const_iterator i = records.begin();
37 for ( ; i != records.end(); i++ ) {
38 if (strcmp((*i)->getServiceName().c_str(), name) == 0) {
42 return (ServiceRecord *)0;
45 ServiceRecord * ServiceSet::find_service(const std::string &name) noexcept
47 return ::find_service(records, name.c_str());
50 void ServiceSet::startService(const char *name)
53 ServiceRecord *record = loadServiceRecord(name);
59 void ServiceSet::stopService(const std::string & name) noexcept
61 ServiceRecord *record = find_service(name);
62 if (record != nullptr) {
68 // Called when a service has actually stopped; dependents have stopped already, unless this stop
69 // is due to an unexpected process termination.
70 void ServiceRecord::stopped() noexcept
72 if (onstart_flags.runs_on_console) {
73 tcsetpgrp(0, getpgrp());
74 discard_console_log_buffer();
80 // If we are a soft dependency of another target, break the acquisition from that target now:
81 for (auto dependent : soft_dpts) {
82 if (dependent->holding_acq) {
83 dependent->holding_acq = false;
88 bool will_restart = (desired_state == ServiceState::STARTED)
89 && service_set->get_auto_restart();
91 for (auto dependency : depends_on) {
92 // we signal dependencies in case they are waiting for us to stop:
93 dependency->dependentStopped();
96 service_state = ServiceState::STOPPED;
99 // Desired state is "started".
104 if (socket_fd != -1) {
109 if (start_explicit) {
110 start_explicit = false;
113 else if (required_by == 0) {
114 service_set->service_inactive(this);
118 logServiceStopped(service_name);
119 notifyListeners(ServiceEvent::STOPPED);
122 dasynq::rearm ServiceChildWatcher::status_change(EventLoop_t &loop, pid_t child, int status) noexcept
124 base_process_service *sr = service;
127 sr->exit_status = status;
129 // Ok, for a process service, any process death which we didn't rig
130 // ourselves is a bit... unexpected. Probably, the child died because
131 // we asked it to (sr->service_state == STOPPING). But even if
132 // we didn't, there's not much we can do.
134 if (sr->waiting_for_execstat) {
135 // We still don't have an exec() status from the forked child, wait for that
136 // before doing any further processing.
137 return rearm::REMOVE;
140 // Must deregister now since handle_exit_status might result in re-launch:
141 deregister(loop, child);
143 sr->handle_exit_status(status);
144 return rearm::REMOVED;
147 bool ServiceRecord::do_auto_restart() noexcept
150 return service_set->get_auto_restart();
155 void process_service::handle_exit_status(int exit_status) noexcept
157 bool did_exit = WIFEXITED(exit_status);
158 bool was_signalled = WIFSIGNALED(exit_status);
160 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
162 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
164 else if (was_signalled) {
165 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
169 if (service_state == ServiceState::STARTING) {
170 if (did_exit && WEXITSTATUS(exit_status) == 0) {
177 else if (service_state == ServiceState::STOPPING) {
178 // We won't log a non-zero exit status or termination due to signal here -
179 // we assume that the process died because we signalled it.
182 else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
183 // TODO if we are pinned-started then we should probably check
184 // that dependencies have started before trying to re-start the
186 if (! restart_ps_process()) {
187 desired_state = ServiceState::STOPPED;
193 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
196 service_set->processQueues(false);
199 void bgproc_service::handle_exit_status(int exit_status) noexcept
201 bool did_exit = WIFEXITED(exit_status);
202 bool was_signalled = WIFSIGNALED(exit_status);
204 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
206 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
208 else if (was_signalled) {
209 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
213 if (doing_recovery) {
215 doing_recovery = false;
216 bool need_stop = false;
217 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
221 // We need to re-read the PID, since it has now changed.
222 if (pid_file.length() != 0) {
223 if (! read_pid_file()) {
230 // Failed startup: no auto-restart.
231 desired_state = ServiceState::STOPPED;
233 service_set->processQueues(false);
239 if (service_state == ServiceState::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 == ServiceState::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 == ServiceState::STARTED && desired_state == ServiceState::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()) {
265 desired_state = ServiceState::STOPPED;
271 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
274 service_set->processQueues(false);
277 void scripted_service::handle_exit_status(int exit_status) noexcept
279 bool did_exit = WIFEXITED(exit_status);
280 bool was_signalled = WIFSIGNALED(exit_status);
282 if (service_state == ServiceState::STOPPING) {
283 if (did_exit && WEXITSTATUS(exit_status) == 0) {
287 // ??? failed to stop! Let's log it as info:
289 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
291 else if (was_signalled) {
292 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
294 // Just assume that we stopped, so that any dependencies
298 service_set->processQueues(false);
301 if (exit_status == 0) {
307 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
309 else if (was_signalled) {
310 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
314 service_set->processQueues(true);
318 rearm ServiceIoWatcher::fd_event(EventLoop_t &loop, int fd, int flags) noexcept
320 base_process_service *sr = service;
321 sr->waiting_for_execstat = false;
324 int r = read(get_watched_fd(), &exec_status, sizeof(int));
326 close(get_watched_fd());
329 // We read an errno code; exec() failed, and the service startup failed.
331 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
332 if (sr->service_state == ServiceState::STARTING) {
333 sr->failed_to_start();
335 else if (sr->service_state == ServiceState::STOPPING) {
336 // Must be a scripted service. We've logged the failure, but it's probably better
337 // not to leave the service in STARTED state:
343 if (sr->service_type == ServiceType::PROCESS) {
344 // This could be a smooth recovery (state already STARTED). Even more, the process
345 // might be stopped (and killed via a signal) during smooth recovery. We don't to
346 // process startup again in either case, so we check for state STARTING:
347 if (sr->service_state == ServiceState::STARTING) {
353 // Somehow the process managed to complete before we even saw the status.
354 sr->handle_exit_status(sr->exit_status);
358 sr->service_set->processQueues(true);
360 return rearm::REMOVED;
363 void ServiceRecord::require() noexcept
365 if (required_by++ == 0) {
366 prop_require = !prop_release;
367 prop_release = false;
368 service_set->addToPropQueue(this);
372 void ServiceRecord::release() noexcept
374 if (--required_by == 0) {
375 desired_state = ServiceState::STOPPED;
377 // Can stop, and can release dependencies now. We don't need to issue a release if
378 // the require was pending though:
379 prop_release = !prop_require;
380 prop_require = false;
381 service_set->addToPropQueue(this);
383 if (service_state == ServiceState::STOPPED) {
384 service_set->service_inactive(this);
392 void ServiceRecord::release_dependencies() noexcept
394 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
398 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
399 ServiceRecord * to = i->getTo();
400 if (i->holding_acq) {
402 i->holding_acq = false;
407 void ServiceRecord::start(bool activate) noexcept
409 if (activate && ! start_explicit) {
411 start_explicit = true;
414 if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
416 bool was_active = service_state != ServiceState::STOPPED || desired_state != ServiceState::STOPPED;
417 desired_state = ServiceState::STARTED;
419 if (service_state != ServiceState::STOPPED) {
420 // We're already starting/started, or we are stopping and need to wait for
421 // that the complete.
422 if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
425 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
426 // but if so they are waiting (for us), so they too can be instantly returned to
428 notifyListeners(ServiceEvent::STOPCANCELLED);
430 else if (! was_active) {
431 service_set->service_active(this);
434 service_state = ServiceState::STARTING;
435 waiting_for_deps = true;
437 if (startCheckDependencies(true)) {
438 service_set->addToStartQueue(this);
442 void ServiceRecord::do_propagation() noexcept
445 // Need to require all our dependencies
446 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
450 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
451 ServiceRecord * to = i->getTo();
453 i->holding_acq = true;
456 prop_require = false;
460 release_dependencies();
461 prop_release = false;
465 prop_failure = false;
466 failed_to_start(true);
480 void ServiceRecord::execute_transition() noexcept
482 if (service_state == ServiceState::STARTING) {
483 if (startCheckDependencies(false)) {
484 allDepsStarted(false);
487 else if (service_state == ServiceState::STOPPING) {
488 if (stopCheckDependents()) {
494 void ServiceRecord::do_start() noexcept
496 if (pinned_stopped) return;
498 if (service_state != ServiceState::STARTING) {
502 service_state = ServiceState::STARTING;
504 waiting_for_deps = true;
506 // Ask dependencies to start, mark them as being waited on.
507 if (startCheckDependencies(false)) {
508 // Once all dependencies are started, we start properly:
513 void ServiceRecord::dependencyStarted() noexcept
515 if (service_state == ServiceState::STARTING && waiting_for_deps) {
516 service_set->addToStartQueue(this);
520 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
522 bool all_deps_started = true;
524 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
525 if ((*i)->service_state != ServiceState::STARTED) {
527 all_deps_started = false;
528 (*i)->prop_start = true;
529 service_set->addToPropQueue(*i);
537 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
538 ServiceRecord * to = i->getTo();
540 if (to->service_state != ServiceState::STARTED) {
541 to->prop_start = true;
542 service_set->addToPropQueue(to);
543 i->waiting_on = true;
544 all_deps_started = false;
547 i->waiting_on = false;
550 else if (i->waiting_on) {
551 if (to->service_state != ServiceState::STARTING) {
552 // Service has either started or is no longer starting
553 i->waiting_on = false;
556 // We are still waiting on this service
562 return all_deps_started;
565 bool ServiceRecord::open_socket() noexcept
567 if (socket_path.empty() || socket_fd != -1) {
568 // No socket, or already open
572 const char * saddrname = socket_path.c_str();
573 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
575 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
576 if (name == nullptr) {
577 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
581 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
584 name->sun_family = AF_UNIX;
585 strcpy(name->sun_path, saddrname);
587 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
589 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
594 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
595 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
603 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
604 // use chown and chmod instead.
605 if (chown(saddrname, socket_uid, socket_gid)) {
606 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
611 if (chmod(saddrname, socket_perms) == -1) {
612 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
617 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
618 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
627 void ServiceRecord::allDepsStarted(bool has_console) noexcept
629 if (onstart_flags.starts_on_console && ! has_console) {
630 waiting_for_deps = true;
635 waiting_for_deps = false;
637 if (! open_socket()) {
641 bool start_success = start_ps_process();
642 if (! start_success) {
647 void ServiceRecord::acquiredConsole() noexcept
649 if (service_state != ServiceState::STARTING) {
650 // We got the console but no longer want it.
653 else if (startCheckDependencies(false)) {
654 allDepsStarted(true);
657 // We got the console but can't use it yet.
662 bool bgproc_service::read_pid_file() noexcept
664 const char *pid_file_c = pid_file.c_str();
665 int fd = open(pid_file_c, O_CLOEXEC);
667 char pidbuf[21]; // just enought to hold any 64-bit integer
668 int r = read(fd, pidbuf, 20);
670 pidbuf[r] = 0; // store nul terminator
671 pid = std::atoi(pidbuf);
672 if (kill(pid, 0) == 0) {
673 child_listener.add_watch(eventLoop, pid);
676 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
686 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
691 void ServiceRecord::started() noexcept
693 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
694 tcsetpgrp(0, getpgrp());
698 logServiceStarted(service_name);
699 service_state = ServiceState::STARTED;
700 notifyListeners(ServiceEvent::STARTED);
702 if (onstart_flags.rw_ready) {
703 open_control_socket();
705 if (onstart_flags.log_ready) {
706 setup_external_log();
709 if (force_stop || desired_state == ServiceState::STOPPED) {
715 // Notify any dependents whose desired state is STARTED:
716 for (auto i = dependents.begin(); i != dependents.end(); i++) {
717 (*i)->dependencyStarted();
719 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
720 (*i)->getFrom()->dependencyStarted();
724 void ServiceRecord::failed_to_start(bool depfailed) noexcept
726 if (!depfailed && onstart_flags.starts_on_console) {
727 tcsetpgrp(0, getpgrp());
731 logServiceFailed(service_name);
732 service_state = ServiceState::STOPPED;
733 if (start_explicit) {
734 start_explicit = false;
737 notifyListeners(ServiceEvent::FAILEDSTART);
739 // Cancel start of dependents:
740 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
741 if ((*i)->service_state == ServiceState::STARTING) {
742 (*i)->prop_failure = true;
743 service_set->addToPropQueue(*i);
746 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
747 // We can send 'start', because this is only a soft dependency.
748 // Our startup failure means that they don't have to wait for us.
749 if ((*i)->waiting_on) {
750 (*i)->holding_acq = false;
751 (*i)->waiting_on = false;
752 (*i)->getFrom()->dependencyStarted();
758 bool ServiceRecord::start_ps_process() noexcept
760 // default implementation: there is no process, so we are started.
765 bool base_process_service::start_ps_process() noexcept
768 return restart_ps_process();
771 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
772 restart_interval_count = 0;
773 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
777 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
779 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
780 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
781 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
782 // is written to the pipe, and the parent can read it.
784 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
787 if (pipe2(pipefd, O_CLOEXEC)) {
788 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
792 const char * logfile = this->logfile.c_str();
794 logfile = "/dev/null";
797 bool child_status_registered = false;
798 ControlConn *control_conn = nullptr;
800 int control_socket[2] = {-1, -1};
801 if (onstart_flags.pass_cs_fd) {
802 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
803 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
807 // Make the server side socket close-on-exec:
808 int fdflags = fcntl(control_socket[0], F_GETFD);
809 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
812 control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
814 catch (std::exception &exc) {
815 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
820 // Set up complete, now fork and exec:
825 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
826 child_status_registered = true;
828 forkpid = child_listener.fork(eventLoop);
830 catch (std::exception &e) {
831 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
836 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
840 close(pipefd[1]); // close the 'other end' fd
841 if (control_socket[1] != -1) {
842 close(control_socket[1]);
846 waiting_for_execstat = true;
853 if (child_status_registered) {
854 child_status_listener.deregister(eventLoop);
857 if (onstart_flags.pass_cs_fd) {
861 close(control_socket[0]);
862 close(control_socket[1]);
872 void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
873 int wpipefd, int csfd) noexcept
875 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
876 // from here until exit().
878 // If the console already has a session leader, presumably it is us. On the other hand
879 // if it has no session leader, and we don't create one, then control inputs such as
880 // ^C will have no effect.
881 bool do_set_ctty = (tcgetsid(0) == -1);
883 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
884 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
885 sigset_t sigwait_set;
887 sigfillset(&sigall_set);
888 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
889 sigdelset(&sigwait_set, SIGCHLD);
890 sigdelset(&sigwait_set, SIGINT);
891 sigdelset(&sigwait_set, SIGTERM);
892 sigdelset(&sigwait_set, SIGQUIT);
894 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
895 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
896 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
897 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
900 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
901 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
902 char csenvbuf[csenvbufsz];
904 int minfd = (socket_fd == -1) ? 3 : 4;
906 // Move wpipefd/csfd to another fd if necessary
907 if (wpipefd < minfd) {
908 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
909 if (wpipefd == -1) goto failure_out;
912 if (csfd != -1 && csfd < minfd) {
913 csfd = fcntl(csfd, F_DUPFD, minfd);
914 if (csfd == -1) goto failure_out;
917 if (socket_fd != -1) {
919 if (dup2(socket_fd, 3) == -1) goto failure_out;
920 if (socket_fd != 3) {
924 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
925 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
926 if (putenv(nbuf)) goto failure_out;
930 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
931 if (putenv(csenvbuf)) goto failure_out;
935 // Re-set stdin, stdout, stderr
936 close(0); close(1); close(2);
938 if (open("/dev/null", O_RDONLY) == 0) {
939 // stdin = 0. That's what we should have; proceed with opening
940 // stdout and stderr.
941 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
944 if (dup2(1, 2) != 2) {
948 else goto failure_out;
950 // We have the option of creating a new process group and/or session. If
951 // we just create a new process group, the child process cannot make itself
952 // a session leader if it wants to do that (eg getty/login will generally
953 // want this). If we do neither, and we are running with a controlling
954 // terminal, a ^C or similar will also affect the child process.
958 // "run on console" - run as a foreground job on the terminal/console device
960 // if do_set_ctty is false, we are the session leader; we are probably running
961 // as a user process. Don't create a new session leader in that case, and run
962 // as part of the parent session. Otherwise, the new session cannot claim the
963 // terminal as a controlling terminal (it is already claimed), meaning that it
964 // will not see control signals from ^C etc.
967 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
968 signal(SIGTSTP, SIG_IGN);
970 // Become session leader
972 ioctl(0, TIOCSCTTY, 0);
975 tcsetpgrp(0, getpgrp());
978 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
980 execvp(args[0], const_cast<char **>(args));
982 // If we got here, the exec failed:
984 int exec_status = errno;
985 write(wpipefd, &exec_status, sizeof(int));
989 // Mark this and all dependent services as force-stopped.
990 void ServiceRecord::forceStop() noexcept
992 if (service_state != ServiceState::STOPPED) {
994 service_set->addToStopQueue(this);
998 void ServiceRecord::dependentStopped() noexcept
1000 if (service_state == ServiceState::STOPPING && waiting_for_deps) {
1001 service_set->addToStopQueue(this);
1005 void ServiceRecord::stop(bool bring_down) noexcept
1007 if (start_explicit) {
1008 start_explicit = false;
1017 void ServiceRecord::do_stop() noexcept
1019 if (pinned_started) return;
1021 if (service_state != ServiceState::STARTED) {
1022 if (service_state == ServiceState::STARTING) {
1023 if (! can_interrupt_start()) {
1024 // Well this is awkward: we're going to have to continue
1025 // starting, but we don't want any dependents to think that
1026 // they are still waiting to start.
1027 // Make sure they remain stopped:
1032 // We must have had desired_state == STARTED.
1033 notifyListeners(ServiceEvent::STARTCANCELLED);
1035 // Reaching this point, we are starting interruptibly - so we
1036 // stop now (by falling through to below).
1039 // If we're starting we need to wait for that to complete.
1040 // If we're already stopping/stopped there's nothing to do.
1045 service_state = ServiceState::STOPPING;
1046 waiting_for_deps = true;
1047 if (stopDependents()) {
1048 service_set->addToStopQueue(this);
1052 bool ServiceRecord::stopCheckDependents() noexcept
1054 bool all_deps_stopped = true;
1055 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1056 if (! (*i)->is_stopped()) {
1057 all_deps_stopped = false;
1062 return all_deps_stopped;
1065 bool ServiceRecord::stopDependents() noexcept
1067 bool all_deps_stopped = true;
1068 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1069 if (! (*i)->is_stopped()) {
1070 // Note we check *first* since if the dependent service is not stopped,
1071 // 1. We will issue a stop to it shortly and
1072 // 2. It will notify us when stopped, at which point the stopCheckDependents()
1073 // check is run anyway.
1074 all_deps_stopped = false;
1078 // If this service is to be forcefully stopped, dependents must also be.
1082 (*i)->prop_stop = true;
1083 service_set->addToPropQueue(*i);
1086 return all_deps_stopped;
1089 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1090 void ServiceRecord::all_deps_stopped() noexcept
1092 waiting_for_deps = false;
1096 void base_process_service::all_deps_stopped() noexcept
1098 waiting_for_deps = false;
1100 // The process is still kicking on - must actually kill it.
1101 if (! onstart_flags.no_sigterm) {
1104 if (term_signal != -1) {
1105 kill(pid, term_signal);
1108 // In most cases, the rest is done in process_child_callback.
1109 // If we are a BGPROCESS and the process is not our immediate child, however, that
1110 // won't work - check for this now:
1111 if (service_type == ServiceType::BGPROCESS) {
1113 pid_t r = waitpid(pid, &status, WNOHANG);
1114 if (r == -1 && errno == ECHILD) {
1115 // We can't track this child (or it's terminated already)
1118 else if (r == pid) {
1119 // Process may have died due to signal since we explicitly requested it to
1120 // stop by signalling it; no need to log any termination status.
1126 // The process is already dead.
1131 void scripted_service::all_deps_stopped() noexcept
1133 waiting_for_deps = false;
1134 if (stop_command.length() == 0) {
1137 else if (! start_ps_process(stop_arg_parts, false)) {
1138 // Couldn't execute stop script, but there's not much we can do:
1143 void ServiceRecord::unpin() noexcept
1145 if (pinned_started) {
1146 pinned_started = false;
1147 if (desired_state == ServiceState::STOPPED) {
1149 service_set->processQueues(false);
1152 if (pinned_stopped) {
1153 pinned_stopped = false;
1154 if (desired_state == ServiceState::STARTED) {
1156 service_set->processQueues(true);
1161 void ServiceRecord::queueForConsole() noexcept
1163 service_set->append_console_queue(this);
1166 void ServiceRecord::releaseConsole() noexcept
1168 service_set->pullConsoleQueue();
1171 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1176 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
1181 base_process_service::base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
1182 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1183 sr_list * pdepends_on, sr_list * pdepends_soft)
1184 : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
1185 pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
1187 restart_interval_count = 0;
1188 restart_interval_time = {0, 0};
1189 restart_timer.service = this;
1190 restart_timer.add_timer(eventLoop);
1192 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1193 restart_interval.tv_sec = 10;
1194 restart_interval.tv_nsec = 0;
1195 max_restart_interval_count = 3;
1198 void base_process_service::do_restart() noexcept
1201 waiting_restart_timer = false;
1203 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1204 // the process should be granted access to the console:
1205 bool on_console = service_state == ServiceState::STARTING
1206 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1208 if (! start_ps_process(exec_arg_parts, on_console)) {
1209 if (service_state == ServiceState::STARTING) {
1213 desired_state = ServiceState::STOPPED;
1216 service_set->processQueues();
1220 // Calculate different between two times (a more recent time, "now", and a previuos time "then").
1221 static timespec diff_time(timespec now, timespec then)
1224 r.tv_sec = now.tv_sec - then.tv_sec;
1225 if (now.tv_nsec >= then.tv_nsec) {
1226 r.tv_nsec = now.tv_nsec - then.tv_nsec;
1230 r.tv_nsec = 1000000000 - (then.tv_nsec - now.tv_nsec);
1235 static bool operator<(const timespec &a, const timespec &b)
1237 if (a.tv_sec < b.tv_sec) return true;
1238 if (a.tv_sec == b.tv_sec && a.tv_nsec < b.tv_nsec) return true;
1242 bool base_process_service::restart_ps_process() noexcept
1244 timespec current_time;
1245 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1247 if (max_restart_interval_count != 0) {
1248 // Check whether we're still in the most recent restart check interval:
1249 timespec int_diff = diff_time(current_time, restart_interval_time);
1250 if (int_diff < restart_interval) {
1251 if (++restart_interval_count >= max_restart_interval_count) {
1252 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1257 restart_interval_time = current_time;
1258 restart_interval_count = 0;
1262 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1263 timespec tdiff = diff_time(current_time, last_start_time);
1264 if (restart_delay < tdiff) {
1265 // > restart delay (normally 200ms)
1269 timespec timeout = diff_time(restart_delay, tdiff);
1270 restart_timer.arm_timer_rel(eventLoop, timeout);
1271 waiting_restart_timer = true;
1276 void base_process_service::interrupt_start() noexcept
1278 // overridden in subclasses
1279 if (waiting_restart_timer) {
1280 restart_timer.stop_timer(eventLoop);
1281 waiting_restart_timer = false;
1285 dasynq::rearm process_restart_timer::timer_expiry(EventLoop_t &, int expiry_count)
1287 service->do_restart();
1288 return dasynq::rearm::DISARM;