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::status_change(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 process_service::handle_exit_status(int exit_status) noexcept
160 bool did_exit = WIFEXITED(exit_status);
161 bool was_signalled = WIFSIGNALED(exit_status);
163 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
165 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
167 else if (was_signalled) {
168 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
172 if (service_state == ServiceState::STARTING) {
173 if (did_exit && WEXITSTATUS(exit_status) == 0) {
180 else if (service_state == ServiceState::STOPPING) {
181 // We won't log a non-zero exit status or termination due to signal here -
182 // we assume that the process died because we signalled it.
185 else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
186 // TODO if we are pinned-started then we should probably check
187 // that dependencies have started before trying to re-start the
189 restart_ps_process();
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 restart_ps_process();
268 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
271 service_set->processQueues(false);
274 void scripted_service::handle_exit_status(int exit_status) noexcept
276 bool did_exit = WIFEXITED(exit_status);
277 bool was_signalled = WIFSIGNALED(exit_status);
279 if (service_state == ServiceState::STOPPING) {
280 if (did_exit && WEXITSTATUS(exit_status) == 0) {
284 // ??? failed to stop! Let's log it as info:
286 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
288 else if (was_signalled) {
289 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
291 // Just assume that we stopped, so that any dependencies
295 service_set->processQueues(false);
298 if (exit_status == 0) {
304 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
306 else if (was_signalled) {
307 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
311 service_set->processQueues(true);
315 rearm ServiceIoWatcher::fd_event(EventLoop_t &loop, int fd, int flags) noexcept
317 base_process_service *sr = service;
318 sr->waiting_for_execstat = false;
321 int r = read(get_watched_fd(), &exec_status, sizeof(int));
323 close(get_watched_fd());
326 // We read an errno code; exec() failed, and the service startup failed.
328 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
329 if (sr->service_state == ServiceState::STARTING) {
330 sr->failed_to_start();
332 else if (sr->service_state == ServiceState::STOPPING) {
333 // Must be a scripted service. We've logged the failure, but it's probably better
334 // not to leave the service in STARTED state:
340 if (sr->service_type == ServiceType::PROCESS) {
341 // This could be a smooth recovery (state already STARTED). Even more, the process
342 // might be stopped (and killed via a signal) during smooth recovery. We don't to
343 // process startup again in either case, so we check for state STARTING:
344 if (sr->service_state == ServiceState::STARTING) {
350 // Somehow the process managed to complete before we even saw the status.
351 sr->handle_exit_status(sr->exit_status);
355 sr->service_set->processQueues(true);
357 return rearm::REMOVED;
360 void ServiceRecord::require() noexcept
362 if (required_by++ == 0) {
364 if (! prop_require) {
366 prop_release = false;
367 service_set->addToPropQueue(this);
370 if (service_state == ServiceState::STOPPED) {
371 // (In any other state, the service is already considered active.)
372 service_set->service_active(this);
377 void ServiceRecord::release() noexcept
379 if (--required_by == 0) {
380 desired_state = ServiceState::STOPPED;
381 // Can stop, and can release dependencies now:
383 prop_require = false;
384 service_set->addToPropQueue(this);
385 if (service_state != ServiceState::STOPPED) {
386 service_set->addToStopQueue(this);
389 service_set->service_inactive(this);
394 void ServiceRecord::release_dependencies() noexcept
396 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
400 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
401 ServiceRecord * to = i->getTo();
402 if (i->holding_acq) {
404 i->holding_acq = false;
409 void ServiceRecord::start(bool activate) noexcept
411 if (activate && ! start_explicit) {
413 start_explicit = true;
416 if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
418 desired_state = ServiceState::STARTED;
419 service_set->addToStartQueue(this);
422 void ServiceRecord::do_propagation() noexcept
425 // Need to require all our dependencies
426 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
430 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
431 ServiceRecord * to = i->getTo();
433 i->holding_acq = true;
436 prop_require = false;
440 release_dependencies();
441 prop_release = false;
445 prop_failure = false;
446 failed_to_start(true);
449 if (waiting_for_deps) {
450 if (service_state == ServiceState::STARTING) {
451 if (startCheckDependencies(false)) {
455 else if (service_state == ServiceState::STOPPING) {
456 if (stopCheckDependents()) {
463 void ServiceRecord::execute_transition() noexcept
465 bool is_started = (service_state == ServiceState::STARTED)
466 || (service_state == ServiceState::STARTING && can_interrupt_start());
467 bool is_stopped = (service_state == ServiceState::STOPPED)
468 || (service_state == ServiceState::STOPPING && can_interrupt_stop());
470 if (is_started && (desired_state == ServiceState::STOPPED || force_stop)) {
471 if (! pinned_started) {
475 else if (is_stopped && desired_state == ServiceState::STARTED) {
476 if (! pinned_stopped) {
482 void ServiceRecord::do_start() noexcept
484 if (pinned_stopped) return;
486 if (service_state != ServiceState::STOPPED) {
487 // We're already starting/started, or we are stopping and need to wait for
488 // that the complete.
489 if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
492 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
493 // but if so they are waiting (for us), so they too can be instantly returned to
495 notifyListeners(ServiceEvent::STOPCANCELLED);
498 service_state = ServiceState::STARTING;
500 waiting_for_deps = true;
502 // Ask dependencies to start, mark them as being waited on.
503 if (! startCheckDependencies(true)) {
507 // Actually start this service.
511 void ServiceRecord::dependencyStarted() noexcept
513 if (service_state == ServiceState::STARTING && waiting_for_deps) {
514 service_set->addToPropQueue(this);
518 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
520 bool all_deps_started = true;
522 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
523 if ((*i)->service_state != ServiceState::STARTED) {
525 all_deps_started = false;
534 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
535 ServiceRecord * to = i->getTo();
537 if (to->service_state != ServiceState::STARTED) {
539 i->waiting_on = true;
540 all_deps_started = false;
543 i->waiting_on = false;
546 else if (i->waiting_on) {
547 if (to->service_state != ServiceState::STARTING) {
548 // Service has either started or is no longer starting
549 i->waiting_on = false;
552 // We are still waiting on this service
558 return all_deps_started;
561 bool ServiceRecord::open_socket() noexcept
563 if (socket_path.empty() || socket_fd != -1) {
564 // No socket, or already open
568 const char * saddrname = socket_path.c_str();
569 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
571 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
572 if (name == nullptr) {
573 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
577 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
580 name->sun_family = AF_UNIX;
581 strcpy(name->sun_path, saddrname);
583 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
585 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
590 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
591 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
599 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
600 // use chown and chmod instead.
601 if (chown(saddrname, socket_uid, socket_gid)) {
602 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
607 if (chmod(saddrname, socket_perms) == -1) {
608 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
613 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
614 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
623 void ServiceRecord::allDepsStarted(bool has_console) noexcept
625 if (onstart_flags.runs_on_console && ! has_console) {
626 waiting_for_deps = true;
631 waiting_for_deps = false;
633 if (! open_socket()) {
637 bool start_success = start_ps_process();
638 if (! start_success) {
643 void ServiceRecord::acquiredConsole() noexcept
645 if (service_state != ServiceState::STARTING) {
646 // We got the console but no longer want it.
649 else if (startCheckDependencies(false)) {
650 allDepsStarted(true);
653 // We got the console but can't use it yet.
658 bool bgproc_service::read_pid_file() noexcept
660 const char *pid_file_c = pid_file.c_str();
661 int fd = open(pid_file_c, O_CLOEXEC);
663 char pidbuf[21]; // just enought to hold any 64-bit integer
664 int r = read(fd, pidbuf, 20);
666 pidbuf[r] = 0; // store nul terminator
667 pid = std::atoi(pidbuf);
668 if (kill(pid, 0) == 0) {
669 child_listener.add_watch(eventLoop, pid);
672 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
682 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
687 void ServiceRecord::started() noexcept
689 if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
690 tcsetpgrp(0, getpgrp());
694 logServiceStarted(service_name);
695 service_state = ServiceState::STARTED;
696 notifyListeners(ServiceEvent::STARTED);
698 if (onstart_flags.rw_ready) {
699 open_control_socket();
701 if (onstart_flags.log_ready) {
702 setup_external_log();
705 if (force_stop || desired_state == ServiceState::STOPPED) {
707 service_set->addToStopQueue(this);
711 // Notify any dependents whose desired state is STARTED:
712 for (auto i = dependents.begin(); i != dependents.end(); i++) {
713 (*i)->dependencyStarted();
715 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
716 (*i)->getFrom()->dependencyStarted();
720 void ServiceRecord::failed_to_start(bool depfailed) noexcept
722 if (!depfailed && onstart_flags.runs_on_console) {
723 tcsetpgrp(0, getpgrp());
727 logServiceFailed(service_name);
728 service_state = ServiceState::STOPPED;
729 if (start_explicit) {
730 start_explicit = false;
733 notifyListeners(ServiceEvent::FAILEDSTART);
735 // Cancel start of dependents:
736 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
737 if ((*i)->service_state == ServiceState::STARTING) {
738 (*i)->prop_failure = true;
739 service_set->addToPropQueue(*i);
742 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
743 // We can send 'start', because this is only a soft dependency.
744 // Our startup failure means that they don't have to wait for us.
745 if ((*i)->waiting_on) {
746 (*i)->holding_acq = false;
747 (*i)->waiting_on = false;
748 (*i)->getFrom()->dependencyStarted();
754 bool ServiceRecord::start_ps_process() noexcept
756 // default implementation: there is no process, so we are started.
761 bool base_process_service::start_ps_process() noexcept
763 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
764 return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
767 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
769 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
770 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
771 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
772 // is written to the pipe, and the parent can read it.
775 if (pipe2(pipefd, O_CLOEXEC)) {
776 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
780 const char * logfile = this->logfile.c_str();
782 logfile = "/dev/null";
785 bool child_status_registered = false;
786 ControlConn *control_conn = nullptr;
788 int control_socket[2] = {-1, -1};
789 if (onstart_flags.pass_cs_fd) {
790 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
791 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
795 // Make the server side socket close-on-exec:
796 int fdflags = fcntl(control_socket[0], F_GETFD);
797 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
800 control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
802 catch (std::exception &exc) {
803 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
808 // Set up complete, now fork and exec:
813 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
814 child_status_registered = true;
816 forkpid = child_listener.fork(eventLoop);
818 catch (std::exception &e) {
819 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
824 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
828 close(pipefd[1]); // close the 'other end' fd
829 if (control_socket[1] != -1) {
830 close(control_socket[1]);
834 waiting_for_execstat = true;
841 if (child_status_registered) {
842 child_status_listener.deregister(eventLoop);
845 if (onstart_flags.pass_cs_fd) {
849 close(control_socket[0]);
850 close(control_socket[1]);
860 void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
861 int wpipefd, int csfd) noexcept
863 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
864 // from here until exit().
866 // If the console already has a session leader, presumably it is us. On the other hand
867 // if it has no session leader, and we don't create one, then control inputs such as
868 // ^C will have no effect.
869 bool do_set_ctty = (tcgetsid(0) == -1);
871 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
872 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
873 sigset_t sigwait_set;
875 sigfillset(&sigall_set);
876 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
877 sigdelset(&sigwait_set, SIGCHLD);
878 sigdelset(&sigwait_set, SIGINT);
879 sigdelset(&sigwait_set, SIGTERM);
881 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
882 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
883 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
884 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
887 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
888 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
889 char csenvbuf[csenvbufsz];
891 int minfd = (socket_fd == -1) ? 3 : 4;
893 // Move wpipefd/csfd to another fd if necessary
894 if (wpipefd < minfd) {
895 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
896 if (wpipefd == -1) goto failure_out;
899 if (csfd != -1 && csfd < minfd) {
900 csfd = fcntl(csfd, F_DUPFD, minfd);
901 if (csfd == -1) goto failure_out;
904 if (socket_fd != -1) {
906 if (dup2(socket_fd, 3) == -1) goto failure_out;
907 if (socket_fd != 3) {
911 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
912 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
913 if (putenv(nbuf)) goto failure_out;
917 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
918 if (putenv(csenvbuf)) goto failure_out;
922 // Re-set stdin, stdout, stderr
923 close(0); close(1); close(2);
925 if (open("/dev/null", O_RDONLY) == 0) {
926 // stdin = 0. That's what we should have; proceed with opening
927 // stdout and stderr.
928 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
931 if (dup2(1, 2) != 2) {
935 else goto failure_out;
937 // We have the option of creating a new process group and/or session. If
938 // we just create a new process group, the child process cannot make itself
939 // a session leader if it wants to do that (eg getty/login will generally
940 // want this). If we do neither, and we are running with a controlling
941 // terminal, a ^C or similar will also affect the child process.
945 // "run on console" - run as a foreground job on the terminal/console device
947 // if do_set_ctty is false, we are the session leader; we are probably running
948 // as a user process. Don't create a new session leader in that case, and run
949 // as part of the parent session. Otherwise, the new session cannot claim the
950 // terminal as a controlling terminal (it is already claimed), meaning that it
951 // will not see control signals from ^C etc.
954 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
955 signal(SIGTSTP, SIG_IGN);
957 // Become session leader
959 ioctl(0, TIOCSCTTY, 0);
962 tcsetpgrp(0, getpgrp());
965 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
967 execvp(args[0], const_cast<char **>(args));
969 // If we got here, the exec failed:
971 int exec_status = errno;
972 write(wpipefd, &exec_status, sizeof(int));
976 // Mark this and all dependent services as force-stopped.
977 void ServiceRecord::forceStop() noexcept
979 if (service_state != ServiceState::STOPPED) {
981 service_set->addToStopQueue(this);
985 void ServiceRecord::dependentStopped() noexcept
987 if (service_state == ServiceState::STOPPING && waiting_for_deps) {
988 service_set->addToPropQueue(this);
992 void ServiceRecord::stop(bool bring_down) noexcept
994 if (start_explicit) {
995 start_explicit = false;
999 if (bring_down && desired_state != ServiceState::STOPPED) {
1000 desired_state = ServiceState::STOPPED;
1001 service_set->addToStopQueue(this);
1005 void ServiceRecord::do_stop() noexcept
1007 if (pinned_started) return;
1009 if (service_state != ServiceState::STARTED) {
1010 if (service_state == ServiceState::STARTING) {
1011 if (! can_interrupt_start()) {
1012 // Well this is awkward: we're going to have to continue
1013 // starting, but we don't want any dependents to think that
1014 // they are still waiting to start.
1015 // Make sure they remain stopped:
1020 // We must have had desired_state == STARTED.
1021 notifyListeners(ServiceEvent::STARTCANCELLED);
1023 // Reaching this point, we have can_interrupt_start() == true. So,
1024 // we can stop. Dependents might be starting, but they must be
1025 // waiting on us, so they should also be immediately stoppable.
1026 // Fall through to below,.
1029 // If we're starting we need to wait for that to complete.
1030 // If we're already stopping/stopped there's nothing to do.
1035 service_state = ServiceState::STOPPING;
1036 waiting_for_deps = true;
1038 // If we get here, we are in STARTED state; stop all dependents.
1039 if (stopDependents()) {
1044 bool ServiceRecord::stopCheckDependents() noexcept
1046 bool all_deps_stopped = true;
1047 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1048 if (! (*i)->is_stopped()) {
1049 all_deps_stopped = false;
1054 return all_deps_stopped;
1057 bool ServiceRecord::stopDependents() noexcept
1059 bool all_deps_stopped = true;
1060 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1061 if (! (*i)->is_stopped()) {
1062 // Note we check *first* since if the dependent service is not stopped,
1063 // 1. We will issue a stop to it shortly and
1064 // 2. It will notify us when stopped, at which point the stopCheckDependents()
1065 // check is run anyway.
1066 all_deps_stopped = false;
1072 return all_deps_stopped;
1075 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1076 void ServiceRecord::all_deps_stopped() noexcept
1078 waiting_for_deps = false;
1082 void base_process_service::all_deps_stopped() noexcept
1084 waiting_for_deps = false;
1086 // The process is still kicking on - must actually kill it.
1087 if (! onstart_flags.no_sigterm) {
1090 if (term_signal != -1) {
1091 kill(pid, term_signal);
1094 // In most cases, the rest is done in process_child_callback.
1095 // If we are a BGPROCESS and the process is not our immediate child, however, that
1096 // won't work - check for this now:
1097 if (service_type == ServiceType::BGPROCESS) {
1099 pid_t r = waitpid(pid, &status, WNOHANG);
1100 if (r == -1 && errno == ECHILD) {
1101 // We can't track this child (or it's terminated already)
1104 else if (r == pid) {
1105 // Process may have died due to signal since we explicitly requested it to
1106 // stop by signalling it; no need to log any termination status.
1112 // The process is already dead.
1117 void scripted_service::all_deps_stopped() noexcept
1119 waiting_for_deps = false;
1120 if (stop_command.length() == 0) {
1123 else if (! start_ps_process(stop_arg_parts, false)) {
1124 // Couldn't execute stop script, but there's not much we can do:
1129 void ServiceRecord::unpin() noexcept
1131 if (pinned_started) {
1132 pinned_started = false;
1133 if (desired_state == ServiceState::STOPPED) {
1135 service_set->processQueues(false);
1138 if (pinned_stopped) {
1139 pinned_stopped = false;
1140 if (desired_state == ServiceState::STARTED) {
1142 service_set->processQueues(true);
1147 void ServiceRecord::queueForConsole() noexcept
1149 service_set->append_console_queue(this);
1152 void ServiceRecord::releaseConsole() noexcept
1154 service_set->pullConsoleQueue();
1157 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1162 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
1167 base_process_service::base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
1168 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1169 sr_list * pdepends_on, sr_list * pdepends_soft)
1170 : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
1171 pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
1173 restart_timer.service = this;
1174 restart_timer.add_timer(eventLoop);
1177 void base_process_service::restart_ps_process() noexcept
1179 timespec current_time;
1180 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1181 auto tdiff_s = current_time.tv_sec - last_start_time.tv_sec;
1182 decltype(current_time.tv_nsec) tdiff_ns;
1183 if (current_time.tv_nsec >= last_start_time.tv_nsec) {
1184 tdiff_ns = current_time.tv_nsec - last_start_time.tv_nsec;
1188 tdiff_ns = 1000000000 - (last_start_time.tv_nsec - current_time.tv_nsec);
1191 if (tdiff_s > 0 || tdiff_ns > 100000000) {
1197 timeout.tv_sec = tdiff_s;
1198 timeout.tv_nsec = tdiff_ns;
1199 restart_timer.arm_timer_rel(eventLoop, timeout);
1203 dasynq::rearm process_restart_timer::timer_expiry(EventLoop_t &, int expiry_count)
1205 return service->restart_timer_expired();
1208 dasynq::rearm base_process_service::restart_timer_expired() noexcept
1210 // begin starting process:
1212 return dasynq::rearm::DISARM;