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 : dependents) {
74 if (dependent->dep_type == dependency_type::SOFT) {
75 if (dependent->holding_acq) {
76 dependent->holding_acq = false;
82 bool will_restart = (desired_state == service_state_t::STARTED)
83 && services->get_auto_restart();
85 for (auto dependency : depends_on) {
86 // we signal dependencies in case they are waiting for us to stop:
87 dependency.get_to()->dependent_stopped();
90 service_state = service_state_t::STOPPED;
93 // Desired state is "started".
98 if (socket_fd != -1) {
103 if (start_explicit) {
104 start_explicit = false;
107 else if (required_by == 0) {
108 services->service_inactive(this);
112 log_service_stopped(service_name);
113 notify_listeners(service_event::STOPPED);
116 dasynq::rearm service_child_watcher::status_change(eventloop_t &loop, pid_t child, int status) noexcept
118 base_process_service *sr = service;
121 sr->exit_status = status;
123 // Ok, for a process service, any process death which we didn't rig
124 // ourselves is a bit... unexpected. Probably, the child died because
125 // we asked it to (sr->service_state == STOPPING). But even if
126 // we didn't, there's not much we can do.
128 if (sr->waiting_for_execstat) {
129 // We still don't have an exec() status from the forked child, wait for that
130 // before doing any further processing.
131 return rearm::NOOP; // hold watch reservation
134 // Must stop watch now since handle_exit_status might result in re-launch:
135 // (stop_watch instead of deregister, so that we hold watch reservation).
138 if (sr->stop_timer_armed) {
139 sr->restart_timer.stop_timer(loop);
140 sr->stop_timer_armed = false;
143 sr->handle_exit_status(status);
147 bool service_record::do_auto_restart() noexcept
150 return services->get_auto_restart();
155 void service_record::emergency_stop() noexcept
157 if (! do_auto_restart() && start_explicit) {
158 start_explicit = false;
166 void process_service::handle_exit_status(int exit_status) noexcept
168 bool did_exit = WIFEXITED(exit_status);
169 bool was_signalled = WIFSIGNALED(exit_status);
172 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
174 log(loglevel_t::ERROR, "Service ", service_name, " process terminated with exit code ",
175 WEXITSTATUS(exit_status));
177 else if (was_signalled) {
178 log(loglevel_t::ERROR, "Service ", service_name, " terminated due to signal ",
179 WTERMSIG(exit_status));
183 if (service_state == service_state_t::STARTING) {
184 if (did_exit && WEXITSTATUS(exit_status) == 0) {
191 else if (service_state == service_state_t::STOPPING) {
192 // We won't log a non-zero exit status or termination due to signal here -
193 // we assume that the process died because we signalled it.
196 else if (smooth_recovery && service_state == service_state_t::STARTED
197 && desired_state == service_state_t::STARTED) {
198 do_smooth_recovery();
204 services->process_queues();
207 void base_process_service::do_smooth_recovery() noexcept
209 if (! restart_ps_process()) {
211 services->process_queues();
215 void bgproc_service::handle_exit_status(int exit_status) noexcept
218 bool did_exit = WIFEXITED(exit_status);
219 bool was_signalled = WIFSIGNALED(exit_status);
221 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
223 log(loglevel_t::ERROR, "Service ", service_name, " process terminated with exit code ",
224 WEXITSTATUS(exit_status));
226 else if (was_signalled) {
227 log(loglevel_t::ERROR, "Service ", service_name, " terminated due to signal ",
228 WTERMSIG(exit_status));
232 // This may be a "smooth recovery" where we are restarting the process while leaving the
233 // service in the STARTED state.
234 if (restarting && service_state == service_state_t::STARTED) {
236 bool need_stop = false;
237 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
241 // We need to re-read the PID, since it has now changed.
242 if (pid_file.length() != 0) {
243 auto pid_result = read_pid_file(&exit_status);
244 switch (pid_result) {
245 case pid_result_t::FAILED:
246 // Failed startup: no auto-restart.
249 case pid_result_t::TERMINATED:
251 case pid_result_t::OK:
258 // Failed startup: no auto-restart.
260 services->process_queues();
267 if (service_state == service_state_t::STARTING) {
268 // POSIX requires that if the process exited clearly with a status code of 0,
269 // the exit status value will be 0:
270 if (exit_status == 0) {
271 auto pid_result = read_pid_file(&exit_status);
272 switch (pid_result) {
273 case pid_result_t::FAILED:
274 // Failed startup: no auto-restart.
277 case pid_result_t::TERMINATED:
278 // started, but immediately terminated
281 case pid_result_t::OK:
290 else if (service_state == service_state_t::STOPPING) {
291 // We won't log a non-zero exit status or termination due to signal here -
292 // we assume that the process died because we signalled it.
295 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
296 do_smooth_recovery();
300 // we must be STARTED
301 if (! do_auto_restart() && start_explicit) {
302 start_explicit = false;
309 services->process_queues();
312 void scripted_service::handle_exit_status(int exit_status) noexcept
314 bool did_exit = WIFEXITED(exit_status);
315 bool was_signalled = WIFSIGNALED(exit_status);
317 if (service_state == service_state_t::STOPPING) {
318 if (did_exit && WEXITSTATUS(exit_status) == 0) {
322 // ??? failed to stop! Let's log it as info:
324 log(loglevel_t::INFO, "Service ", service_name, " stop command failed with exit code ",
325 WEXITSTATUS(exit_status));
327 else if (was_signalled) {
328 log(loglevel_t::INFO, "Serivice ", service_name, " stop command terminated due to signal ",
329 WTERMSIG(exit_status));
331 // Just assume that we stopped, so that any dependencies
335 services->process_queues();
338 if (exit_status == 0) {
344 log(loglevel_t::ERROR, "Service ", service_name, " command failed with exit code ",
345 WEXITSTATUS(exit_status));
347 else if (was_signalled) {
348 log(loglevel_t::ERROR, "Service ", service_name, " command terminated due to signal ",
349 WTERMSIG(exit_status));
353 services->process_queues();
357 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
359 base_process_service *sr = service;
360 sr->waiting_for_execstat = false;
363 int r = read(get_watched_fd(), &exec_status, sizeof(int));
365 close(get_watched_fd());
368 // We read an errno code; exec() failed, and the service startup failed.
370 sr->child_listener.deregister(eventLoop, sr->pid);
371 sr->reserved_child_watch = false;
372 if (sr->stop_timer_armed) {
373 sr->restart_timer.stop_timer(loop);
374 sr->stop_timer_armed = false;
378 log(loglevel_t::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
379 if (sr->service_state == service_state_t::STARTING) {
380 sr->failed_to_start();
382 else if (sr->service_state == service_state_t::STOPPING) {
383 // Must be a scripted service. We've logged the failure, but it's probably better
384 // not to leave the service in STARTED state:
390 if (sr->record_type == service_type::PROCESS) {
391 // This could be a smooth recovery (state already STARTED). Even more, the process
392 // might be stopped (and killed via a signal) during smooth recovery. We don't to
393 // process startup again in either case, so we check for state STARTING:
394 if (sr->service_state == service_state_t::STARTING) {
400 // Somehow the process managed to complete before we even saw the status.
401 sr->handle_exit_status(sr->exit_status);
405 sr->services->process_queues();
407 return rearm::REMOVED;
410 void service_record::require() noexcept
412 if (required_by++ == 0) {
413 prop_require = !prop_release;
414 prop_release = false;
415 services->add_prop_queue(this);
419 void service_record::release() noexcept
421 if (--required_by == 0) {
422 desired_state = service_state_t::STOPPED;
424 // Can stop, and can release dependencies now. We don't need to issue a release if
425 // the require was pending though:
426 prop_release = !prop_require;
427 prop_require = false;
428 services->add_prop_queue(this);
430 if (service_state == service_state_t::STOPPED) {
431 services->service_inactive(this);
439 void service_record::release_dependencies() noexcept
441 for (auto & dependency : depends_on) {
442 service_record * dep_to = dependency.get_to();
443 if (dependency.holding_acq) {
445 dependency.holding_acq = false;
450 void service_record::start(bool activate) noexcept
452 if (activate && ! start_explicit) {
454 start_explicit = true;
457 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
459 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
460 desired_state = service_state_t::STARTED;
462 if (service_state != service_state_t::STOPPED) {
463 // We're already starting/started, or we are stopping and need to wait for
464 // that the complete.
465 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
468 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
469 // but if so they are waiting (for us), so they too can be instantly returned to
471 notify_listeners(service_event::STOPCANCELLED);
473 else if (! was_active) {
474 services->service_active(this);
477 service_state = service_state_t::STARTING;
478 waiting_for_deps = true;
480 if (start_check_dependencies(true)) {
481 services->add_transition_queue(this);
485 void service_record::do_propagation() noexcept
488 // Need to require all our dependencies
489 for (auto & dep : depends_on) {
490 dep.get_to()->require();
491 dep.holding_acq = true;
493 prop_require = false;
497 release_dependencies();
498 prop_release = false;
502 prop_failure = false;
503 failed_to_start(true);
517 void service_record::execute_transition() noexcept
519 // state is STARTED with restarting set true if we are running a smooth recovery.
520 if (service_state == service_state_t::STARTING || (service_state == service_state_t::STARTED
522 if (start_check_dependencies(false)) {
523 bool have_console = service_state == service_state_t::STARTED && onstart_flags.runs_on_console;
524 all_deps_started(have_console);
527 else if (service_state == service_state_t::STOPPING) {
528 if (stop_check_dependents()) {
534 void service_record::do_start() noexcept
536 if (pinned_stopped) return;
538 if (service_state != service_state_t::STARTING) {
542 service_state = service_state_t::STARTING;
544 waiting_for_deps = true;
546 // Ask dependencies to start, mark them as being waited on.
547 if (start_check_dependencies(false)) {
548 // Once all dependencies are started, we start properly:
553 void service_record::dependencyStarted() noexcept
555 if ((service_state == service_state_t::STARTING || service_state == service_state_t::STARTED)
556 && waiting_for_deps) {
557 services->add_transition_queue(this);
561 bool service_record::start_check_dependencies(bool start_deps) noexcept
563 bool all_deps_started = true;
565 for (auto dep : depends_on) {
566 if (dep.dep_type == dependency_type::REGULAR) {
567 if (dep.get_to()->service_state != service_state_t::STARTED) {
569 all_deps_started = false;
570 dep.get_to()->prop_start = true;
571 services->add_prop_queue(dep.get_to());
578 else if (dep.dep_type == dependency_type::SOFT) {
579 service_record * to = dep.get_to();
581 if (to->service_state != service_state_t::STARTED) {
582 to->prop_start = true;
583 services->add_prop_queue(to);
584 dep.waiting_on = true;
585 all_deps_started = false;
588 dep.waiting_on = false;
591 else if (dep.waiting_on) {
592 if (to->service_state != service_state_t::STARTING) {
593 // Service has either started or is no longer starting
594 dep.waiting_on = false;
597 // We are still waiting on this service
604 return all_deps_started;
607 bool service_record::open_socket() noexcept
609 if (socket_path.empty() || socket_fd != -1) {
610 // No socket, or already open
614 const char * saddrname = socket_path.c_str();
616 // Check the specified socket path
617 struct stat stat_buf;
618 if (stat(saddrname, &stat_buf) == 0) {
619 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
621 log(loglevel_t::ERROR, service_name, ": Activation socket file exists (and is not a socket)");
625 else if (errno != ENOENT) {
627 log(loglevel_t::ERROR, service_name, ": Error checking activation socket: ", strerror(errno));
631 // Remove stale socket file (if it exists).
632 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
633 // error when we try to create the socket anyway.
636 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
637 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
638 if (name == nullptr) {
639 log(loglevel_t::ERROR, service_name, ": Opening activation socket: out of memory");
643 name->sun_family = AF_UNIX;
644 strcpy(name->sun_path, saddrname);
646 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
648 log(loglevel_t::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
653 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
654 log(loglevel_t::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
662 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
663 // use chown and chmod instead.
664 if (chown(saddrname, socket_uid, socket_gid)) {
665 log(loglevel_t::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
670 if (chmod(saddrname, socket_perms) == -1) {
671 log(loglevel_t::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
676 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
677 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));
686 void service_record::all_deps_started(bool has_console) noexcept
688 if (onstart_flags.starts_on_console && ! has_console) {
689 waiting_for_deps = true;
694 waiting_for_deps = false;
696 // We overload can_interrupt_start to check whether there is any other
697 // process (eg restart timer) that needs to finish before starting.
698 if (can_interrupt_start()) {
699 waiting_for_deps = true;
703 if (! open_socket()) {
707 bool start_success = start_ps_process();
708 if (! start_success) {
713 void service_record::acquired_console() noexcept
715 if (service_state != service_state_t::STARTING) {
716 // We got the console but no longer want it.
719 else if (start_check_dependencies(false)) {
720 all_deps_started(true);
723 // We got the console but can't use it yet.
728 bgproc_service::pid_result_t
729 bgproc_service::read_pid_file(int *exit_status) noexcept
731 const char *pid_file_c = pid_file.c_str();
732 int fd = open(pid_file_c, O_CLOEXEC);
734 log(loglevel_t::ERROR, service_name, ": read pid file: ", strerror(errno));
735 return pid_result_t::FAILED;
738 char pidbuf[21]; // just enough to hold any 64-bit integer
739 int r = ss_read(fd, pidbuf, 20);
741 // Could not read from PID file
742 log(loglevel_t::ERROR, service_name, ": could not read from pidfile; ", strerror(errno));
744 return pid_result_t::FAILED;
748 pidbuf[r] = 0; // store nul terminator
750 bool valid_pid = false;
752 unsigned long long v = std::stoull(pidbuf, nullptr, 0);
753 if (v <= std::numeric_limits<pid_t>::max()) {
758 catch (std::out_of_range &exc) {
761 catch (std::invalid_argument &exc) {
762 // Ok, so it doesn't look like a number: proceed...
766 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
767 if (wait_r == -1 && errno == ECHILD) {
768 // We can't track this child - check process exists:
769 if (kill(pid, 0) == 0 || errno != ESRCH) {
770 tracking_child = false;
771 return pid_result_t::OK;
774 log(loglevel_t::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
776 return pid_result_t::FAILED;
779 else if (wait_r == pid) {
781 return pid_result_t::TERMINATED;
783 else if (wait_r == 0) {
784 // We can track the child
785 child_listener.add_reserved(eventLoop, pid, DEFAULT_PRIORITY - 10);
786 tracking_child = true;
787 reserved_child_watch = true;
788 return pid_result_t::OK;
792 log(loglevel_t::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
794 return pid_result_t::FAILED;
797 void service_record::started() noexcept
799 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
800 tcsetpgrp(0, getpgrp());
804 log_service_started(service_name);
805 service_state = service_state_t::STARTED;
806 notify_listeners(service_event::STARTED);
808 if (onstart_flags.rw_ready) {
809 open_control_socket();
811 if (onstart_flags.log_ready) {
812 setup_external_log();
815 if (force_stop || desired_state == service_state_t::STOPPED) {
821 // Notify any dependents whose desired state is STARTED:
822 for (auto dept : dependents) {
823 dept->get_from()->dependencyStarted();
827 void service_record::failed_to_start(bool depfailed) noexcept
829 if (!depfailed && onstart_flags.starts_on_console) {
830 tcsetpgrp(0, getpgrp());
834 log_service_failed(service_name);
835 service_state = service_state_t::STOPPED;
836 if (start_explicit) {
837 start_explicit = false;
840 notify_listeners(service_event::FAILEDSTART);
842 // Cancel start of dependents:
843 for (auto & dept : dependents) {
844 if (dept->dep_type == dependency_type::REGULAR) {
845 if (dept->get_from()->service_state == service_state_t::STARTING) {
846 dept->get_from()->prop_failure = true;
847 services->add_prop_queue(dept->get_from());
850 else if (dept->dep_type == dependency_type::SOFT) {
851 if (dept->waiting_on) {
852 dept->waiting_on = false;
853 dept->get_from()->dependencyStarted();
855 if (dept->holding_acq) {
856 dept->holding_acq = false;
863 bool service_record::start_ps_process() noexcept
865 // default implementation: there is no process, so we are started.
870 bool base_process_service::start_ps_process() noexcept
874 return restart_ps_process();
879 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
880 restart_interval_count = 0;
881 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
885 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
887 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
888 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
889 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
890 // is written to the pipe, and the parent can read it.
892 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
895 if (pipe2(pipefd, O_CLOEXEC)) {
896 log(loglevel_t::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
900 const char * logfile = this->logfile.c_str();
902 logfile = "/dev/null";
905 bool child_status_registered = false;
906 control_conn_t *control_conn = nullptr;
908 int control_socket[2] = {-1, -1};
909 if (onstart_flags.pass_cs_fd) {
910 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
911 log(loglevel_t::ERROR, service_name, ": can't create control socket: ", strerror(errno));
915 // Make the server side socket close-on-exec:
916 int fdflags = fcntl(control_socket[0], F_GETFD);
917 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
920 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
922 catch (std::exception &exc) {
923 log(loglevel_t::ERROR, service_name, ": can't launch process; out of memory");
928 // Set up complete, now fork and exec:
933 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
934 child_status_registered = true;
936 // We specify a high priority (i.e. low priority value) so that process termination is
937 // handled early. This means we have always recorded that the process is terminated by the
938 // time that we handle events that might otherwise cause us to signal the process, so we
939 // avoid sending a signal to an invalid (and possibly recycled) process ID.
940 forkpid = child_listener.fork(eventLoop, reserved_child_watch, DEFAULT_PRIORITY - 10);
941 reserved_child_watch = true;
943 catch (std::exception &e) {
944 log(loglevel_t::ERROR, service_name, ": Could not fork: ", e.what());
949 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
953 close(pipefd[1]); // close the 'other end' fd
954 if (control_socket[1] != -1) {
955 close(control_socket[1]);
959 waiting_for_execstat = true;
966 if (child_status_registered) {
967 child_status_listener.deregister(eventLoop);
970 if (onstart_flags.pass_cs_fd) {
974 close(control_socket[0]);
975 close(control_socket[1]);
985 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
986 int wpipefd, int csfd) noexcept
988 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
989 // from here until exit().
991 // If the console already has a session leader, presumably it is us. On the other hand
992 // if it has no session leader, and we don't create one, then control inputs such as
993 // ^C will have no effect.
994 bool do_set_ctty = (tcgetsid(0) == -1);
996 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
997 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
998 sigset_t sigwait_set;
1000 sigfillset(&sigall_set);
1001 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
1002 sigdelset(&sigwait_set, SIGCHLD);
1003 sigdelset(&sigwait_set, SIGINT);
1004 sigdelset(&sigwait_set, SIGTERM);
1005 sigdelset(&sigwait_set, SIGQUIT);
1007 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
1008 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
1009 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
1010 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
1013 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
1014 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
1015 char csenvbuf[csenvbufsz];
1017 int minfd = (socket_fd == -1) ? 3 : 4;
1019 // Move wpipefd/csfd to another fd if necessary
1020 if (wpipefd < minfd) {
1021 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
1022 if (wpipefd == -1) goto failure_out;
1025 if (csfd != -1 && csfd < minfd) {
1026 csfd = fcntl(csfd, F_DUPFD, minfd);
1027 if (csfd == -1) goto failure_out;
1030 if (socket_fd != -1) {
1032 if (dup2(socket_fd, 3) == -1) goto failure_out;
1033 if (socket_fd != 3) {
1037 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
1038 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
1039 if (putenv(nbuf)) goto failure_out;
1043 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
1044 if (putenv(csenvbuf)) goto failure_out;
1048 // Re-set stdin, stdout, stderr
1049 close(0); close(1); close(2);
1051 if (open("/dev/null", O_RDONLY) == 0) {
1052 // stdin = 0. That's what we should have; proceed with opening
1053 // stdout and stderr.
1054 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1057 if (dup2(1, 2) != 2) {
1061 else goto failure_out;
1063 // We have the option of creating a session and process group, or just a new process
1064 // group. If we just create a new process group, the child process cannot make itself
1065 // a session leader if it wants to do that (eg getty/login will generally want this).
1066 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1067 // will also affect the child process (which probably isn't so bad, though since we
1068 // will handle the shutdown ourselves it's not necessary). Creating a new session
1069 // (and a new process group as part of that) seems like a safe bet, and has the
1070 // advantage of letting us signal the process as part of a process group.
1074 // "run on console" - run as a foreground job on the terminal/console device
1076 // if do_set_ctty is false, we are the session leader; we are probably running
1077 // as a user process. Don't create a new session leader in that case, and run
1078 // as part of the parent session. Otherwise, the new session cannot claim the
1079 // terminal as a controlling terminal (it is already claimed), meaning that it
1080 // will not see control signals from ^C etc.
1083 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1084 signal(SIGTSTP, SIG_IGN);
1086 // Become session leader
1088 ioctl(0, TIOCSCTTY, 0);
1091 tcsetpgrp(0, getpgrp());
1094 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1096 execvp(args[0], const_cast<char **>(args));
1098 // If we got here, the exec failed:
1100 int exec_status = errno;
1101 write(wpipefd, &exec_status, sizeof(int));
1105 // Mark this and all dependent services as force-stopped.
1106 void service_record::forced_stop() noexcept
1108 if (service_state != service_state_t::STOPPED) {
1110 services->add_transition_queue(this);
1114 void service_record::dependent_stopped() noexcept
1116 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1117 services->add_transition_queue(this);
1121 void service_record::stop(bool bring_down) noexcept
1123 if (start_explicit) {
1124 start_explicit = false;
1133 void service_record::do_stop() noexcept
1135 if (pinned_started) return;
1137 if (start_explicit && ! do_auto_restart()) {
1138 start_explicit = false;
1140 if (required_by == 0) return; // release will re-call us anyway
1143 if (service_state != service_state_t::STARTED) {
1144 if (service_state == service_state_t::STARTING) {
1145 if (! can_interrupt_start()) {
1146 // Well this is awkward: we're going to have to continue
1147 // starting, but we don't want any dependents to think that
1148 // they are still waiting to start.
1149 // Make sure they remain stopped:
1154 // We must have had desired_state == STARTED.
1155 notify_listeners(service_event::STARTCANCELLED);
1159 // Reaching this point, we are starting interruptibly - so we
1160 // stop now (by falling through to below).
1163 // If we're starting we need to wait for that to complete.
1164 // If we're already stopping/stopped there's nothing to do.
1169 service_state = service_state_t::STOPPING;
1170 waiting_for_deps = true;
1171 if (stop_dependents()) {
1172 services->add_transition_queue(this);
1176 bool service_record::stop_check_dependents() noexcept
1178 bool all_deps_stopped = true;
1179 for (auto dept : dependents) {
1180 if (dept->dep_type == dependency_type::REGULAR && ! dept->get_from()->is_stopped()) {
1181 all_deps_stopped = false;
1186 return all_deps_stopped;
1189 bool service_record::stop_dependents() noexcept
1191 bool all_deps_stopped = true;
1192 for (auto dept : dependents) {
1193 if (dept->dep_type == dependency_type::REGULAR) {
1194 if (! dept->get_from()->is_stopped()) {
1195 // Note we check *first* since if the dependent service is not stopped,
1196 // 1. We will issue a stop to it shortly and
1197 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1198 // check is run anyway.
1199 all_deps_stopped = false;
1203 // If this service is to be forcefully stopped, dependents must also be.
1204 dept->get_from()->forced_stop();
1207 dept->get_from()->prop_stop = true;
1208 services->add_prop_queue(dept->get_from());
1212 return all_deps_stopped;
1215 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1216 void service_record::all_deps_stopped() noexcept
1218 waiting_for_deps = false;
1222 void base_process_service::kill_pg(int signo) noexcept
1224 pid_t pgid = getpgid(pid);
1226 // only should happen if pid is invalid, which should never happen...
1227 log(loglevel_t::ERROR, service_name, ": can't signal process: ", strerror(errno));
1233 void base_process_service::all_deps_stopped() noexcept
1235 waiting_for_deps = false;
1237 // The process is still kicking on - must actually kill it. We signal the process
1238 // group (-pid) rather than just the process as there's less risk then of creating
1239 // an orphaned process group:
1240 if (! onstart_flags.no_sigterm) {
1243 if (term_signal != -1) {
1244 kill_pg(term_signal);
1247 // In most cases, the rest is done in handle_exit_status.
1248 // If we are a BGPROCESS and the process is not our immediate child, however, that
1249 // won't work - check for this now:
1250 if (record_type == service_type::BGPROCESS && ! tracking_child) {
1253 else if (stop_timeout != time_val(0,0)) {
1254 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1255 stop_timer_armed = true;
1259 // The process is already dead.
1264 void scripted_service::all_deps_stopped() noexcept
1266 waiting_for_deps = false;
1267 if (stop_command.length() == 0) {
1270 else if (! start_ps_process(stop_arg_parts, false)) {
1271 // Couldn't execute stop script, but there's not much we can do:
1275 // successfully started stop script: start kill timer:
1276 if (stop_timeout != time_val(0,0)) {
1277 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1278 stop_timer_armed = true;
1283 void service_record::unpin() noexcept
1285 if (pinned_started) {
1286 pinned_started = false;
1287 if (desired_state == service_state_t::STOPPED || force_stop) {
1289 services->process_queues();
1292 if (pinned_stopped) {
1293 pinned_stopped = false;
1294 if (desired_state == service_state_t::STARTED) {
1296 services->process_queues();
1301 void service_record::queue_for_console() noexcept
1303 services->append_console_queue(this);
1306 void service_record::release_console() noexcept
1308 services->pull_console_queue();
1311 void service_record::interrupt_start() noexcept
1313 services->unqueue_console(this);
1316 void service_set::service_active(service_record *sr) noexcept
1321 void service_set::service_inactive(service_record *sr) noexcept
1326 base_process_service::base_process_service(service_set *sset, string name,
1327 service_type service_type_p, string &&command,
1328 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1329 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1330 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1331 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1333 restart_interval_count = 0;
1334 restart_interval_time = {0, 0};
1335 restart_timer.service = this;
1336 restart_timer.add_timer(eventLoop);
1338 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1339 restart_interval.seconds() = 10;
1340 restart_interval.nseconds() = 0;
1341 max_restart_interval_count = 3;
1343 waiting_restart_timer = false;
1344 reserved_child_watch = false;
1345 tracking_child = false;
1346 stop_timer_armed = false;
1349 void base_process_service::do_restart() noexcept
1351 waiting_restart_timer = false;
1352 restart_interval_count++;
1354 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1355 // the process should be granted access to the console:
1356 bool on_console = service_state == service_state_t::STARTING
1357 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1359 if (service_state == service_state_t::STARTING) {
1360 // for a smooth recovery, we want to check dependencies are available before actually
1362 if (! start_check_dependencies(false)) {
1363 waiting_for_deps = true;
1368 if (! start_ps_process(exec_arg_parts, on_console)) {
1370 if (service_state == service_state_t::STARTING) {
1374 desired_state = service_state_t::STOPPED;
1377 services->process_queues();
1381 bool base_process_service::restart_ps_process() noexcept
1383 using time_val = eventloop_t::time_val;
1385 time_val current_time;
1386 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1388 if (max_restart_interval_count != 0) {
1389 // Check whether we're still in the most recent restart check interval:
1390 time_val int_diff = current_time - restart_interval_time;
1391 if (int_diff < restart_interval) {
1392 if (restart_interval_count >= max_restart_interval_count) {
1393 log(loglevel_t::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1398 restart_interval_time = current_time;
1399 restart_interval_count = 0;
1403 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1404 time_val tdiff = current_time - last_start_time;
1405 if (restart_delay <= tdiff) {
1406 // > restart delay (normally 200ms)
1410 time_val timeout = restart_delay - tdiff;
1411 restart_timer.arm_timer_rel(eventLoop, timeout);
1412 waiting_restart_timer = true;
1417 void base_process_service::interrupt_start() noexcept
1419 // overridden in subclasses
1420 if (waiting_restart_timer) {
1421 restart_timer.stop_timer(eventLoop);
1422 waiting_restart_timer = false;
1424 service_record::interrupt_start();
1427 void base_process_service::kill_with_fire() noexcept
1430 log(loglevel_t::WARN, "Service ", service_name, "with pid ", pid, " exceeded allowed stop time; killing.");
1435 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1437 if (service->service_state == service_state_t::STOPPING) {
1438 service->kill_with_fire();
1439 service->stop_timer_armed = false;
1442 // STARTING / STARTED:
1443 service->do_restart();
1445 return dasynq::rearm::DISARM;