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.
69 void ServiceRecord::stopped() noexcept
71 if (service_type != ServiceType::SCRIPTED && service_type != ServiceType::BGPROCESS && onstart_flags.runs_on_console) {
72 tcsetpgrp(0, getpgrp());
73 discard_console_log_buffer();
79 // If we are a soft dependency of another target, break the acquisition from that target now:
80 bool will_restart = (desired_state == ServiceState::STARTED) && service_set->get_auto_restart();
82 for (auto dependency : soft_dpts) {
83 if (dependency->holding_acq) {
84 dependency->holding_acq = false;
90 will_restart &= (desired_state == ServiceState::STARTED);
91 for (auto dependency : depends_on) {
92 if (! will_restart || ! dependency->can_interrupt_stop()) {
93 dependency->dependentStopped();
98 // Desired state is "started".
99 service_state = ServiceState::STOPPED;
100 service_set->addToStartQueue(this);
103 if (socket_fd != -1) {
108 if (start_explicit) {
109 start_explicit = false;
113 service_state = ServiceState::STOPPED;
114 if (required_by == 0) {
115 // Since state wasn't STOPPED until now, any release performed above won't have marked
116 // the service inactive. We check for that now:
117 service_set->service_inactive(this);
121 logServiceStopped(service_name);
122 notifyListeners(ServiceEvent::STOPPED);
125 dasynq::rearm ServiceChildWatcher::child_status(EventLoop_t &loop, pid_t child, int status) noexcept
127 base_process_service *sr = service;
130 sr->exit_status = status;
132 // Ok, for a process service, any process death which we didn't rig
133 // ourselves is a bit... unexpected. Probably, the child died because
134 // we asked it to (sr->service_state == STOPPING). But even if
135 // we didn't, there's not much we can do.
137 if (sr->waiting_for_execstat) {
138 // We still don't have an exec() status from the forked child, wait for that
139 // before doing any further processing.
140 return rearm::REMOVE;
143 // Must deregister now since handle_exit_status might result in re-launch:
144 deregister(loop, child);
146 sr->handle_exit_status(status);
147 return rearm::REMOVED;
150 bool ServiceRecord::do_auto_restart() noexcept
153 return service_set->get_auto_restart();
158 void base_process_service::handle_exit_status(int exit_status) noexcept
160 // TODO make abstract
163 void process_service::handle_exit_status(int exit_status) noexcept
165 bool did_exit = WIFEXITED(exit_status);
166 bool was_signalled = WIFSIGNALED(exit_status);
168 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
170 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
172 else if (was_signalled) {
173 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
177 if (service_state == ServiceState::STARTING) {
178 if (did_exit && WEXITSTATUS(exit_status) == 0) {
185 else if (service_state == ServiceState::STOPPING) {
186 // We won't log a non-zero exit status or termination due to signal here -
187 // we assume that the process died because we signalled it.
190 else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
191 // TODO ensure a minimum time between restarts
192 // TODO if we are pinned-started then we should probably check
193 // that dependencies have started before trying to re-start the
199 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
202 service_set->processQueues(false);
205 void bgproc_service::handle_exit_status(int exit_status) noexcept
207 bool did_exit = WIFEXITED(exit_status);
208 bool was_signalled = WIFSIGNALED(exit_status);
210 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
212 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
214 else if (was_signalled) {
215 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
219 if (doing_recovery) {
221 doing_recovery = false;
222 bool need_stop = false;
223 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
227 // We need to re-read the PID, since it has now changed.
228 if (pid_file.length() != 0) {
229 if (! read_pid_file()) {
236 // Failed startup: no auto-restart.
237 desired_state = ServiceState::STOPPED;
239 service_set->processQueues(false);
245 if (service_state == ServiceState::STARTING) {
246 // POSIX requires that if the process exited clearly with a status code of 0,
247 // the exit status value will be 0:
248 if (exit_status == 0) {
249 if (pid_file.length() != 0 && ! read_pid_file()) {
260 else if (service_state == ServiceState::STOPPING) {
261 // We won't log a non-zero exit status or termination due to signal here -
262 // we assume that the process died because we signalled it.
265 else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
266 // TODO ensure a minimum time between restarts
267 // TODO if we are pinned-started then we should probably check
268 // that dependencies have started before trying to re-start the
270 doing_recovery = true;
275 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
278 service_set->processQueues(false);
281 void scripted_service::handle_exit_status(int exit_status) noexcept
283 bool did_exit = WIFEXITED(exit_status);
284 bool was_signalled = WIFSIGNALED(exit_status);
286 if (service_state == ServiceState::STOPPING) {
287 if (did_exit && WEXITSTATUS(exit_status) == 0) {
291 // ??? failed to stop! Let's log it as info:
293 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
295 else if (was_signalled) {
296 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
298 // Just assume that we stopped, so that any dependencies
302 service_set->processQueues(false);
305 if (exit_status == 0) {
311 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
313 else if (was_signalled) {
314 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
318 service_set->processQueues(true);
322 rearm ServiceIoWatcher::fd_event(EventLoop_t &loop, int fd, int flags) noexcept
324 base_process_service *sr = service;
325 sr->waiting_for_execstat = false;
328 int r = read(get_watched_fd(), &exec_status, sizeof(int));
330 close(get_watched_fd());
333 // We read an errno code; exec() failed, and the service startup failed.
335 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
336 if (sr->service_state == ServiceState::STARTING) {
337 sr->failed_to_start();
339 else if (sr->service_state == ServiceState::STOPPING) {
340 // Must be a scripted service. We've logged the failure, but it's probably better
341 // not to leave the service in STARTED state:
347 if (sr->service_type == ServiceType::PROCESS) {
348 // This could be a smooth recovery (state already STARTED). Even more, the process
349 // might be stopped (and killed via a signal) during smooth recovery. We don't to
350 // process startup again in either case, so we check for state STARTING:
351 if (sr->service_state == ServiceState::STARTING) {
357 // Somehow the process managed to complete before we even saw the status.
358 sr->handle_exit_status(sr->exit_status);
362 sr->service_set->processQueues(true);
364 return rearm::REMOVED;
367 void ServiceRecord::require() noexcept
369 if (required_by++ == 0) {
371 if (! prop_require) {
373 prop_release = false;
374 service_set->addToPropQueue(this);
377 if (service_state == ServiceState::STOPPED) {
378 // (In any other state, the service is already considered active.)
379 service_set->service_active(this);
384 void ServiceRecord::release() noexcept
386 if (--required_by == 0) {
387 desired_state = ServiceState::STOPPED;
388 // Can stop, and can release dependencies now:
390 prop_require = false;
391 service_set->addToPropQueue(this);
392 if (service_state != ServiceState::STOPPED) {
393 service_set->addToStopQueue(this);
396 service_set->service_inactive(this);
401 void ServiceRecord::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 ServiceRecord * to = i->getTo();
409 if (i->holding_acq) {
411 i->holding_acq = false;
416 void ServiceRecord::start(bool activate) noexcept
418 if (activate && ! start_explicit) {
420 start_explicit = true;
423 if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
425 desired_state = ServiceState::STARTED;
426 service_set->addToStartQueue(this);
429 void ServiceRecord::do_propagation() noexcept
432 // Need to require all our dependencies
433 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
437 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
438 ServiceRecord * to = i->getTo();
440 i->holding_acq = true;
443 prop_require = false;
447 release_dependencies();
448 prop_release = false;
452 prop_failure = false;
453 failed_to_start(true);
456 if (waiting_for_deps) {
457 if (service_state == ServiceState::STARTING) {
458 if (startCheckDependencies(false)) {
462 else if (service_state == ServiceState::STOPPING) {
463 if (stopCheckDependents()) {
470 void ServiceRecord::execute_transition() noexcept
472 bool is_started = (service_state == ServiceState::STARTED)
473 || (service_state == ServiceState::STARTING && can_interrupt_start());
474 bool is_stopped = (service_state == ServiceState::STOPPED)
475 || (service_state == ServiceState::STOPPING && can_interrupt_stop());
477 if (is_started && (desired_state == ServiceState::STOPPED || force_stop)) {
478 if (! pinned_started) {
482 else if (is_stopped && desired_state == ServiceState::STARTED) {
483 if (! pinned_stopped) {
489 void ServiceRecord::do_start() noexcept
491 if (pinned_stopped) return;
493 if (service_state != ServiceState::STOPPED) {
494 // We're already starting/started, or we are stopping and need to wait for
495 // that the complete.
496 if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
499 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
500 // but if so they are waiting (for us), so they too can be instantly returned to
502 notifyListeners(ServiceEvent::STOPCANCELLED);
505 service_state = ServiceState::STARTING;
507 waiting_for_deps = true;
509 // Ask dependencies to start, mark them as being waited on.
510 if (! startCheckDependencies(true)) {
514 // Actually start this service.
518 void ServiceRecord::dependencyStarted() noexcept
520 if (service_state == ServiceState::STARTING && waiting_for_deps) {
521 service_set->addToPropQueue(this);
525 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
527 bool all_deps_started = true;
529 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
530 if ((*i)->service_state != ServiceState::STARTED) {
532 all_deps_started = false;
541 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
542 ServiceRecord * to = i->getTo();
544 if (to->service_state != ServiceState::STARTED) {
546 i->waiting_on = true;
547 all_deps_started = false;
550 i->waiting_on = false;
553 else if (i->waiting_on) {
554 if (to->service_state != ServiceState::STARTING) {
555 // Service has either started or is no longer starting
556 i->waiting_on = false;
559 // We are still waiting on this service
565 return all_deps_started;
568 bool ServiceRecord::open_socket() noexcept
570 if (socket_path.empty() || socket_fd != -1) {
571 // No socket, or already open
575 const char * saddrname = socket_path.c_str();
576 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
578 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
579 if (name == nullptr) {
580 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
584 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
587 name->sun_family = AF_UNIX;
588 strcpy(name->sun_path, saddrname);
590 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
592 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
597 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
598 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
606 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
607 // use chown and chmod instead.
608 if (chown(saddrname, socket_uid, socket_gid)) {
609 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
614 if (chmod(saddrname, socket_perms) == -1) {
615 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
620 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
621 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
630 void ServiceRecord::allDepsStarted(bool has_console) noexcept
632 if (onstart_flags.runs_on_console && ! has_console) {
633 waiting_for_deps = true;
638 waiting_for_deps = false;
640 if (! open_socket()) {
644 if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS
645 || service_type == ServiceType::SCRIPTED) {
646 bool start_success = start_ps_process();
647 if (! start_success) {
652 // "internal" service
657 void ServiceRecord::acquiredConsole() noexcept
659 if (service_state != ServiceState::STARTING) {
660 // We got the console but no longer want it.
663 else if (startCheckDependencies(false)) {
664 allDepsStarted(true);
667 // We got the console but can't use it yet.
672 bool base_process_service::read_pid_file() noexcept
674 const char *pid_file_c = pid_file.c_str();
675 int fd = open(pid_file_c, O_CLOEXEC);
677 char pidbuf[21]; // just enought to hold any 64-bit integer
678 int r = read(fd, pidbuf, 20);
680 pidbuf[r] = 0; // store nul terminator
681 pid = std::atoi(pidbuf);
682 if (kill(pid, 0) == 0) {
683 child_listener.add_watch(eventLoop, pid);
686 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
696 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
701 void ServiceRecord::started() noexcept
703 if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
704 tcsetpgrp(0, getpgrp());
708 logServiceStarted(service_name);
709 service_state = ServiceState::STARTED;
710 notifyListeners(ServiceEvent::STARTED);
712 if (onstart_flags.rw_ready) {
713 open_control_socket();
715 if (onstart_flags.log_ready) {
716 setup_external_log();
719 if (force_stop || desired_state == ServiceState::STOPPED) {
721 service_set->addToStopQueue(this);
725 // Notify any dependents whose desired state is STARTED:
726 for (auto i = dependents.begin(); i != dependents.end(); i++) {
727 (*i)->dependencyStarted();
729 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
730 (*i)->getFrom()->dependencyStarted();
734 void ServiceRecord::failed_to_start(bool depfailed) noexcept
736 if (!depfailed && onstart_flags.runs_on_console) {
737 tcsetpgrp(0, getpgrp());
741 logServiceFailed(service_name);
742 service_state = ServiceState::STOPPED;
743 if (start_explicit) {
744 start_explicit = false;
747 notifyListeners(ServiceEvent::FAILEDSTART);
749 // Cancel start of dependents:
750 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
751 if ((*i)->service_state == ServiceState::STARTING) {
752 (*i)->prop_failure = true;
753 service_set->addToPropQueue(*i);
756 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
757 // We can send 'start', because this is only a soft dependency.
758 // Our startup failure means that they don't have to wait for us.
759 if ((*i)->waiting_on) {
760 (*i)->holding_acq = false;
761 (*i)->waiting_on = false;
762 (*i)->getFrom()->dependencyStarted();
768 bool ServiceRecord::start_ps_process() noexcept
773 bool base_process_service::start_ps_process() noexcept
775 return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
778 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
780 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
781 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
782 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
783 // is written to the pipe, and the parent can read it.
786 if (pipe2(pipefd, O_CLOEXEC)) {
787 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
791 const char * logfile = this->logfile.c_str();
793 logfile = "/dev/null";
796 bool child_status_registered = false;
797 ControlConn *control_conn = nullptr;
799 int control_socket[2] = {-1, -1};
800 if (onstart_flags.pass_cs_fd) {
801 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
802 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
806 // Make the server side socket close-on-exec:
807 int fdflags = fcntl(control_socket[0], F_GETFD);
808 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
811 control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
813 catch (std::exception &exc) {
814 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
819 // Set up complete, now fork and exec:
824 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
825 child_status_registered = true;
827 forkpid = child_listener.fork(eventLoop);
829 catch (std::exception &e) {
830 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
835 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
839 close(pipefd[1]); // close the 'other end' fd
840 if (control_socket[1] != -1) {
841 close(control_socket[1]);
845 waiting_for_execstat = true;
852 if (child_status_registered) {
853 child_status_listener.deregister(eventLoop);
856 if (onstart_flags.pass_cs_fd) {
860 close(control_socket[0]);
861 close(control_socket[1]);
871 void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
872 int wpipefd, int csfd) noexcept
874 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
875 // from here until exit().
877 // If the console already has a session leader, presumably it is us. On the other hand
878 // if it has no session leader, and we don't create one, then control inputs such as
879 // ^C will have no effect.
880 bool do_set_ctty = (tcgetsid(0) == -1);
882 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
883 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
884 sigset_t sigwait_set;
886 sigfillset(&sigall_set);
887 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
888 sigdelset(&sigwait_set, SIGCHLD);
889 sigdelset(&sigwait_set, SIGINT);
890 sigdelset(&sigwait_set, SIGTERM);
892 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
893 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
894 // on the maxiumum number of bytes required for LISTEN=xxx, including nul terminator,
895 // where xxx is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
898 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
899 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
900 char csenvbuf[csenvbufsz];
902 int minfd = (socket_fd == -1) ? 3 : 4;
904 // Move wpipefd/csfd to another fd if necessary
905 if (wpipefd < minfd) {
906 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
907 if (wpipefd == -1) goto failure_out;
910 if (csfd != -1 && csfd < minfd) {
911 csfd = fcntl(csfd, F_DUPFD, minfd);
912 if (csfd == -1) goto failure_out;
915 if (socket_fd != -1) {
917 if (dup2(socket_fd, 3) == -1) goto failure_out;
918 if (socket_fd != 3) {
922 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
923 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
924 if (putenv(nbuf)) goto failure_out;
928 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
929 if (putenv(csenvbuf)) goto failure_out;
933 // Re-set stdin, stdout, stderr
934 close(0); close(1); close(2);
936 if (open("/dev/null", O_RDONLY) == 0) {
937 // stdin = 0. That's what we should have; proceed with opening
938 // stdout and stderr.
939 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
942 if (dup2(1, 2) != 2) {
946 else goto failure_out;
948 // We have the option of creating a new process group and/or session. If
949 // we just create a new process group, the child process cannot make itself
950 // a session leader if it wants to do that (eg getty/login will generally
951 // want this). If we do neither, and we are running with a controlling
952 // terminal, a ^C or similar will also affect the child process.
956 // "run on console" - run as a foreground job on the terminal/console device
958 // if do_set_ctty is false, we are the session leader; we are probably running
959 // as a user process. Don't create a new session leader in that case, and run
960 // as part of the parent session. Otherwise, the new session cannot claim the
961 // terminal as a controlling terminal (it is already claimed), meaning that it
962 // will not see control signals from ^C etc.
965 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
966 signal(SIGTSTP, SIG_IGN);
968 // Become session leader
970 ioctl(0, TIOCSCTTY, 0);
973 tcsetpgrp(0, getpgrp());
976 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
978 execvp(args[0], const_cast<char **>(args));
980 // If we got here, the exec failed:
982 int exec_status = errno;
983 write(wpipefd, &exec_status, sizeof(int));
987 // Mark this and all dependent services as force-stopped.
988 void ServiceRecord::forceStop() noexcept
990 if (service_state != ServiceState::STOPPED) {
992 service_set->addToStopQueue(this);
996 void ServiceRecord::dependentStopped() noexcept
998 if (service_state == ServiceState::STOPPING && waiting_for_deps) {
999 service_set->addToPropQueue(this);
1003 void ServiceRecord::stop(bool bring_down) noexcept
1005 if (start_explicit) {
1006 start_explicit = false;
1010 if (bring_down && desired_state != ServiceState::STOPPED) {
1011 desired_state = ServiceState::STOPPED;
1012 service_set->addToStopQueue(this);
1016 void ServiceRecord::do_stop() noexcept
1018 if (pinned_started) return;
1020 if (service_state != ServiceState::STARTED) {
1021 if (service_state == ServiceState::STARTING) {
1022 if (! can_interrupt_start()) {
1023 // Well this is awkward: we're going to have to continue
1024 // starting, but we don't want any dependents to think that
1025 // they are still waiting to start.
1026 // Make sure they remain stopped:
1031 // We must have had desired_state == STARTED.
1032 notifyListeners(ServiceEvent::STARTCANCELLED);
1034 // Reaching this point, we have can_interrupt_start() == true. So,
1035 // we can stop. Dependents might be starting, but they must be
1036 // waiting on us, so they should also be immediately stoppable.
1037 // Fall through to below,.
1040 // If we're starting we need to wait for that to complete.
1041 // If we're already stopping/stopped there's nothing to do.
1046 service_state = ServiceState::STOPPING;
1047 waiting_for_deps = true;
1049 // If we get here, we are in STARTED state; stop all dependents.
1050 if (stopDependents()) {
1055 bool ServiceRecord::stopCheckDependents() noexcept
1057 bool all_deps_stopped = true;
1058 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1059 if (! (*i)->is_stopped()) {
1060 all_deps_stopped = false;
1065 return all_deps_stopped;
1068 bool ServiceRecord::stopDependents() noexcept
1070 bool all_deps_stopped = true;
1071 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1072 if (! (*i)->is_stopped()) {
1073 // Note we check *first* since if the dependent service is not stopped,
1074 // 1. We will issue a stop to it shortly and
1075 // 2. It will notify us when stopped, at which point the stopCheckDependents()
1076 // check is run anyway.
1077 all_deps_stopped = false;
1083 return all_deps_stopped;
1086 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1087 void ServiceRecord::all_deps_stopped() noexcept
1089 waiting_for_deps = false;
1093 void base_process_service::all_deps_stopped() noexcept
1095 waiting_for_deps = false;
1097 // The process is still kicking on - must actually kill it.
1098 if (! onstart_flags.no_sigterm) {
1101 if (term_signal != -1) {
1102 kill(pid, term_signal);
1105 // In most cases, the rest is done in process_child_callback.
1106 // If we are a BGPROCESS and the process is not our immediate child, however, that
1107 // won't work - check for this now:
1108 if (service_type == ServiceType::BGPROCESS) {
1110 pid_t r = waitpid(pid, &status, WNOHANG);
1111 if (r == -1 && errno == ECHILD) {
1112 // We can't track this child (or it's terminated already)
1115 else if (r == pid) {
1116 // TODO, examine status and log anything unusual.
1122 // The process is already dead.
1127 void scripted_service::all_deps_stopped() noexcept
1129 waiting_for_deps = false;
1130 if (stop_command.length() == 0) {
1133 else if (! start_ps_process(stop_arg_parts, false)) {
1134 // Couldn't execute stop script, but there's not much we can do:
1139 void ServiceRecord::unpin() noexcept
1141 if (pinned_started) {
1142 pinned_started = false;
1143 if (desired_state == ServiceState::STOPPED) {
1145 service_set->processQueues(false);
1148 if (pinned_stopped) {
1149 pinned_stopped = false;
1150 if (desired_state == ServiceState::STARTED) {
1152 service_set->processQueues(true);
1157 void ServiceRecord::queueForConsole() noexcept
1159 service_set->append_console_queue(this);
1162 void ServiceRecord::releaseConsole() noexcept
1164 service_set->pullConsoleQueue();
1167 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1172 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept