10 #include <sys/ioctl.h>
12 #include <sys/socket.h>
18 #include "dinit-log.h"
19 #include "dinit-socket.h"
22 * service.cc - Service management.
23 * See service.h for details.
27 void open_control_socket(bool report_ro_failure = true) noexcept;
28 void setup_external_log() noexcept;
29 extern eventloop_t eventLoop;
31 // Find the requested service by name
32 static service_record * find_service(const std::list<service_record *> & records,
33 const char *name) noexcept
36 list<service_record *>::const_iterator i = records.begin();
37 for ( ; i != records.end(); i++ ) {
38 if (strcmp((*i)->getServiceName().c_str(), name) == 0) {
42 return (service_record *)0;
45 service_record * service_set::find_service(const std::string &name) noexcept
47 return ::find_service(records, name.c_str());
50 void service_set::stopService(const std::string & name) noexcept
52 service_record *record = find_service(name);
53 if (record != nullptr) {
59 // Called when a service has actually stopped; dependents have stopped already, unless this stop
60 // is due to an unexpected process termination.
61 void service_record::stopped() noexcept
63 if (onstart_flags.runs_on_console) {
64 tcsetpgrp(0, getpgrp());
65 discard_console_log_buffer();
71 // If we are a soft dependency of another target, break the acquisition from that target now:
72 for (auto dependent : soft_dpts) {
73 if (dependent->holding_acq) {
74 dependent->holding_acq = false;
79 bool will_restart = (desired_state == service_state_t::STARTED)
80 && services->get_auto_restart();
82 for (auto dependency : depends_on) {
83 // we signal dependencies in case they are waiting for us to stop:
84 dependency->dependentStopped();
87 service_state = service_state_t::STOPPED;
90 // Desired state is "started".
95 if (socket_fd != -1) {
100 if (start_explicit) {
101 start_explicit = false;
104 else if (required_by == 0) {
105 services->service_inactive(this);
109 logServiceStopped(service_name);
110 notifyListeners(service_event::STOPPED);
113 dasynq::rearm service_child_watcher::status_change(eventloop_t &loop, pid_t child, int status) noexcept
115 base_process_service *sr = service;
118 sr->exit_status = status;
120 // Ok, for a process service, any process death which we didn't rig
121 // ourselves is a bit... unexpected. Probably, the child died because
122 // we asked it to (sr->service_state == STOPPING). But even if
123 // we didn't, there's not much we can do.
125 if (sr->waiting_for_execstat) {
126 // We still don't have an exec() status from the forked child, wait for that
127 // before doing any further processing.
128 return rearm::REMOVE;
131 // Must deregister now since handle_exit_status might result in re-launch:
132 deregister(loop, child);
134 sr->handle_exit_status(status);
135 return rearm::REMOVED;
138 bool service_record::do_auto_restart() noexcept
141 return services->get_auto_restart();
146 void service_record::emergency_stop() noexcept
148 if (! do_auto_restart() && start_explicit) {
149 start_explicit = false;
157 void process_service::handle_exit_status(int exit_status) noexcept
159 bool did_exit = WIFEXITED(exit_status);
160 bool was_signalled = WIFSIGNALED(exit_status);
162 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
164 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
166 else if (was_signalled) {
167 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
171 if (service_state == service_state_t::STARTING) {
172 if (did_exit && WEXITSTATUS(exit_status) == 0) {
179 else if (service_state == service_state_t::STOPPING) {
180 // We won't log a non-zero exit status or termination due to signal here -
181 // we assume that the process died because we signalled it.
184 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
185 // TODO if we are pinned-started then we should probably check
186 // that dependencies have started before trying to re-start the
188 if (! restart_ps_process()) {
190 services->process_queues();
197 services->process_queues();
200 void bgproc_service::handle_exit_status(int exit_status) noexcept
203 bool did_exit = WIFEXITED(exit_status);
204 bool was_signalled = WIFSIGNALED(exit_status);
206 if (exit_status != 0 && service_state != service_state_t::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) {
216 doing_recovery = false;
217 bool need_stop = false;
218 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
222 // We need to re-read the PID, since it has now changed.
223 if (pid_file.length() != 0) {
224 auto pid_result = read_pid_file(&exit_status);
225 switch (pid_result) {
226 case pid_result_t::FAILED:
227 // Failed startup: no auto-restart.
230 case pid_result_t::TERMINATED:
232 case pid_result_t::OK:
239 // Failed startup: no auto-restart.
241 services->process_queues();
247 if (service_state == service_state_t::STARTING) {
248 // POSIX requires that if the process exited clearly with a status code of 0,
249 // the exit status value will be 0:
250 if (exit_status == 0) {
251 auto pid_result = read_pid_file(&exit_status);
252 switch (pid_result) {
253 case pid_result_t::FAILED:
254 // Failed startup: no auto-restart.
257 case pid_result_t::TERMINATED:
258 // started, but immediately terminated
261 case pid_result_t::OK:
270 else if (service_state == service_state_t::STOPPING) {
271 // We won't log a non-zero exit status or termination due to signal here -
272 // we assume that the process died because we signalled it.
275 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
276 // TODO if we are pinned-started then we should probably check
277 // that dependencies have started before trying to re-start the
279 doing_recovery = true;
280 if (! restart_ps_process()) {
282 services->process_queues();
287 // we must be STARTED
288 if (! do_auto_restart() && start_explicit) {
289 start_explicit = false;
296 services->process_queues();
299 void scripted_service::handle_exit_status(int exit_status) noexcept
301 bool did_exit = WIFEXITED(exit_status);
302 bool was_signalled = WIFSIGNALED(exit_status);
304 if (service_state == service_state_t::STOPPING) {
305 if (did_exit && WEXITSTATUS(exit_status) == 0) {
309 // ??? failed to stop! Let's log it as info:
311 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
313 else if (was_signalled) {
314 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
316 // Just assume that we stopped, so that any dependencies
320 services->process_queues();
323 if (exit_status == 0) {
329 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
331 else if (was_signalled) {
332 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
336 services->process_queues();
340 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
342 base_process_service *sr = service;
343 sr->waiting_for_execstat = false;
346 int r = read(get_watched_fd(), &exec_status, sizeof(int));
348 close(get_watched_fd());
351 // We read an errno code; exec() failed, and the service startup failed.
353 sr->child_listener.deregister(eventLoop, sr->pid);
356 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
357 if (sr->service_state == service_state_t::STARTING) {
358 sr->failed_to_start();
360 else if (sr->service_state == service_state_t::STOPPING) {
361 // Must be a scripted service. We've logged the failure, but it's probably better
362 // not to leave the service in STARTED state:
368 if (sr->record_type == service_type::PROCESS) {
369 // This could be a smooth recovery (state already STARTED). Even more, the process
370 // might be stopped (and killed via a signal) during smooth recovery. We don't to
371 // process startup again in either case, so we check for state STARTING:
372 if (sr->service_state == service_state_t::STARTING) {
378 // Somehow the process managed to complete before we even saw the status.
379 sr->handle_exit_status(sr->exit_status);
383 sr->services->process_queues();
385 return rearm::REMOVED;
388 void service_record::require() noexcept
390 if (required_by++ == 0) {
391 prop_require = !prop_release;
392 prop_release = false;
393 services->addToPropQueue(this);
397 void service_record::release() noexcept
399 if (--required_by == 0) {
400 desired_state = service_state_t::STOPPED;
402 // Can stop, and can release dependencies now. We don't need to issue a release if
403 // the require was pending though:
404 prop_release = !prop_require;
405 prop_require = false;
406 services->addToPropQueue(this);
408 if (service_state == service_state_t::STOPPED) {
409 services->service_inactive(this);
417 void service_record::release_dependencies() noexcept
419 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
423 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
424 service_record * to = i->getTo();
425 if (i->holding_acq) {
427 i->holding_acq = false;
432 void service_record::start(bool activate) noexcept
434 if (activate && ! start_explicit) {
436 start_explicit = true;
439 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
441 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
442 desired_state = service_state_t::STARTED;
444 if (service_state != service_state_t::STOPPED) {
445 // We're already starting/started, or we are stopping and need to wait for
446 // that the complete.
447 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
450 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
451 // but if so they are waiting (for us), so they too can be instantly returned to
453 notifyListeners(service_event::STOPCANCELLED);
455 else if (! was_active) {
456 services->service_active(this);
459 service_state = service_state_t::STARTING;
460 waiting_for_deps = true;
462 if (startCheckDependencies(true)) {
463 services->addToStartQueue(this);
467 void service_record::do_propagation() noexcept
470 // Need to require all our dependencies
471 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
475 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
476 service_record * to = i->getTo();
478 i->holding_acq = true;
481 prop_require = false;
485 release_dependencies();
486 prop_release = false;
490 prop_failure = false;
491 failed_to_start(true);
505 void service_record::execute_transition() noexcept
507 if (service_state == service_state_t::STARTING) {
508 if (startCheckDependencies(false)) {
509 allDepsStarted(false);
512 else if (service_state == service_state_t::STOPPING) {
513 if (stopCheckDependents()) {
519 void service_record::do_start() noexcept
521 if (pinned_stopped) return;
523 if (service_state != service_state_t::STARTING) {
527 service_state = service_state_t::STARTING;
529 waiting_for_deps = true;
531 // Ask dependencies to start, mark them as being waited on.
532 if (startCheckDependencies(false)) {
533 // Once all dependencies are started, we start properly:
538 void service_record::dependencyStarted() noexcept
540 if (service_state == service_state_t::STARTING && waiting_for_deps) {
541 services->addToStartQueue(this);
545 bool service_record::startCheckDependencies(bool start_deps) noexcept
547 bool all_deps_started = true;
549 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
550 if ((*i)->service_state != service_state_t::STARTED) {
552 all_deps_started = false;
553 (*i)->prop_start = true;
554 services->addToPropQueue(*i);
562 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
563 service_record * to = i->getTo();
565 if (to->service_state != service_state_t::STARTED) {
566 to->prop_start = true;
567 services->addToPropQueue(to);
568 i->waiting_on = true;
569 all_deps_started = false;
572 i->waiting_on = false;
575 else if (i->waiting_on) {
576 if (to->service_state != service_state_t::STARTING) {
577 // Service has either started or is no longer starting
578 i->waiting_on = false;
581 // We are still waiting on this service
587 return all_deps_started;
590 bool service_record::open_socket() noexcept
592 if (socket_path.empty() || socket_fd != -1) {
593 // No socket, or already open
597 const char * saddrname = socket_path.c_str();
598 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
600 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
601 if (name == nullptr) {
602 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
606 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
609 name->sun_family = AF_UNIX;
610 strcpy(name->sun_path, saddrname);
612 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
614 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
619 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
620 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
628 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
629 // use chown and chmod instead.
630 if (chown(saddrname, socket_uid, socket_gid)) {
631 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
636 if (chmod(saddrname, socket_perms) == -1) {
637 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
642 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
643 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
652 void service_record::allDepsStarted(bool has_console) noexcept
654 if (onstart_flags.starts_on_console && ! has_console) {
655 waiting_for_deps = true;
660 waiting_for_deps = false;
662 // We overload can_interrupt_start to check whether there is any other
663 // process (eg restart timer) that needs to finish before starting.
664 if (can_interrupt_start()) {
665 waiting_for_deps = true;
669 if (! open_socket()) {
673 bool start_success = start_ps_process();
674 if (! start_success) {
679 void service_record::acquiredConsole() noexcept
681 if (service_state != service_state_t::STARTING) {
682 // We got the console but no longer want it.
685 else if (startCheckDependencies(false)) {
686 allDepsStarted(true);
689 // We got the console but can't use it yet.
694 bgproc_service::pid_result_t
695 bgproc_service::read_pid_file(int *exit_status) noexcept
697 const char *pid_file_c = pid_file.c_str();
698 int fd = open(pid_file_c, O_CLOEXEC);
700 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
701 return pid_result_t::FAILED;
704 char pidbuf[21]; // just enough to hold any 64-bit integer
705 int r = read(fd, pidbuf, 20); // TODO signal-safe read
707 // Could not read from PID file
708 log(LogLevel::ERROR, service_name, ": could not read from pidfile; ", strerror(errno));
710 return pid_result_t::FAILED;
714 pidbuf[r] = 0; // store nul terminator
715 // TODO may need stoull; what if int isn't big enough...
716 pid = std::atoi(pidbuf);
717 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
718 if (wait_r == -1 && errno == ECHILD) {
719 // We can't track this child - check process exists:
720 if (kill(pid, 0) == 0) {
721 tracking_child = false;
722 return pid_result_t::OK;
725 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
727 return pid_result_t::FAILED;
730 else if (wait_r == pid) {
732 return pid_result_t::TERMINATED;
734 else if (wait_r == 0) {
735 // We can track the child
736 // TODO we must use a preallocated watch!!
737 child_listener.add_watch(eventLoop, pid);
738 tracking_child = true;
739 return pid_result_t::OK;
742 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
744 return pid_result_t::FAILED;
748 void service_record::started() noexcept
750 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
751 tcsetpgrp(0, getpgrp());
755 logServiceStarted(service_name);
756 service_state = service_state_t::STARTED;
757 notifyListeners(service_event::STARTED);
759 if (onstart_flags.rw_ready) {
760 open_control_socket();
762 if (onstart_flags.log_ready) {
763 setup_external_log();
766 if (force_stop || desired_state == service_state_t::STOPPED) {
772 // Notify any dependents whose desired state is STARTED:
773 for (auto i = dependents.begin(); i != dependents.end(); i++) {
774 (*i)->dependencyStarted();
776 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
777 (*i)->getFrom()->dependencyStarted();
781 void service_record::failed_to_start(bool depfailed) noexcept
783 if (!depfailed && onstart_flags.starts_on_console) {
784 tcsetpgrp(0, getpgrp());
788 logServiceFailed(service_name);
789 service_state = service_state_t::STOPPED;
790 if (start_explicit) {
791 start_explicit = false;
794 notifyListeners(service_event::FAILEDSTART);
796 // Cancel start of dependents:
797 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
798 if ((*i)->service_state == service_state_t::STARTING) {
799 (*i)->prop_failure = true;
800 services->addToPropQueue(*i);
803 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
804 // We can send 'start', because this is only a soft dependency.
805 // Our startup failure means that they don't have to wait for us.
806 if ((*i)->waiting_on) {
807 (*i)->holding_acq = false;
808 (*i)->waiting_on = false;
809 (*i)->getFrom()->dependencyStarted();
815 bool service_record::start_ps_process() noexcept
817 // default implementation: there is no process, so we are started.
822 bool base_process_service::start_ps_process() noexcept
825 return restart_ps_process();
828 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
829 restart_interval_count = 0;
830 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
834 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
836 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
837 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
838 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
839 // is written to the pipe, and the parent can read it.
841 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
844 if (pipe2(pipefd, O_CLOEXEC)) {
845 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
849 const char * logfile = this->logfile.c_str();
851 logfile = "/dev/null";
854 bool child_status_registered = false;
855 control_conn_t *control_conn = nullptr;
857 int control_socket[2] = {-1, -1};
858 if (onstart_flags.pass_cs_fd) {
859 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
860 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
864 // Make the server side socket close-on-exec:
865 int fdflags = fcntl(control_socket[0], F_GETFD);
866 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
869 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
871 catch (std::exception &exc) {
872 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
877 // Set up complete, now fork and exec:
882 // We add the status listener with a high priority (i.e. low priority value) so that process
883 // termination is handled early. This means we have always recorded that the process is
884 // terminated by the time that we handle events that might otherwise cause us to signal the
885 // process, so we avoid sending a signal to an invalid (and possibly recycled) process ID.
886 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS, true, DEFAULT_PRIORITY - 10);
887 child_status_registered = true;
889 forkpid = child_listener.fork(eventLoop);
891 catch (std::exception &e) {
892 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
897 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
901 close(pipefd[1]); // close the 'other end' fd
902 if (control_socket[1] != -1) {
903 close(control_socket[1]);
907 waiting_for_execstat = true;
914 if (child_status_registered) {
915 child_status_listener.deregister(eventLoop);
918 if (onstart_flags.pass_cs_fd) {
922 close(control_socket[0]);
923 close(control_socket[1]);
933 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
934 int wpipefd, int csfd) noexcept
936 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
937 // from here until exit().
939 // If the console already has a session leader, presumably it is us. On the other hand
940 // if it has no session leader, and we don't create one, then control inputs such as
941 // ^C will have no effect.
942 bool do_set_ctty = (tcgetsid(0) == -1);
944 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
945 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
946 sigset_t sigwait_set;
948 sigfillset(&sigall_set);
949 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
950 sigdelset(&sigwait_set, SIGCHLD);
951 sigdelset(&sigwait_set, SIGINT);
952 sigdelset(&sigwait_set, SIGTERM);
953 sigdelset(&sigwait_set, SIGQUIT);
955 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
956 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
957 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
958 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
961 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
962 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
963 char csenvbuf[csenvbufsz];
965 int minfd = (socket_fd == -1) ? 3 : 4;
967 // Move wpipefd/csfd to another fd if necessary
968 if (wpipefd < minfd) {
969 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
970 if (wpipefd == -1) goto failure_out;
973 if (csfd != -1 && csfd < minfd) {
974 csfd = fcntl(csfd, F_DUPFD, minfd);
975 if (csfd == -1) goto failure_out;
978 if (socket_fd != -1) {
980 if (dup2(socket_fd, 3) == -1) goto failure_out;
981 if (socket_fd != 3) {
985 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
986 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
987 if (putenv(nbuf)) goto failure_out;
991 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
992 if (putenv(csenvbuf)) goto failure_out;
996 // Re-set stdin, stdout, stderr
997 close(0); close(1); close(2);
999 if (open("/dev/null", O_RDONLY) == 0) {
1000 // stdin = 0. That's what we should have; proceed with opening
1001 // stdout and stderr.
1002 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1005 if (dup2(1, 2) != 2) {
1009 else goto failure_out;
1011 // We have the option of creating a session and process group, or just a new process
1012 // group. If we just create a new process group, the child process cannot make itself
1013 // a session leader if it wants to do that (eg getty/login will generally want this).
1014 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1015 // will also affect the child process (which probably isn't so bad, though since we
1016 // will handle the shutdown ourselves it's not necessary). Creating a new session
1017 // (and a new process group as part of that) seems like a safe bet, and has the
1018 // advantage of letting us signal the process as part of a process group.
1022 // "run on console" - run as a foreground job on the terminal/console device
1024 // if do_set_ctty is false, we are the session leader; we are probably running
1025 // as a user process. Don't create a new session leader in that case, and run
1026 // as part of the parent session. Otherwise, the new session cannot claim the
1027 // terminal as a controlling terminal (it is already claimed), meaning that it
1028 // will not see control signals from ^C etc.
1031 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1032 signal(SIGTSTP, SIG_IGN);
1034 // Become session leader
1036 ioctl(0, TIOCSCTTY, 0);
1039 tcsetpgrp(0, getpgrp());
1042 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1044 execvp(args[0], const_cast<char **>(args));
1046 // If we got here, the exec failed:
1048 int exec_status = errno;
1049 write(wpipefd, &exec_status, sizeof(int));
1053 // Mark this and all dependent services as force-stopped.
1054 void service_record::forceStop() noexcept
1056 if (service_state != service_state_t::STOPPED) {
1058 services->addToStopQueue(this);
1062 void service_record::dependentStopped() noexcept
1064 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1065 services->addToStopQueue(this);
1069 void service_record::stop(bool bring_down) noexcept
1071 if (start_explicit) {
1072 start_explicit = false;
1081 void service_record::do_stop() noexcept
1083 if (pinned_started) return;
1085 if (start_explicit && ! do_auto_restart()) {
1086 start_explicit = false;
1088 if (required_by == 0) return; // release will re-call us anyway
1091 if (service_state != service_state_t::STARTED) {
1092 if (service_state == service_state_t::STARTING) {
1093 if (! can_interrupt_start()) {
1094 // Well this is awkward: we're going to have to continue
1095 // starting, but we don't want any dependents to think that
1096 // they are still waiting to start.
1097 // Make sure they remain stopped:
1102 // We must have had desired_state == STARTED.
1103 notifyListeners(service_event::STARTCANCELLED);
1107 // Reaching this point, we are starting interruptibly - so we
1108 // stop now (by falling through to below).
1111 // If we're starting we need to wait for that to complete.
1112 // If we're already stopping/stopped there's nothing to do.
1117 service_state = service_state_t::STOPPING;
1118 waiting_for_deps = true;
1119 if (stopDependents()) {
1120 services->addToStopQueue(this);
1124 bool service_record::stopCheckDependents() noexcept
1126 bool all_deps_stopped = true;
1127 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1128 if (! (*i)->is_stopped()) {
1129 all_deps_stopped = false;
1134 return all_deps_stopped;
1137 bool service_record::stopDependents() noexcept
1139 bool all_deps_stopped = true;
1140 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1141 if (! (*i)->is_stopped()) {
1142 // Note we check *first* since if the dependent service is not stopped,
1143 // 1. We will issue a stop to it shortly and
1144 // 2. It will notify us when stopped, at which point the stopCheckDependents()
1145 // check is run anyway.
1146 all_deps_stopped = false;
1150 // If this service is to be forcefully stopped, dependents must also be.
1154 (*i)->prop_stop = true;
1155 services->addToPropQueue(*i);
1158 return all_deps_stopped;
1161 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1162 void service_record::all_deps_stopped() noexcept
1164 waiting_for_deps = false;
1168 void base_process_service::all_deps_stopped() noexcept
1170 waiting_for_deps = false;
1172 // The process is still kicking on - must actually kill it. We signal the process
1173 // group (-pid) rather than just the process as there's less risk then of creating
1174 // an orphaned process group:
1175 if (! onstart_flags.no_sigterm) {
1176 kill(-pid, SIGTERM);
1178 if (term_signal != -1) {
1179 kill(-pid, term_signal);
1182 // In most cases, the rest is done in handle_exit_status.
1183 // If we are a BGPROCESS and the process is not our immediate child, however, that
1184 // won't work - check for this now:
1185 if (record_type == service_type::BGPROCESS) {
1186 // TODO use 'tracking_child' instead
1188 pid_t r = waitpid(pid, &status, WNOHANG);
1189 if (r == -1 && errno == ECHILD) {
1190 // We can't track this child (or it's terminated already)
1193 else if (r == pid) {
1194 // Process may have died due to signal since we explicitly requested it to
1195 // stop by signalling it; no need to log any termination status.
1201 // The process is already dead.
1206 void scripted_service::all_deps_stopped() noexcept
1208 waiting_for_deps = false;
1209 if (stop_command.length() == 0) {
1212 else if (! start_ps_process(stop_arg_parts, false)) {
1213 // Couldn't execute stop script, but there's not much we can do:
1218 void service_record::unpin() noexcept
1220 if (pinned_started) {
1221 pinned_started = false;
1222 if (desired_state == service_state_t::STOPPED) {
1224 services->process_queues();
1227 if (pinned_stopped) {
1228 pinned_stopped = false;
1229 if (desired_state == service_state_t::STARTED) {
1231 services->process_queues();
1236 void service_record::queue_for_console() noexcept
1238 services->append_console_queue(this);
1241 void service_record::release_console() noexcept
1243 services->pull_console_queue();
1246 void service_record::interrupt_start() noexcept
1248 services->unqueue_console(this);
1251 void service_set::service_active(service_record *sr) noexcept
1256 void service_set::service_inactive(service_record *sr) noexcept
1261 base_process_service::base_process_service(service_set *sset, string name, service_type service_type_p, string &&command,
1262 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1263 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1264 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1265 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1267 restart_interval_count = 0;
1268 restart_interval_time = {0, 0};
1269 restart_timer.service = this;
1270 restart_timer.add_timer(eventLoop);
1272 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1273 restart_interval.tv_sec = 10;
1274 restart_interval.tv_nsec = 0;
1275 max_restart_interval_count = 3;
1278 void base_process_service::do_restart() noexcept
1281 waiting_restart_timer = false;
1282 restart_interval_count++;
1284 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1285 // the process should be granted access to the console:
1286 bool on_console = service_state == service_state_t::STARTING
1287 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1289 if (! start_ps_process(exec_arg_parts, on_console)) {
1290 if (service_state == service_state_t::STARTING) {
1294 desired_state = service_state_t::STOPPED;
1297 services->process_queues();
1301 bool base_process_service::restart_ps_process() noexcept
1303 using time_val = eventloop_t::time_val;
1305 time_val current_time;
1306 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1308 if (max_restart_interval_count != 0) {
1309 // Check whether we're still in the most recent restart check interval:
1310 time_val int_diff = current_time - restart_interval_time;
1311 if (int_diff < restart_interval) {
1312 if (restart_interval_count >= max_restart_interval_count) {
1313 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1318 restart_interval_time = current_time;
1319 restart_interval_count = 0;
1323 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1324 time_val tdiff = current_time - last_start_time;
1325 if (restart_delay <= tdiff) {
1326 // > restart delay (normally 200ms)
1330 time_val timeout = restart_delay - tdiff;
1331 restart_timer.arm_timer_rel(eventLoop, timeout);
1332 waiting_restart_timer = true;
1337 void base_process_service::interrupt_start() noexcept
1339 // overridden in subclasses
1340 if (waiting_restart_timer) {
1341 restart_timer.stop_timer(eventLoop);
1342 waiting_restart_timer = false;
1344 service_record::interrupt_start();
1347 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1349 service->do_restart();
1350 return dasynq::rearm::DISARM;