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 bool will_restart = (desired_state == ServiceState::STARTED)
82 && service_set->get_auto_restart();
85 for (auto dependency : soft_dpts) {
86 if (dependency->holding_acq) {
87 dependency->holding_acq = false;
93 for (auto dependency : depends_on) {
94 // we signal dependencies in case they are waiting for us to stop - but only if we won't
95 // restart or if they are stopping uninterruptibly.
96 if (! will_restart || ! dependency->can_interrupt_stop()) {
97 dependency->dependentStopped();
101 service_state = ServiceState::STOPPED;
104 // Desired state is "started".
106 service_set->addToStartQueue(this);
109 if (socket_fd != -1) {
114 if (start_explicit) {
115 start_explicit = false;
118 else if (required_by == 0) {
119 service_set->service_inactive(this);
123 logServiceStopped(service_name);
124 notifyListeners(ServiceEvent::STOPPED);
127 dasynq::rearm ServiceChildWatcher::status_change(EventLoop_t &loop, pid_t child, int status) noexcept
129 base_process_service *sr = service;
132 sr->exit_status = status;
134 // Ok, for a process service, any process death which we didn't rig
135 // ourselves is a bit... unexpected. Probably, the child died because
136 // we asked it to (sr->service_state == STOPPING). But even if
137 // we didn't, there's not much we can do.
139 if (sr->waiting_for_execstat) {
140 // We still don't have an exec() status from the forked child, wait for that
141 // before doing any further processing.
142 return rearm::REMOVE;
145 // Must deregister now since handle_exit_status might result in re-launch:
146 deregister(loop, child);
148 sr->handle_exit_status(status);
149 return rearm::REMOVED;
152 bool ServiceRecord::do_auto_restart() noexcept
155 return service_set->get_auto_restart();
160 void process_service::handle_exit_status(int exit_status) noexcept
162 bool did_exit = WIFEXITED(exit_status);
163 bool was_signalled = WIFSIGNALED(exit_status);
165 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
167 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
169 else if (was_signalled) {
170 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
174 if (service_state == ServiceState::STARTING) {
175 if (did_exit && WEXITSTATUS(exit_status) == 0) {
182 else if (service_state == ServiceState::STOPPING) {
183 // We won't log a non-zero exit status or termination due to signal here -
184 // we assume that the process died because we signalled it.
187 else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
188 // TODO if we are pinned-started then we should probably check
189 // that dependencies have started before trying to re-start the
191 restart_ps_process();
195 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
198 service_set->processQueues(false);
201 void bgproc_service::handle_exit_status(int exit_status) noexcept
203 bool did_exit = WIFEXITED(exit_status);
204 bool was_signalled = WIFSIGNALED(exit_status);
206 if (exit_status != 0 && service_state != ServiceState::STOPPING) {
208 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
210 else if (was_signalled) {
211 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
215 if (doing_recovery) {
217 doing_recovery = false;
218 bool need_stop = false;
219 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
223 // We need to re-read the PID, since it has now changed.
224 if (pid_file.length() != 0) {
225 if (! read_pid_file()) {
232 // Failed startup: no auto-restart.
233 desired_state = ServiceState::STOPPED;
235 service_set->processQueues(false);
241 if (service_state == ServiceState::STARTING) {
242 // POSIX requires that if the process exited clearly with a status code of 0,
243 // the exit status value will be 0:
244 if (exit_status == 0) {
245 if (pid_file.length() != 0 && ! read_pid_file()) {
256 else if (service_state == ServiceState::STOPPING) {
257 // We won't log a non-zero exit status or termination due to signal here -
258 // we assume that the process died because we signalled it.
261 else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
262 // TODO if we are pinned-started then we should probably check
263 // that dependencies have started before trying to re-start the
265 doing_recovery = true;
266 restart_ps_process();
270 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
273 service_set->processQueues(false);
276 void scripted_service::handle_exit_status(int exit_status) noexcept
278 bool did_exit = WIFEXITED(exit_status);
279 bool was_signalled = WIFSIGNALED(exit_status);
281 if (service_state == ServiceState::STOPPING) {
282 if (did_exit && WEXITSTATUS(exit_status) == 0) {
286 // ??? failed to stop! Let's log it as info:
288 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
290 else if (was_signalled) {
291 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
293 // Just assume that we stopped, so that any dependencies
297 service_set->processQueues(false);
300 if (exit_status == 0) {
306 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
308 else if (was_signalled) {
309 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
313 service_set->processQueues(true);
317 rearm ServiceIoWatcher::fd_event(EventLoop_t &loop, int fd, int flags) noexcept
319 base_process_service *sr = service;
320 sr->waiting_for_execstat = false;
323 int r = read(get_watched_fd(), &exec_status, sizeof(int));
325 close(get_watched_fd());
328 // We read an errno code; exec() failed, and the service startup failed.
330 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
331 if (sr->service_state == ServiceState::STARTING) {
332 sr->failed_to_start();
334 else if (sr->service_state == ServiceState::STOPPING) {
335 // Must be a scripted service. We've logged the failure, but it's probably better
336 // not to leave the service in STARTED state:
342 if (sr->service_type == ServiceType::PROCESS) {
343 // This could be a smooth recovery (state already STARTED). Even more, the process
344 // might be stopped (and killed via a signal) during smooth recovery. We don't to
345 // process startup again in either case, so we check for state STARTING:
346 if (sr->service_state == ServiceState::STARTING) {
352 // Somehow the process managed to complete before we even saw the status.
353 sr->handle_exit_status(sr->exit_status);
357 sr->service_set->processQueues(true);
359 return rearm::REMOVED;
362 void ServiceRecord::require() noexcept
364 if (required_by++ == 0) {
366 if (! prop_require) {
368 prop_release = false;
369 service_set->addToPropQueue(this);
372 if (service_state == ServiceState::STOPPED) {
373 // (In any other state, the service is already considered active.)
374 service_set->service_active(this);
379 void ServiceRecord::release() noexcept
381 if (--required_by == 0) {
382 desired_state = ServiceState::STOPPED;
383 // Can stop, and can release dependencies now:
385 prop_require = false;
386 service_set->addToPropQueue(this);
387 if (service_state != ServiceState::STOPPED) {
388 service_set->addToStopQueue(this);
391 service_set->service_inactive(this);
396 void ServiceRecord::release_dependencies() noexcept
398 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
402 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
403 ServiceRecord * to = i->getTo();
404 if (i->holding_acq) {
406 i->holding_acq = false;
411 void ServiceRecord::start(bool activate) noexcept
413 if (activate && ! start_explicit) {
415 start_explicit = true;
418 if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
420 desired_state = ServiceState::STARTED;
421 service_set->addToStartQueue(this);
424 void ServiceRecord::do_propagation() noexcept
427 // Need to require all our dependencies
428 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
432 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
433 ServiceRecord * to = i->getTo();
435 i->holding_acq = true;
438 prop_require = false;
442 release_dependencies();
443 prop_release = false;
447 prop_failure = false;
448 failed_to_start(true);
451 if (waiting_for_deps) {
452 if (service_state == ServiceState::STARTING) {
453 if (startCheckDependencies(false)) {
457 else if (service_state == ServiceState::STOPPING) {
458 if (stopCheckDependents()) {
465 void ServiceRecord::execute_transition() noexcept
467 bool is_started = (service_state == ServiceState::STARTED)
468 || (service_state == ServiceState::STARTING && can_interrupt_start());
469 bool is_stopped = (service_state == ServiceState::STOPPED)
470 || (service_state == ServiceState::STOPPING && can_interrupt_stop());
472 if (is_started && (desired_state == ServiceState::STOPPED || force_stop)) {
473 if (! pinned_started) {
477 else if (is_stopped && desired_state == ServiceState::STARTED) {
478 if (! pinned_stopped) {
484 void ServiceRecord::do_start() noexcept
486 if (pinned_stopped) return;
488 if (service_state != ServiceState::STOPPED) {
489 // We're already starting/started, or we are stopping and need to wait for
490 // that the complete.
491 if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
494 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
495 // but if so they are waiting (for us), so they too can be instantly returned to
497 notifyListeners(ServiceEvent::STOPCANCELLED);
500 service_state = ServiceState::STARTING;
502 waiting_for_deps = true;
504 // Ask dependencies to start, mark them as being waited on.
505 if (! startCheckDependencies(true)) {
509 // Actually start this service.
513 void ServiceRecord::dependencyStarted() noexcept
515 if (service_state == ServiceState::STARTING && waiting_for_deps) {
516 service_set->addToPropQueue(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;
536 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
537 ServiceRecord * to = i->getTo();
539 if (to->service_state != ServiceState::STARTED) {
541 i->waiting_on = true;
542 all_deps_started = false;
545 i->waiting_on = false;
548 else if (i->waiting_on) {
549 if (to->service_state != ServiceState::STARTING) {
550 // Service has either started or is no longer starting
551 i->waiting_on = false;
554 // We are still waiting on this service
560 return all_deps_started;
563 bool ServiceRecord::open_socket() noexcept
565 if (socket_path.empty() || socket_fd != -1) {
566 // No socket, or already open
570 const char * saddrname = socket_path.c_str();
571 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
573 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
574 if (name == nullptr) {
575 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
579 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
582 name->sun_family = AF_UNIX;
583 strcpy(name->sun_path, saddrname);
585 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
587 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
592 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
593 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
601 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
602 // use chown and chmod instead.
603 if (chown(saddrname, socket_uid, socket_gid)) {
604 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
609 if (chmod(saddrname, socket_perms) == -1) {
610 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
615 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
616 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
625 void ServiceRecord::allDepsStarted(bool has_console) noexcept
627 if (onstart_flags.starts_on_console && ! has_console) {
628 waiting_for_deps = true;
633 waiting_for_deps = false;
635 if (! open_socket()) {
639 bool start_success = start_ps_process();
640 if (! start_success) {
645 void ServiceRecord::acquiredConsole() noexcept
647 if (service_state != ServiceState::STARTING) {
648 // We got the console but no longer want it.
651 else if (startCheckDependencies(false)) {
652 allDepsStarted(true);
655 // We got the console but can't use it yet.
660 bool bgproc_service::read_pid_file() noexcept
662 const char *pid_file_c = pid_file.c_str();
663 int fd = open(pid_file_c, O_CLOEXEC);
665 char pidbuf[21]; // just enought to hold any 64-bit integer
666 int r = read(fd, pidbuf, 20);
668 pidbuf[r] = 0; // store nul terminator
669 pid = std::atoi(pidbuf);
670 if (kill(pid, 0) == 0) {
671 child_listener.add_watch(eventLoop, pid);
674 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
684 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
689 void ServiceRecord::started() noexcept
691 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
692 tcsetpgrp(0, getpgrp());
696 logServiceStarted(service_name);
697 service_state = ServiceState::STARTED;
698 notifyListeners(ServiceEvent::STARTED);
700 if (onstart_flags.rw_ready) {
701 open_control_socket();
703 if (onstart_flags.log_ready) {
704 setup_external_log();
707 if (force_stop || desired_state == ServiceState::STOPPED) {
709 service_set->addToStopQueue(this);
713 // Notify any dependents whose desired state is STARTED:
714 for (auto i = dependents.begin(); i != dependents.end(); i++) {
715 (*i)->dependencyStarted();
717 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
718 (*i)->getFrom()->dependencyStarted();
722 void ServiceRecord::failed_to_start(bool depfailed) noexcept
724 if (!depfailed && onstart_flags.starts_on_console) {
725 tcsetpgrp(0, getpgrp());
729 logServiceFailed(service_name);
730 service_state = ServiceState::STOPPED;
731 if (start_explicit) {
732 start_explicit = false;
735 notifyListeners(ServiceEvent::FAILEDSTART);
737 // Cancel start of dependents:
738 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
739 if ((*i)->service_state == ServiceState::STARTING) {
740 (*i)->prop_failure = true;
741 service_set->addToPropQueue(*i);
744 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
745 // We can send 'start', because this is only a soft dependency.
746 // Our startup failure means that they don't have to wait for us.
747 if ((*i)->waiting_on) {
748 (*i)->holding_acq = false;
749 (*i)->waiting_on = false;
750 (*i)->getFrom()->dependencyStarted();
756 bool ServiceRecord::start_ps_process() noexcept
758 // default implementation: there is no process, so we are started.
763 bool base_process_service::start_ps_process() noexcept
766 restart_ps_process();
770 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
774 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
776 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
777 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
778 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
779 // is written to the pipe, and the parent can read it.
781 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
784 if (pipe2(pipefd, O_CLOEXEC)) {
785 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
789 const char * logfile = this->logfile.c_str();
791 logfile = "/dev/null";
794 bool child_status_registered = false;
795 ControlConn *control_conn = nullptr;
797 int control_socket[2] = {-1, -1};
798 if (onstart_flags.pass_cs_fd) {
799 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
800 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
804 // Make the server side socket close-on-exec:
805 int fdflags = fcntl(control_socket[0], F_GETFD);
806 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
809 control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
811 catch (std::exception &exc) {
812 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
817 // Set up complete, now fork and exec:
822 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
823 child_status_registered = true;
825 forkpid = child_listener.fork(eventLoop);
827 catch (std::exception &e) {
828 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
833 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
837 close(pipefd[1]); // close the 'other end' fd
838 if (control_socket[1] != -1) {
839 close(control_socket[1]);
843 waiting_for_execstat = true;
850 if (child_status_registered) {
851 child_status_listener.deregister(eventLoop);
854 if (onstart_flags.pass_cs_fd) {
858 close(control_socket[0]);
859 close(control_socket[1]);
869 void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
870 int wpipefd, int csfd) noexcept
872 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
873 // from here until exit().
875 // If the console already has a session leader, presumably it is us. On the other hand
876 // if it has no session leader, and we don't create one, then control inputs such as
877 // ^C will have no effect.
878 bool do_set_ctty = (tcgetsid(0) == -1);
880 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
881 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
882 sigset_t sigwait_set;
884 sigfillset(&sigall_set);
885 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
886 sigdelset(&sigwait_set, SIGCHLD);
887 sigdelset(&sigwait_set, SIGINT);
888 sigdelset(&sigwait_set, SIGTERM);
890 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
891 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
892 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
893 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
896 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
897 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
898 char csenvbuf[csenvbufsz];
900 int minfd = (socket_fd == -1) ? 3 : 4;
902 // Move wpipefd/csfd to another fd if necessary
903 if (wpipefd < minfd) {
904 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
905 if (wpipefd == -1) goto failure_out;
908 if (csfd != -1 && csfd < minfd) {
909 csfd = fcntl(csfd, F_DUPFD, minfd);
910 if (csfd == -1) goto failure_out;
913 if (socket_fd != -1) {
915 if (dup2(socket_fd, 3) == -1) goto failure_out;
916 if (socket_fd != 3) {
920 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
921 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
922 if (putenv(nbuf)) goto failure_out;
926 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
927 if (putenv(csenvbuf)) goto failure_out;
931 // Re-set stdin, stdout, stderr
932 close(0); close(1); close(2);
934 if (open("/dev/null", O_RDONLY) == 0) {
935 // stdin = 0. That's what we should have; proceed with opening
936 // stdout and stderr.
937 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
940 if (dup2(1, 2) != 2) {
944 else goto failure_out;
946 // We have the option of creating a new process group and/or session. If
947 // we just create a new process group, the child process cannot make itself
948 // a session leader if it wants to do that (eg getty/login will generally
949 // want this). If we do neither, and we are running with a controlling
950 // terminal, a ^C or similar will also affect the child process.
954 // "run on console" - run as a foreground job on the terminal/console device
956 // if do_set_ctty is false, we are the session leader; we are probably running
957 // as a user process. Don't create a new session leader in that case, and run
958 // as part of the parent session. Otherwise, the new session cannot claim the
959 // terminal as a controlling terminal (it is already claimed), meaning that it
960 // will not see control signals from ^C etc.
963 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
964 signal(SIGTSTP, SIG_IGN);
966 // Become session leader
968 ioctl(0, TIOCSCTTY, 0);
971 tcsetpgrp(0, getpgrp());
974 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
976 execvp(args[0], const_cast<char **>(args));
978 // If we got here, the exec failed:
980 int exec_status = errno;
981 write(wpipefd, &exec_status, sizeof(int));
985 // Mark this and all dependent services as force-stopped.
986 void ServiceRecord::forceStop() noexcept
988 if (service_state != ServiceState::STOPPED) {
990 service_set->addToStopQueue(this);
994 void ServiceRecord::dependentStopped() noexcept
996 if (service_state == ServiceState::STOPPING && waiting_for_deps) {
997 service_set->addToPropQueue(this);
1001 void ServiceRecord::stop(bool bring_down) noexcept
1003 if (start_explicit) {
1004 start_explicit = false;
1008 if (bring_down && desired_state != ServiceState::STOPPED) {
1009 desired_state = ServiceState::STOPPED;
1010 service_set->addToStopQueue(this);
1014 void ServiceRecord::do_stop() noexcept
1016 if (pinned_started) return;
1018 if (service_state != ServiceState::STARTED) {
1019 if (service_state == ServiceState::STARTING) {
1020 if (! can_interrupt_start()) {
1021 // Well this is awkward: we're going to have to continue
1022 // starting, but we don't want any dependents to think that
1023 // they are still waiting to start.
1024 // Make sure they remain stopped:
1029 // We must have had desired_state == STARTED.
1030 notifyListeners(ServiceEvent::STARTCANCELLED);
1032 // Reaching this point, we have can_interrupt_start() == true. So,
1033 // we can stop. Dependents might be starting, but they must be
1034 // waiting on us, so they should also be immediately stoppable.
1035 // Fall through to below,.
1038 // If we're starting we need to wait for that to complete.
1039 // If we're already stopping/stopped there's nothing to do.
1044 service_state = ServiceState::STOPPING;
1045 waiting_for_deps = true;
1047 // If we get here, we are in STARTED state; stop all dependents.
1048 if (stopDependents()) {
1053 bool ServiceRecord::stopCheckDependents() noexcept
1055 bool all_deps_stopped = true;
1056 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1057 if (! (*i)->is_stopped()) {
1058 all_deps_stopped = false;
1063 return all_deps_stopped;
1066 bool ServiceRecord::stopDependents() noexcept
1068 bool all_deps_stopped = true;
1069 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1070 if (! (*i)->is_stopped()) {
1071 // Note we check *first* since if the dependent service is not stopped,
1072 // 1. We will issue a stop to it shortly and
1073 // 2. It will notify us when stopped, at which point the stopCheckDependents()
1074 // check is run anyway.
1075 all_deps_stopped = false;
1081 return all_deps_stopped;
1084 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1085 void ServiceRecord::all_deps_stopped() noexcept
1087 waiting_for_deps = false;
1091 void base_process_service::all_deps_stopped() noexcept
1093 waiting_for_deps = false;
1095 // The process is still kicking on - must actually kill it.
1096 if (! onstart_flags.no_sigterm) {
1099 if (term_signal != -1) {
1100 kill(pid, term_signal);
1103 // In most cases, the rest is done in process_child_callback.
1104 // If we are a BGPROCESS and the process is not our immediate child, however, that
1105 // won't work - check for this now:
1106 if (service_type == ServiceType::BGPROCESS) {
1108 pid_t r = waitpid(pid, &status, WNOHANG);
1109 if (r == -1 && errno == ECHILD) {
1110 // We can't track this child (or it's terminated already)
1113 else if (r == pid) {
1114 // Process may have died due to signal since we explicitly requested it to
1115 // stop by signalling it; no need to log any termination status.
1121 // The process is already dead.
1126 void scripted_service::all_deps_stopped() noexcept
1128 waiting_for_deps = false;
1129 if (stop_command.length() == 0) {
1132 else if (! start_ps_process(stop_arg_parts, false)) {
1133 // Couldn't execute stop script, but there's not much we can do:
1138 void ServiceRecord::unpin() noexcept
1140 if (pinned_started) {
1141 pinned_started = false;
1142 if (desired_state == ServiceState::STOPPED) {
1144 service_set->processQueues(false);
1147 if (pinned_stopped) {
1148 pinned_stopped = false;
1149 if (desired_state == ServiceState::STARTED) {
1151 service_set->processQueues(true);
1156 void ServiceRecord::queueForConsole() noexcept
1158 service_set->append_console_queue(this);
1161 void ServiceRecord::releaseConsole() noexcept
1163 service_set->pullConsoleQueue();
1166 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1171 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
1176 base_process_service::base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
1177 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1178 sr_list * pdepends_on, sr_list * pdepends_soft)
1179 : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
1180 pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
1182 restart_timer.service = this;
1183 restart_timer.add_timer(eventLoop);
1186 void base_process_service::do_restart() noexcept
1190 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1191 // the process should be granted access to the console:
1192 bool on_console = service_state == ServiceState::STARTING
1193 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1195 if (! start_ps_process(exec_arg_parts, on_console)) {
1197 if (service_state == ServiceState::STARTING) {
1201 desired_state = ServiceState::STOPPED;
1204 service_set->processQueues();
1208 void base_process_service::restart_ps_process() noexcept
1210 timespec current_time;
1211 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1212 auto tdiff_s = current_time.tv_sec - last_start_time.tv_sec;
1213 decltype(current_time.tv_nsec) tdiff_ns;
1214 if (current_time.tv_nsec >= last_start_time.tv_nsec) {
1215 tdiff_ns = current_time.tv_nsec - last_start_time.tv_nsec;
1219 tdiff_ns = 1000000000 - (last_start_time.tv_nsec - current_time.tv_nsec);
1222 if (tdiff_s > 0 || tdiff_ns > 200000000) {
1229 timeout.tv_nsec = 200000000 - tdiff_ns;
1230 restart_timer.arm_timer_rel(eventLoop, timeout);
1234 dasynq::rearm process_restart_timer::timer_expiry(EventLoop_t &, int expiry_count)
1236 service->do_restart();
1237 return dasynq::rearm::DISARM;