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->dependent_stopped();
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 notify_listeners(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::NOOP; // hold watch reservation
131 // Must stop watch now since handle_exit_status might result in re-launch:
132 // (stop_watch instead of deregister, so that we hold watch reservation).
135 sr->handle_exit_status(status);
139 bool service_record::do_auto_restart() noexcept
142 return services->get_auto_restart();
147 void service_record::emergency_stop() noexcept
149 if (! do_auto_restart() && start_explicit) {
150 start_explicit = false;
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 != service_state_t::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 == service_state_t::STARTING) {
173 if (did_exit && WEXITSTATUS(exit_status) == 0) {
180 else if (service_state == service_state_t::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 == service_state_t::STARTED && desired_state == service_state_t::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 if (! restart_ps_process()) {
191 services->process_queues();
198 services->process_queues();
201 void bgproc_service::handle_exit_status(int exit_status) noexcept
204 bool did_exit = WIFEXITED(exit_status);
205 bool was_signalled = WIFSIGNALED(exit_status);
207 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
209 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
211 else if (was_signalled) {
212 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
216 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 auto pid_result = read_pid_file(&exit_status);
226 switch (pid_result) {
227 case pid_result_t::FAILED:
228 // Failed startup: no auto-restart.
231 case pid_result_t::TERMINATED:
233 case pid_result_t::OK:
240 // Failed startup: no auto-restart.
242 services->process_queues();
248 if (service_state == service_state_t::STARTING) {
249 // POSIX requires that if the process exited clearly with a status code of 0,
250 // the exit status value will be 0:
251 if (exit_status == 0) {
252 auto pid_result = read_pid_file(&exit_status);
253 switch (pid_result) {
254 case pid_result_t::FAILED:
255 // Failed startup: no auto-restart.
258 case pid_result_t::TERMINATED:
259 // started, but immediately terminated
262 case pid_result_t::OK:
271 else if (service_state == service_state_t::STOPPING) {
272 // We won't log a non-zero exit status or termination due to signal here -
273 // we assume that the process died because we signalled it.
276 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
277 // TODO if we are pinned-started then we should probably check
278 // that dependencies have started before trying to re-start the
280 doing_recovery = true;
281 if (! restart_ps_process()) {
283 services->process_queues();
288 // we must be STARTED
289 if (! do_auto_restart() && start_explicit) {
290 start_explicit = false;
297 services->process_queues();
300 void scripted_service::handle_exit_status(int exit_status) noexcept
302 bool did_exit = WIFEXITED(exit_status);
303 bool was_signalled = WIFSIGNALED(exit_status);
305 if (service_state == service_state_t::STOPPING) {
306 if (did_exit && WEXITSTATUS(exit_status) == 0) {
310 // ??? failed to stop! Let's log it as info:
312 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
314 else if (was_signalled) {
315 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
317 // Just assume that we stopped, so that any dependencies
321 services->process_queues();
324 if (exit_status == 0) {
330 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
332 else if (was_signalled) {
333 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
337 services->process_queues();
341 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
343 base_process_service *sr = service;
344 sr->waiting_for_execstat = false;
347 int r = read(get_watched_fd(), &exec_status, sizeof(int));
349 close(get_watched_fd());
352 // We read an errno code; exec() failed, and the service startup failed.
354 sr->child_listener.deregister(eventLoop, sr->pid);
355 sr->reserved_child_watch = false;
358 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
359 if (sr->service_state == service_state_t::STARTING) {
360 sr->failed_to_start();
362 else if (sr->service_state == service_state_t::STOPPING) {
363 // Must be a scripted service. We've logged the failure, but it's probably better
364 // not to leave the service in STARTED state:
370 if (sr->record_type == service_type::PROCESS) {
371 // This could be a smooth recovery (state already STARTED). Even more, the process
372 // might be stopped (and killed via a signal) during smooth recovery. We don't to
373 // process startup again in either case, so we check for state STARTING:
374 if (sr->service_state == service_state_t::STARTING) {
380 // Somehow the process managed to complete before we even saw the status.
381 sr->handle_exit_status(sr->exit_status);
385 sr->services->process_queues();
387 return rearm::REMOVED;
390 void service_record::require() noexcept
392 if (required_by++ == 0) {
393 prop_require = !prop_release;
394 prop_release = false;
395 services->addToPropQueue(this);
399 void service_record::release() noexcept
401 if (--required_by == 0) {
402 desired_state = service_state_t::STOPPED;
404 // Can stop, and can release dependencies now. We don't need to issue a release if
405 // the require was pending though:
406 prop_release = !prop_require;
407 prop_require = false;
408 services->addToPropQueue(this);
410 if (service_state == service_state_t::STOPPED) {
411 services->service_inactive(this);
419 void service_record::release_dependencies() noexcept
421 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
425 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
426 service_record * to = i->getTo();
427 if (i->holding_acq) {
429 i->holding_acq = false;
434 void service_record::start(bool activate) noexcept
436 if (activate && ! start_explicit) {
438 start_explicit = true;
441 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
443 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
444 desired_state = service_state_t::STARTED;
446 if (service_state != service_state_t::STOPPED) {
447 // We're already starting/started, or we are stopping and need to wait for
448 // that the complete.
449 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
452 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
453 // but if so they are waiting (for us), so they too can be instantly returned to
455 notify_listeners(service_event::STOPCANCELLED);
457 else if (! was_active) {
458 services->service_active(this);
461 service_state = service_state_t::STARTING;
462 waiting_for_deps = true;
464 if (start_check_dependencies(true)) {
465 services->addToStartQueue(this);
469 void service_record::do_propagation() noexcept
472 // Need to require all our dependencies
473 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
477 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
478 service_record * to = i->getTo();
480 i->holding_acq = true;
483 prop_require = false;
487 release_dependencies();
488 prop_release = false;
492 prop_failure = false;
493 failed_to_start(true);
507 void service_record::execute_transition() noexcept
509 if (service_state == service_state_t::STARTING) {
510 if (start_check_dependencies(false)) {
511 all_deps_started(false);
514 else if (service_state == service_state_t::STOPPING) {
515 if (stop_check_dependents()) {
521 void service_record::do_start() noexcept
523 if (pinned_stopped) return;
525 if (service_state != service_state_t::STARTING) {
529 service_state = service_state_t::STARTING;
531 waiting_for_deps = true;
533 // Ask dependencies to start, mark them as being waited on.
534 if (start_check_dependencies(false)) {
535 // Once all dependencies are started, we start properly:
540 void service_record::dependencyStarted() noexcept
542 if (service_state == service_state_t::STARTING && waiting_for_deps) {
543 services->addToStartQueue(this);
547 bool service_record::start_check_dependencies(bool start_deps) noexcept
549 bool all_deps_started = true;
551 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
552 if ((*i)->service_state != service_state_t::STARTED) {
554 all_deps_started = false;
555 (*i)->prop_start = true;
556 services->addToPropQueue(*i);
564 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
565 service_record * to = i->getTo();
567 if (to->service_state != service_state_t::STARTED) {
568 to->prop_start = true;
569 services->addToPropQueue(to);
570 i->waiting_on = true;
571 all_deps_started = false;
574 i->waiting_on = false;
577 else if (i->waiting_on) {
578 if (to->service_state != service_state_t::STARTING) {
579 // Service has either started or is no longer starting
580 i->waiting_on = false;
583 // We are still waiting on this service
589 return all_deps_started;
592 bool service_record::open_socket() noexcept
594 if (socket_path.empty() || socket_fd != -1) {
595 // No socket, or already open
599 const char * saddrname = socket_path.c_str();
600 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
602 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
603 if (name == nullptr) {
604 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
608 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
611 name->sun_family = AF_UNIX;
612 strcpy(name->sun_path, saddrname);
614 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
616 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
621 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
622 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
630 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
631 // use chown and chmod instead.
632 if (chown(saddrname, socket_uid, socket_gid)) {
633 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
638 if (chmod(saddrname, socket_perms) == -1) {
639 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
644 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
645 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
654 void service_record::all_deps_started(bool has_console) noexcept
656 if (onstart_flags.starts_on_console && ! has_console) {
657 waiting_for_deps = true;
662 waiting_for_deps = false;
664 // We overload can_interrupt_start to check whether there is any other
665 // process (eg restart timer) that needs to finish before starting.
666 if (can_interrupt_start()) {
667 waiting_for_deps = true;
671 if (! open_socket()) {
675 bool start_success = start_ps_process();
676 if (! start_success) {
681 void service_record::acquiredConsole() noexcept
683 if (service_state != service_state_t::STARTING) {
684 // We got the console but no longer want it.
687 else if (start_check_dependencies(false)) {
688 all_deps_started(true);
691 // We got the console but can't use it yet.
696 bgproc_service::pid_result_t
697 bgproc_service::read_pid_file(int *exit_status) noexcept
699 const char *pid_file_c = pid_file.c_str();
700 int fd = open(pid_file_c, O_CLOEXEC);
702 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
703 return pid_result_t::FAILED;
706 char pidbuf[21]; // just enough to hold any 64-bit integer
707 int r = read(fd, pidbuf, 20); // TODO signal-safe read
709 // Could not read from PID file
710 log(LogLevel::ERROR, service_name, ": could not read from pidfile; ", strerror(errno));
712 return pid_result_t::FAILED;
716 pidbuf[r] = 0; // store nul terminator
717 // TODO may need stoull; what if int isn't big enough...
718 pid = std::atoi(pidbuf);
719 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
720 if (wait_r == -1 && errno == ECHILD) {
721 // We can't track this child - check process exists:
722 if (kill(pid, 0) == 0) {
723 tracking_child = false;
724 return pid_result_t::OK;
727 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
729 return pid_result_t::FAILED;
732 else if (wait_r == pid) {
734 return pid_result_t::TERMINATED;
736 else if (wait_r == 0) {
737 // We can track the child
738 child_listener.add_reserved(eventLoop, pid, DEFAULT_PRIORITY - 10);
739 tracking_child = true;
740 reserved_child_watch = true;
741 return pid_result_t::OK;
744 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
746 return pid_result_t::FAILED;
750 void service_record::started() noexcept
752 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
753 tcsetpgrp(0, getpgrp());
757 logServiceStarted(service_name);
758 service_state = service_state_t::STARTED;
759 notify_listeners(service_event::STARTED);
761 if (onstart_flags.rw_ready) {
762 open_control_socket();
764 if (onstart_flags.log_ready) {
765 setup_external_log();
768 if (force_stop || desired_state == service_state_t::STOPPED) {
774 // Notify any dependents whose desired state is STARTED:
775 for (auto i = dependents.begin(); i != dependents.end(); i++) {
776 (*i)->dependencyStarted();
778 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
779 (*i)->getFrom()->dependencyStarted();
783 void service_record::failed_to_start(bool depfailed) noexcept
785 if (!depfailed && onstart_flags.starts_on_console) {
786 tcsetpgrp(0, getpgrp());
790 logServiceFailed(service_name);
791 service_state = service_state_t::STOPPED;
792 if (start_explicit) {
793 start_explicit = false;
796 notify_listeners(service_event::FAILEDSTART);
798 // Cancel start of dependents:
799 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
800 if ((*i)->service_state == service_state_t::STARTING) {
801 (*i)->prop_failure = true;
802 services->addToPropQueue(*i);
805 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
806 // We can send 'start', because this is only a soft dependency.
807 // Our startup failure means that they don't have to wait for us.
808 if ((*i)->waiting_on) {
809 (*i)->holding_acq = false;
810 (*i)->waiting_on = false;
811 (*i)->getFrom()->dependencyStarted();
817 bool service_record::start_ps_process() noexcept
819 // default implementation: there is no process, so we are started.
824 bool base_process_service::start_ps_process() noexcept
827 return restart_ps_process();
830 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
831 restart_interval_count = 0;
832 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
836 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
838 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
839 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
840 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
841 // is written to the pipe, and the parent can read it.
843 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
846 if (pipe2(pipefd, O_CLOEXEC)) {
847 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
851 const char * logfile = this->logfile.c_str();
853 logfile = "/dev/null";
856 bool child_status_registered = false;
857 control_conn_t *control_conn = nullptr;
859 int control_socket[2] = {-1, -1};
860 if (onstart_flags.pass_cs_fd) {
861 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
862 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
866 // Make the server side socket close-on-exec:
867 int fdflags = fcntl(control_socket[0], F_GETFD);
868 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
871 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
873 catch (std::exception &exc) {
874 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
879 // Set up complete, now fork and exec:
884 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
885 child_status_registered = true;
887 // We specify a high priority (i.e. low priority value) so that process termination is
888 // handled early. This means we have always recorded that the process is terminated by the
889 // time that we handle events that might otherwise cause us to signal the process, so we
890 // avoid sending a signal to an invalid (and possibly recycled) process ID.
891 forkpid = child_listener.fork(eventLoop, reserved_child_watch, DEFAULT_PRIORITY - 10);
892 reserved_child_watch = true;
894 catch (std::exception &e) {
895 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
900 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
904 close(pipefd[1]); // close the 'other end' fd
905 if (control_socket[1] != -1) {
906 close(control_socket[1]);
910 waiting_for_execstat = true;
917 if (child_status_registered) {
918 child_status_listener.deregister(eventLoop);
921 if (onstart_flags.pass_cs_fd) {
925 close(control_socket[0]);
926 close(control_socket[1]);
936 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
937 int wpipefd, int csfd) noexcept
939 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
940 // from here until exit().
942 // If the console already has a session leader, presumably it is us. On the other hand
943 // if it has no session leader, and we don't create one, then control inputs such as
944 // ^C will have no effect.
945 bool do_set_ctty = (tcgetsid(0) == -1);
947 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
948 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
949 sigset_t sigwait_set;
951 sigfillset(&sigall_set);
952 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
953 sigdelset(&sigwait_set, SIGCHLD);
954 sigdelset(&sigwait_set, SIGINT);
955 sigdelset(&sigwait_set, SIGTERM);
956 sigdelset(&sigwait_set, SIGQUIT);
958 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
959 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
960 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
961 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
964 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
965 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
966 char csenvbuf[csenvbufsz];
968 int minfd = (socket_fd == -1) ? 3 : 4;
970 // Move wpipefd/csfd to another fd if necessary
971 if (wpipefd < minfd) {
972 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
973 if (wpipefd == -1) goto failure_out;
976 if (csfd != -1 && csfd < minfd) {
977 csfd = fcntl(csfd, F_DUPFD, minfd);
978 if (csfd == -1) goto failure_out;
981 if (socket_fd != -1) {
983 if (dup2(socket_fd, 3) == -1) goto failure_out;
984 if (socket_fd != 3) {
988 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
989 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
990 if (putenv(nbuf)) goto failure_out;
994 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
995 if (putenv(csenvbuf)) goto failure_out;
999 // Re-set stdin, stdout, stderr
1000 close(0); close(1); close(2);
1002 if (open("/dev/null", O_RDONLY) == 0) {
1003 // stdin = 0. That's what we should have; proceed with opening
1004 // stdout and stderr.
1005 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1008 if (dup2(1, 2) != 2) {
1012 else goto failure_out;
1014 // We have the option of creating a session and process group, or just a new process
1015 // group. If we just create a new process group, the child process cannot make itself
1016 // a session leader if it wants to do that (eg getty/login will generally want this).
1017 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1018 // will also affect the child process (which probably isn't so bad, though since we
1019 // will handle the shutdown ourselves it's not necessary). Creating a new session
1020 // (and a new process group as part of that) seems like a safe bet, and has the
1021 // advantage of letting us signal the process as part of a process group.
1025 // "run on console" - run as a foreground job on the terminal/console device
1027 // if do_set_ctty is false, we are the session leader; we are probably running
1028 // as a user process. Don't create a new session leader in that case, and run
1029 // as part of the parent session. Otherwise, the new session cannot claim the
1030 // terminal as a controlling terminal (it is already claimed), meaning that it
1031 // will not see control signals from ^C etc.
1034 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1035 signal(SIGTSTP, SIG_IGN);
1037 // Become session leader
1039 ioctl(0, TIOCSCTTY, 0);
1042 tcsetpgrp(0, getpgrp());
1045 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1047 execvp(args[0], const_cast<char **>(args));
1049 // If we got here, the exec failed:
1051 int exec_status = errno;
1052 write(wpipefd, &exec_status, sizeof(int));
1056 // Mark this and all dependent services as force-stopped.
1057 void service_record::forceStop() noexcept
1059 if (service_state != service_state_t::STOPPED) {
1061 services->addToStopQueue(this);
1065 void service_record::dependent_stopped() noexcept
1067 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1068 services->addToStopQueue(this);
1072 void service_record::stop(bool bring_down) noexcept
1074 if (start_explicit) {
1075 start_explicit = false;
1084 void service_record::do_stop() noexcept
1086 if (pinned_started) return;
1088 if (start_explicit && ! do_auto_restart()) {
1089 start_explicit = false;
1091 if (required_by == 0) return; // release will re-call us anyway
1094 if (service_state != service_state_t::STARTED) {
1095 if (service_state == service_state_t::STARTING) {
1096 if (! can_interrupt_start()) {
1097 // Well this is awkward: we're going to have to continue
1098 // starting, but we don't want any dependents to think that
1099 // they are still waiting to start.
1100 // Make sure they remain stopped:
1105 // We must have had desired_state == STARTED.
1106 notify_listeners(service_event::STARTCANCELLED);
1110 // Reaching this point, we are starting interruptibly - so we
1111 // stop now (by falling through to below).
1114 // If we're starting we need to wait for that to complete.
1115 // If we're already stopping/stopped there's nothing to do.
1120 service_state = service_state_t::STOPPING;
1121 waiting_for_deps = true;
1122 if (stop_dependents()) {
1123 services->addToStopQueue(this);
1127 bool service_record::stop_check_dependents() noexcept
1129 bool all_deps_stopped = true;
1130 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1131 if (! (*i)->is_stopped()) {
1132 all_deps_stopped = false;
1137 return all_deps_stopped;
1140 bool service_record::stop_dependents() noexcept
1142 bool all_deps_stopped = true;
1143 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1144 if (! (*i)->is_stopped()) {
1145 // Note we check *first* since if the dependent service is not stopped,
1146 // 1. We will issue a stop to it shortly and
1147 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1148 // check is run anyway.
1149 all_deps_stopped = false;
1153 // If this service is to be forcefully stopped, dependents must also be.
1157 (*i)->prop_stop = true;
1158 services->addToPropQueue(*i);
1161 return all_deps_stopped;
1164 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1165 void service_record::all_deps_stopped() noexcept
1167 waiting_for_deps = false;
1171 void base_process_service::all_deps_stopped() noexcept
1173 waiting_for_deps = false;
1175 // The process is still kicking on - must actually kill it. We signal the process
1176 // group (-pid) rather than just the process as there's less risk then of creating
1177 // an orphaned process group:
1178 if (! onstart_flags.no_sigterm) {
1179 kill(-pid, SIGTERM);
1181 if (term_signal != -1) {
1182 kill(-pid, term_signal);
1185 // In most cases, the rest is done in handle_exit_status.
1186 // If we are a BGPROCESS and the process is not our immediate child, however, that
1187 // won't work - check for this now:
1188 if (record_type == service_type::BGPROCESS) {
1189 // TODO use 'tracking_child' instead
1191 pid_t r = waitpid(pid, &status, WNOHANG);
1192 if (r == -1 && errno == ECHILD) {
1193 // We can't track this child (or it's terminated already)
1196 else if (r == pid) {
1197 // Process may have died due to signal since we explicitly requested it to
1198 // stop by signalling it; no need to log any termination status.
1204 // The process is already dead.
1209 void scripted_service::all_deps_stopped() noexcept
1211 waiting_for_deps = false;
1212 if (stop_command.length() == 0) {
1215 else if (! start_ps_process(stop_arg_parts, false)) {
1216 // Couldn't execute stop script, but there's not much we can do:
1221 void service_record::unpin() noexcept
1223 if (pinned_started) {
1224 pinned_started = false;
1225 if (desired_state == service_state_t::STOPPED) {
1227 services->process_queues();
1230 if (pinned_stopped) {
1231 pinned_stopped = false;
1232 if (desired_state == service_state_t::STARTED) {
1234 services->process_queues();
1239 void service_record::queue_for_console() noexcept
1241 services->append_console_queue(this);
1244 void service_record::release_console() noexcept
1246 services->pull_console_queue();
1249 void service_record::interrupt_start() noexcept
1251 services->unqueue_console(this);
1254 void service_set::service_active(service_record *sr) noexcept
1259 void service_set::service_inactive(service_record *sr) noexcept
1264 base_process_service::base_process_service(service_set *sset, string name, service_type service_type_p, string &&command,
1265 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1266 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1267 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1268 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1270 restart_interval_count = 0;
1271 restart_interval_time = {0, 0};
1272 restart_timer.service = this;
1273 restart_timer.add_timer(eventLoop);
1275 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1276 restart_interval.tv_sec = 10;
1277 restart_interval.tv_nsec = 0;
1278 max_restart_interval_count = 3;
1280 waiting_restart_timer = false;
1281 reserved_child_watch = false;
1284 void base_process_service::do_restart() noexcept
1287 waiting_restart_timer = false;
1288 restart_interval_count++;
1290 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1291 // the process should be granted access to the console:
1292 bool on_console = service_state == service_state_t::STARTING
1293 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1295 if (! start_ps_process(exec_arg_parts, on_console)) {
1296 if (service_state == service_state_t::STARTING) {
1300 desired_state = service_state_t::STOPPED;
1303 services->process_queues();
1307 bool base_process_service::restart_ps_process() noexcept
1309 using time_val = eventloop_t::time_val;
1311 time_val current_time;
1312 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1314 if (max_restart_interval_count != 0) {
1315 // Check whether we're still in the most recent restart check interval:
1316 time_val int_diff = current_time - restart_interval_time;
1317 if (int_diff < restart_interval) {
1318 if (restart_interval_count >= max_restart_interval_count) {
1319 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1324 restart_interval_time = current_time;
1325 restart_interval_count = 0;
1329 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1330 time_val tdiff = current_time - last_start_time;
1331 if (restart_delay <= tdiff) {
1332 // > restart delay (normally 200ms)
1336 time_val timeout = restart_delay - tdiff;
1337 restart_timer.arm_timer_rel(eventLoop, timeout);
1338 waiting_restart_timer = true;
1343 void base_process_service::interrupt_start() noexcept
1345 // overridden in subclasses
1346 if (waiting_restart_timer) {
1347 restart_timer.stop_timer(eventLoop);
1348 waiting_restart_timer = false;
1350 service_record::interrupt_start();
1353 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1355 service->do_restart();
1356 return dasynq::rearm::DISARM;