10 #include <sys/ioctl.h>
12 #include <sys/socket.h>
18 #include "dinit-log.h"
19 #include "dinit-socket.h"
20 #include "dinit-util.h"
23 * service.cc - Service management.
24 * See service.h for details.
28 void open_control_socket(bool report_ro_failure = true) noexcept;
29 void setup_external_log() noexcept;
30 extern eventloop_t eventLoop;
32 // Find the requested service by name
33 static service_record * find_service(const std::list<service_record *> & records,
34 const char *name) noexcept
37 list<service_record *>::const_iterator i = records.begin();
38 for ( ; i != records.end(); i++ ) {
39 if (strcmp((*i)->get_service_name().c_str(), name) == 0) {
43 return (service_record *)0;
46 service_record * service_set::find_service(const std::string &name) noexcept
48 return ::find_service(records, name.c_str());
51 void service_set::stop_service(const std::string & name) noexcept
53 service_record *record = find_service(name);
54 if (record != nullptr) {
60 // Called when a service has actually stopped; dependents have stopped already, unless this stop
61 // is due to an unexpected process termination.
62 void service_record::stopped() noexcept
64 if (onstart_flags.runs_on_console) {
65 tcsetpgrp(0, getpgrp());
66 discard_console_log_buffer();
72 // If we are a soft dependency of another target, break the acquisition from that target now:
73 for (auto dependent : soft_dpts) {
74 if (dependent->holding_acq) {
75 dependent->holding_acq = false;
80 bool will_restart = (desired_state == service_state_t::STARTED)
81 && services->get_auto_restart();
83 for (auto dependency : depends_on) {
84 // we signal dependencies in case they are waiting for us to stop:
85 dependency->dependent_stopped();
88 service_state = service_state_t::STOPPED;
91 // Desired state is "started".
96 if (socket_fd != -1) {
101 if (start_explicit) {
102 start_explicit = false;
105 else if (required_by == 0) {
106 services->service_inactive(this);
110 log_service_stopped(service_name);
111 notify_listeners(service_event::STOPPED);
114 dasynq::rearm service_child_watcher::status_change(eventloop_t &loop, pid_t child, int status) noexcept
116 base_process_service *sr = service;
119 sr->exit_status = status;
121 // Ok, for a process service, any process death which we didn't rig
122 // ourselves is a bit... unexpected. Probably, the child died because
123 // we asked it to (sr->service_state == STOPPING). But even if
124 // we didn't, there's not much we can do.
126 if (sr->waiting_for_execstat) {
127 // We still don't have an exec() status from the forked child, wait for that
128 // before doing any further processing.
129 return rearm::NOOP; // hold watch reservation
132 // Must stop watch now since handle_exit_status might result in re-launch:
133 // (stop_watch instead of deregister, so that we hold watch reservation).
136 if (sr->stop_timer_armed) {
137 sr->restart_timer.stop_timer(loop);
138 sr->stop_timer_armed = false;
141 sr->handle_exit_status(status);
145 bool service_record::do_auto_restart() noexcept
148 return services->get_auto_restart();
153 void service_record::emergency_stop() noexcept
155 if (! do_auto_restart() && start_explicit) {
156 start_explicit = false;
164 void process_service::handle_exit_status(int exit_status) noexcept
166 bool did_exit = WIFEXITED(exit_status);
167 bool was_signalled = WIFSIGNALED(exit_status);
170 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
172 log(loglevel_t::ERROR, "Service ", service_name, " process terminated with exit code ",
173 WEXITSTATUS(exit_status));
175 else if (was_signalled) {
176 log(loglevel_t::ERROR, "Service ", service_name, " terminated due to signal ",
177 WTERMSIG(exit_status));
181 if (service_state == service_state_t::STARTING) {
182 if (did_exit && WEXITSTATUS(exit_status) == 0) {
189 else if (service_state == service_state_t::STOPPING) {
190 // We won't log a non-zero exit status or termination due to signal here -
191 // we assume that the process died because we signalled it.
194 else if (smooth_recovery && service_state == service_state_t::STARTED
195 && desired_state == service_state_t::STARTED) {
196 do_smooth_recovery();
202 services->process_queues();
205 void base_process_service::do_smooth_recovery() noexcept
207 if (! restart_ps_process()) {
209 services->process_queues();
213 void bgproc_service::handle_exit_status(int exit_status) noexcept
216 bool did_exit = WIFEXITED(exit_status);
217 bool was_signalled = WIFSIGNALED(exit_status);
219 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
221 log(loglevel_t::ERROR, "Service ", service_name, " process terminated with exit code ",
222 WEXITSTATUS(exit_status));
224 else if (was_signalled) {
225 log(loglevel_t::ERROR, "Service ", service_name, " terminated due to signal ",
226 WTERMSIG(exit_status));
230 // This may be a "smooth recovery" where we are restarting the process while leaving the
231 // service in the STARTED state.
232 if (restarting && service_state == service_state_t::STARTED) {
234 bool need_stop = false;
235 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
239 // We need to re-read the PID, since it has now changed.
240 if (pid_file.length() != 0) {
241 auto pid_result = read_pid_file(&exit_status);
242 switch (pid_result) {
243 case pid_result_t::FAILED:
244 // Failed startup: no auto-restart.
247 case pid_result_t::TERMINATED:
249 case pid_result_t::OK:
256 // Failed startup: no auto-restart.
258 services->process_queues();
265 if (service_state == service_state_t::STARTING) {
266 // POSIX requires that if the process exited clearly with a status code of 0,
267 // the exit status value will be 0:
268 if (exit_status == 0) {
269 auto pid_result = read_pid_file(&exit_status);
270 switch (pid_result) {
271 case pid_result_t::FAILED:
272 // Failed startup: no auto-restart.
275 case pid_result_t::TERMINATED:
276 // started, but immediately terminated
279 case pid_result_t::OK:
288 else if (service_state == service_state_t::STOPPING) {
289 // We won't log a non-zero exit status or termination due to signal here -
290 // we assume that the process died because we signalled it.
293 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
294 do_smooth_recovery();
298 // we must be STARTED
299 if (! do_auto_restart() && start_explicit) {
300 start_explicit = false;
307 services->process_queues();
310 void scripted_service::handle_exit_status(int exit_status) noexcept
312 bool did_exit = WIFEXITED(exit_status);
313 bool was_signalled = WIFSIGNALED(exit_status);
315 if (service_state == service_state_t::STOPPING) {
316 if (did_exit && WEXITSTATUS(exit_status) == 0) {
320 // ??? failed to stop! Let's log it as info:
322 log(loglevel_t::INFO, "Service ", service_name, " stop command failed with exit code ",
323 WEXITSTATUS(exit_status));
325 else if (was_signalled) {
326 log(loglevel_t::INFO, "Serivice ", service_name, " stop command terminated due to signal ",
327 WTERMSIG(exit_status));
329 // Just assume that we stopped, so that any dependencies
333 services->process_queues();
336 if (exit_status == 0) {
342 log(loglevel_t::ERROR, "Service ", service_name, " command failed with exit code ",
343 WEXITSTATUS(exit_status));
345 else if (was_signalled) {
346 log(loglevel_t::ERROR, "Service ", service_name, " command terminated due to signal ",
347 WTERMSIG(exit_status));
351 services->process_queues();
355 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
357 base_process_service *sr = service;
358 sr->waiting_for_execstat = false;
361 int r = read(get_watched_fd(), &exec_status, sizeof(int));
363 close(get_watched_fd());
366 // We read an errno code; exec() failed, and the service startup failed.
368 sr->child_listener.deregister(eventLoop, sr->pid);
369 sr->reserved_child_watch = false;
370 if (sr->stop_timer_armed) {
371 sr->restart_timer.stop_timer(loop);
372 sr->stop_timer_armed = false;
376 log(loglevel_t::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
377 if (sr->service_state == service_state_t::STARTING) {
378 sr->failed_to_start();
380 else if (sr->service_state == service_state_t::STOPPING) {
381 // Must be a scripted service. We've logged the failure, but it's probably better
382 // not to leave the service in STARTED state:
388 if (sr->record_type == service_type::PROCESS) {
389 // This could be a smooth recovery (state already STARTED). Even more, the process
390 // might be stopped (and killed via a signal) during smooth recovery. We don't to
391 // process startup again in either case, so we check for state STARTING:
392 if (sr->service_state == service_state_t::STARTING) {
398 // Somehow the process managed to complete before we even saw the status.
399 sr->handle_exit_status(sr->exit_status);
403 sr->services->process_queues();
405 return rearm::REMOVED;
408 void service_record::require() noexcept
410 if (required_by++ == 0) {
411 prop_require = !prop_release;
412 prop_release = false;
413 services->add_prop_queue(this);
417 void service_record::release() noexcept
419 if (--required_by == 0) {
420 desired_state = service_state_t::STOPPED;
422 // Can stop, and can release dependencies now. We don't need to issue a release if
423 // the require was pending though:
424 prop_release = !prop_require;
425 prop_require = false;
426 services->add_prop_queue(this);
428 if (service_state == service_state_t::STOPPED) {
429 services->service_inactive(this);
437 void service_record::release_dependencies() noexcept
439 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
443 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
444 service_record * to = i->get_to();
445 if (i->holding_acq) {
447 i->holding_acq = false;
452 void service_record::start(bool activate) noexcept
454 if (activate && ! start_explicit) {
456 start_explicit = true;
459 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
461 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
462 desired_state = service_state_t::STARTED;
464 if (service_state != service_state_t::STOPPED) {
465 // We're already starting/started, or we are stopping and need to wait for
466 // that the complete.
467 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
470 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
471 // but if so they are waiting (for us), so they too can be instantly returned to
473 notify_listeners(service_event::STOPCANCELLED);
475 else if (! was_active) {
476 services->service_active(this);
479 service_state = service_state_t::STARTING;
480 waiting_for_deps = true;
482 if (start_check_dependencies(true)) {
483 services->add_transition_queue(this);
487 void service_record::do_propagation() noexcept
490 // Need to require all our dependencies
491 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
495 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
496 service_record * to = i->get_to();
498 i->holding_acq = true;
501 prop_require = false;
505 release_dependencies();
506 prop_release = false;
510 prop_failure = false;
511 failed_to_start(true);
525 void service_record::execute_transition() noexcept
527 // state is STARTED with restarting set true if we are running a smooth recovery.
528 if (service_state == service_state_t::STARTING || (service_state == service_state_t::STARTED
530 if (start_check_dependencies(false)) {
531 bool have_console = service_state == service_state_t::STARTED && onstart_flags.runs_on_console;
532 all_deps_started(have_console);
535 else if (service_state == service_state_t::STOPPING) {
536 if (stop_check_dependents()) {
542 void service_record::do_start() noexcept
544 if (pinned_stopped) return;
546 if (service_state != service_state_t::STARTING) {
550 service_state = service_state_t::STARTING;
552 waiting_for_deps = true;
554 // Ask dependencies to start, mark them as being waited on.
555 if (start_check_dependencies(false)) {
556 // Once all dependencies are started, we start properly:
561 void service_record::dependencyStarted() noexcept
563 if ((service_state == service_state_t::STARTING || service_state == service_state_t::STARTED)
564 && waiting_for_deps) {
565 services->add_transition_queue(this);
569 bool service_record::start_check_dependencies(bool start_deps) noexcept
571 bool all_deps_started = true;
573 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
574 if ((*i)->service_state != service_state_t::STARTED) {
576 all_deps_started = false;
577 (*i)->prop_start = true;
578 services->add_prop_queue(*i);
586 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
587 service_record * to = i->get_to();
589 if (to->service_state != service_state_t::STARTED) {
590 to->prop_start = true;
591 services->add_prop_queue(to);
592 i->waiting_on = true;
593 all_deps_started = false;
596 i->waiting_on = false;
599 else if (i->waiting_on) {
600 if (to->service_state != service_state_t::STARTING) {
601 // Service has either started or is no longer starting
602 i->waiting_on = false;
605 // We are still waiting on this service
611 return all_deps_started;
614 bool service_record::open_socket() noexcept
616 if (socket_path.empty() || socket_fd != -1) {
617 // No socket, or already open
621 const char * saddrname = socket_path.c_str();
623 // Check the specified socket path
624 struct stat stat_buf;
625 if (stat(saddrname, &stat_buf) == 0) {
626 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
628 log(loglevel_t::ERROR, service_name, ": Activation socket file exists (and is not a socket)");
632 else if (errno != ENOENT) {
634 log(loglevel_t::ERROR, service_name, ": Error checking activation socket: ", strerror(errno));
638 // Remove stale socket file (if it exists).
639 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
640 // error when we try to create the socket anyway.
643 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
644 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
645 if (name == nullptr) {
646 log(loglevel_t::ERROR, service_name, ": Opening activation socket: out of memory");
650 name->sun_family = AF_UNIX;
651 strcpy(name->sun_path, saddrname);
653 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
655 log(loglevel_t::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
660 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
661 log(loglevel_t::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
669 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
670 // use chown and chmod instead.
671 if (chown(saddrname, socket_uid, socket_gid)) {
672 log(loglevel_t::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
677 if (chmod(saddrname, socket_perms) == -1) {
678 log(loglevel_t::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
683 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
684 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));
693 void service_record::all_deps_started(bool has_console) noexcept
695 if (onstart_flags.starts_on_console && ! has_console) {
696 waiting_for_deps = true;
701 waiting_for_deps = false;
703 // We overload can_interrupt_start to check whether there is any other
704 // process (eg restart timer) that needs to finish before starting.
705 if (can_interrupt_start()) {
706 waiting_for_deps = true;
710 if (! open_socket()) {
714 bool start_success = start_ps_process();
715 if (! start_success) {
720 void service_record::acquired_console() noexcept
722 if (service_state != service_state_t::STARTING) {
723 // We got the console but no longer want it.
726 else if (start_check_dependencies(false)) {
727 all_deps_started(true);
730 // We got the console but can't use it yet.
735 bgproc_service::pid_result_t
736 bgproc_service::read_pid_file(int *exit_status) noexcept
738 const char *pid_file_c = pid_file.c_str();
739 int fd = open(pid_file_c, O_CLOEXEC);
741 log(loglevel_t::ERROR, service_name, ": read pid file: ", strerror(errno));
742 return pid_result_t::FAILED;
745 char pidbuf[21]; // just enough to hold any 64-bit integer
746 int r = ss_read(fd, pidbuf, 20);
748 // Could not read from PID file
749 log(loglevel_t::ERROR, service_name, ": could not read from pidfile; ", strerror(errno));
751 return pid_result_t::FAILED;
755 pidbuf[r] = 0; // store nul terminator
757 bool valid_pid = false;
759 unsigned long long v = std::stoull(pidbuf, nullptr, 0);
760 if (v <= std::numeric_limits<pid_t>::max()) {
765 catch (std::out_of_range &exc) {
768 catch (std::invalid_argument &exc) {
769 // Ok, so it doesn't look like a number: proceed...
773 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
774 if (wait_r == -1 && errno == ECHILD) {
775 // We can't track this child - check process exists:
776 if (kill(pid, 0) == 0 || errno != ESRCH) {
777 tracking_child = false;
778 return pid_result_t::OK;
781 log(loglevel_t::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
783 return pid_result_t::FAILED;
786 else if (wait_r == pid) {
788 return pid_result_t::TERMINATED;
790 else if (wait_r == 0) {
791 // We can track the child
792 child_listener.add_reserved(eventLoop, pid, DEFAULT_PRIORITY - 10);
793 tracking_child = true;
794 reserved_child_watch = true;
795 return pid_result_t::OK;
799 log(loglevel_t::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
801 return pid_result_t::FAILED;
804 void service_record::started() noexcept
806 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
807 tcsetpgrp(0, getpgrp());
811 log_service_started(service_name);
812 service_state = service_state_t::STARTED;
813 notify_listeners(service_event::STARTED);
815 if (onstart_flags.rw_ready) {
816 open_control_socket();
818 if (onstart_flags.log_ready) {
819 setup_external_log();
822 if (force_stop || desired_state == service_state_t::STOPPED) {
828 // Notify any dependents whose desired state is STARTED:
829 for (auto i = dependents.begin(); i != dependents.end(); i++) {
830 (*i)->dependencyStarted();
832 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
833 (*i)->get_from()->dependencyStarted();
837 void service_record::failed_to_start(bool depfailed) noexcept
839 if (!depfailed && onstart_flags.starts_on_console) {
840 tcsetpgrp(0, getpgrp());
844 log_service_failed(service_name);
845 service_state = service_state_t::STOPPED;
846 if (start_explicit) {
847 start_explicit = false;
850 notify_listeners(service_event::FAILEDSTART);
852 // Cancel start of dependents:
853 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
854 if ((*i)->service_state == service_state_t::STARTING) {
855 (*i)->prop_failure = true;
856 services->add_prop_queue(*i);
859 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
860 // We can send 'start', because this is only a soft dependency.
861 // Our startup failure means that they don't have to wait for us.
862 if ((*i)->waiting_on) {
863 (*i)->holding_acq = false;
864 (*i)->waiting_on = false;
865 (*i)->get_from()->dependencyStarted();
871 bool service_record::start_ps_process() noexcept
873 // default implementation: there is no process, so we are started.
878 bool base_process_service::start_ps_process() noexcept
882 return restart_ps_process();
887 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
888 restart_interval_count = 0;
889 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
893 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
895 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
896 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
897 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
898 // is written to the pipe, and the parent can read it.
900 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
903 if (pipe2(pipefd, O_CLOEXEC)) {
904 log(loglevel_t::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
908 const char * logfile = this->logfile.c_str();
910 logfile = "/dev/null";
913 bool child_status_registered = false;
914 control_conn_t *control_conn = nullptr;
916 int control_socket[2] = {-1, -1};
917 if (onstart_flags.pass_cs_fd) {
918 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
919 log(loglevel_t::ERROR, service_name, ": can't create control socket: ", strerror(errno));
923 // Make the server side socket close-on-exec:
924 int fdflags = fcntl(control_socket[0], F_GETFD);
925 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
928 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
930 catch (std::exception &exc) {
931 log(loglevel_t::ERROR, service_name, ": can't launch process; out of memory");
936 // Set up complete, now fork and exec:
941 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
942 child_status_registered = true;
944 // We specify a high priority (i.e. low priority value) so that process termination is
945 // handled early. This means we have always recorded that the process is terminated by the
946 // time that we handle events that might otherwise cause us to signal the process, so we
947 // avoid sending a signal to an invalid (and possibly recycled) process ID.
948 forkpid = child_listener.fork(eventLoop, reserved_child_watch, DEFAULT_PRIORITY - 10);
949 reserved_child_watch = true;
951 catch (std::exception &e) {
952 log(loglevel_t::ERROR, service_name, ": Could not fork: ", e.what());
957 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
961 close(pipefd[1]); // close the 'other end' fd
962 if (control_socket[1] != -1) {
963 close(control_socket[1]);
967 waiting_for_execstat = true;
974 if (child_status_registered) {
975 child_status_listener.deregister(eventLoop);
978 if (onstart_flags.pass_cs_fd) {
982 close(control_socket[0]);
983 close(control_socket[1]);
993 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
994 int wpipefd, int csfd) noexcept
996 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
997 // from here until exit().
999 // If the console already has a session leader, presumably it is us. On the other hand
1000 // if it has no session leader, and we don't create one, then control inputs such as
1001 // ^C will have no effect.
1002 bool do_set_ctty = (tcgetsid(0) == -1);
1004 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
1005 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
1006 sigset_t sigwait_set;
1007 sigset_t sigall_set;
1008 sigfillset(&sigall_set);
1009 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
1010 sigdelset(&sigwait_set, SIGCHLD);
1011 sigdelset(&sigwait_set, SIGINT);
1012 sigdelset(&sigwait_set, SIGTERM);
1013 sigdelset(&sigwait_set, SIGQUIT);
1015 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
1016 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
1017 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
1018 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
1021 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
1022 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
1023 char csenvbuf[csenvbufsz];
1025 int minfd = (socket_fd == -1) ? 3 : 4;
1027 // Move wpipefd/csfd to another fd if necessary
1028 if (wpipefd < minfd) {
1029 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
1030 if (wpipefd == -1) goto failure_out;
1033 if (csfd != -1 && csfd < minfd) {
1034 csfd = fcntl(csfd, F_DUPFD, minfd);
1035 if (csfd == -1) goto failure_out;
1038 if (socket_fd != -1) {
1040 if (dup2(socket_fd, 3) == -1) goto failure_out;
1041 if (socket_fd != 3) {
1045 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
1046 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
1047 if (putenv(nbuf)) goto failure_out;
1051 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
1052 if (putenv(csenvbuf)) goto failure_out;
1056 // Re-set stdin, stdout, stderr
1057 close(0); close(1); close(2);
1059 if (open("/dev/null", O_RDONLY) == 0) {
1060 // stdin = 0. That's what we should have; proceed with opening
1061 // stdout and stderr.
1062 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1065 if (dup2(1, 2) != 2) {
1069 else goto failure_out;
1071 // We have the option of creating a session and process group, or just a new process
1072 // group. If we just create a new process group, the child process cannot make itself
1073 // a session leader if it wants to do that (eg getty/login will generally want this).
1074 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1075 // will also affect the child process (which probably isn't so bad, though since we
1076 // will handle the shutdown ourselves it's not necessary). Creating a new session
1077 // (and a new process group as part of that) seems like a safe bet, and has the
1078 // advantage of letting us signal the process as part of a process group.
1082 // "run on console" - run as a foreground job on the terminal/console device
1084 // if do_set_ctty is false, we are the session leader; we are probably running
1085 // as a user process. Don't create a new session leader in that case, and run
1086 // as part of the parent session. Otherwise, the new session cannot claim the
1087 // terminal as a controlling terminal (it is already claimed), meaning that it
1088 // will not see control signals from ^C etc.
1091 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1092 signal(SIGTSTP, SIG_IGN);
1094 // Become session leader
1096 ioctl(0, TIOCSCTTY, 0);
1099 tcsetpgrp(0, getpgrp());
1102 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1104 execvp(args[0], const_cast<char **>(args));
1106 // If we got here, the exec failed:
1108 int exec_status = errno;
1109 write(wpipefd, &exec_status, sizeof(int));
1113 // Mark this and all dependent services as force-stopped.
1114 void service_record::forced_stop() noexcept
1116 if (service_state != service_state_t::STOPPED) {
1118 services->add_transition_queue(this);
1122 void service_record::dependent_stopped() noexcept
1124 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1125 services->add_transition_queue(this);
1129 void service_record::stop(bool bring_down) noexcept
1131 if (start_explicit) {
1132 start_explicit = false;
1141 void service_record::do_stop() noexcept
1143 if (pinned_started) return;
1145 if (start_explicit && ! do_auto_restart()) {
1146 start_explicit = false;
1148 if (required_by == 0) return; // release will re-call us anyway
1151 if (service_state != service_state_t::STARTED) {
1152 if (service_state == service_state_t::STARTING) {
1153 if (! can_interrupt_start()) {
1154 // Well this is awkward: we're going to have to continue
1155 // starting, but we don't want any dependents to think that
1156 // they are still waiting to start.
1157 // Make sure they remain stopped:
1162 // We must have had desired_state == STARTED.
1163 notify_listeners(service_event::STARTCANCELLED);
1167 // Reaching this point, we are starting interruptibly - so we
1168 // stop now (by falling through to below).
1171 // If we're starting we need to wait for that to complete.
1172 // If we're already stopping/stopped there's nothing to do.
1177 service_state = service_state_t::STOPPING;
1178 waiting_for_deps = true;
1179 if (stop_dependents()) {
1180 services->add_transition_queue(this);
1184 bool service_record::stop_check_dependents() noexcept
1186 bool all_deps_stopped = true;
1187 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1188 if (! (*i)->is_stopped()) {
1189 all_deps_stopped = false;
1194 return all_deps_stopped;
1197 bool service_record::stop_dependents() noexcept
1199 bool all_deps_stopped = true;
1200 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1201 if (! (*i)->is_stopped()) {
1202 // Note we check *first* since if the dependent service is not stopped,
1203 // 1. We will issue a stop to it shortly and
1204 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1205 // check is run anyway.
1206 all_deps_stopped = false;
1210 // If this service is to be forcefully stopped, dependents must also be.
1211 (*i)->forced_stop();
1214 (*i)->prop_stop = true;
1215 services->add_prop_queue(*i);
1218 return all_deps_stopped;
1221 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1222 void service_record::all_deps_stopped() noexcept
1224 waiting_for_deps = false;
1228 void base_process_service::kill_pg(int signo) noexcept
1230 pid_t pgid = getpgid(pid);
1232 // only should happen if pid is invalid, which should never happen...
1233 log(loglevel_t::ERROR, service_name, ": can't signal process: ", strerror(errno));
1239 void base_process_service::all_deps_stopped() noexcept
1241 waiting_for_deps = false;
1243 // The process is still kicking on - must actually kill it. We signal the process
1244 // group (-pid) rather than just the process as there's less risk then of creating
1245 // an orphaned process group:
1246 if (! onstart_flags.no_sigterm) {
1249 if (term_signal != -1) {
1250 kill_pg(term_signal);
1253 // In most cases, the rest is done in handle_exit_status.
1254 // If we are a BGPROCESS and the process is not our immediate child, however, that
1255 // won't work - check for this now:
1256 if (record_type == service_type::BGPROCESS && ! tracking_child) {
1259 else if (stop_timeout != time_val(0,0)) {
1260 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1261 stop_timer_armed = true;
1265 // The process is already dead.
1270 void scripted_service::all_deps_stopped() noexcept
1272 waiting_for_deps = false;
1273 if (stop_command.length() == 0) {
1276 else if (! start_ps_process(stop_arg_parts, false)) {
1277 // Couldn't execute stop script, but there's not much we can do:
1281 // successfully started stop script: start kill timer:
1282 if (stop_timeout != time_val(0,0)) {
1283 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1284 stop_timer_armed = true;
1289 void service_record::unpin() noexcept
1291 if (pinned_started) {
1292 pinned_started = false;
1293 if (desired_state == service_state_t::STOPPED) {
1295 services->process_queues();
1298 if (pinned_stopped) {
1299 pinned_stopped = false;
1300 if (desired_state == service_state_t::STARTED) {
1302 services->process_queues();
1307 void service_record::queue_for_console() noexcept
1309 services->append_console_queue(this);
1312 void service_record::release_console() noexcept
1314 services->pull_console_queue();
1317 void service_record::interrupt_start() noexcept
1319 services->unqueue_console(this);
1322 void service_set::service_active(service_record *sr) noexcept
1327 void service_set::service_inactive(service_record *sr) noexcept
1332 base_process_service::base_process_service(service_set *sset, string name,
1333 service_type service_type_p, string &&command,
1334 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1335 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1336 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1337 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1339 restart_interval_count = 0;
1340 restart_interval_time = {0, 0};
1341 restart_timer.service = this;
1342 restart_timer.add_timer(eventLoop);
1344 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1345 restart_interval.seconds() = 10;
1346 restart_interval.nseconds() = 0;
1347 max_restart_interval_count = 3;
1349 waiting_restart_timer = false;
1350 reserved_child_watch = false;
1351 tracking_child = false;
1352 stop_timer_armed = false;
1355 void base_process_service::do_restart() noexcept
1357 waiting_restart_timer = false;
1358 restart_interval_count++;
1360 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1361 // the process should be granted access to the console:
1362 bool on_console = service_state == service_state_t::STARTING
1363 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1365 if (service_state == service_state_t::STARTING) {
1366 // for a smooth recovery, we want to check dependencies are available before actually
1368 if (! start_check_dependencies(false)) {
1369 waiting_for_deps = true;
1374 if (! start_ps_process(exec_arg_parts, on_console)) {
1376 if (service_state == service_state_t::STARTING) {
1380 desired_state = service_state_t::STOPPED;
1383 services->process_queues();
1387 bool base_process_service::restart_ps_process() noexcept
1389 using time_val = eventloop_t::time_val;
1391 time_val current_time;
1392 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1394 if (max_restart_interval_count != 0) {
1395 // Check whether we're still in the most recent restart check interval:
1396 time_val int_diff = current_time - restart_interval_time;
1397 if (int_diff < restart_interval) {
1398 if (restart_interval_count >= max_restart_interval_count) {
1399 log(loglevel_t::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1404 restart_interval_time = current_time;
1405 restart_interval_count = 0;
1409 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1410 time_val tdiff = current_time - last_start_time;
1411 if (restart_delay <= tdiff) {
1412 // > restart delay (normally 200ms)
1416 time_val timeout = restart_delay - tdiff;
1417 restart_timer.arm_timer_rel(eventLoop, timeout);
1418 waiting_restart_timer = true;
1423 void base_process_service::interrupt_start() noexcept
1425 // overridden in subclasses
1426 if (waiting_restart_timer) {
1427 restart_timer.stop_timer(eventLoop);
1428 waiting_restart_timer = false;
1430 service_record::interrupt_start();
1433 void base_process_service::kill_with_fire() noexcept
1436 log(loglevel_t::WARN, "Service ", service_name, "with pid ", pid, " exceeded allowed stop time; killing.");
1441 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1443 if (service->service_state == service_state_t::STOPPING) {
1444 service->kill_with_fire();
1445 service->stop_timer_armed = false;
1448 // STARTING / STARTED:
1449 service->do_restart();
1451 return dasynq::rearm::DISARM;