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 event_loop;
32 using clock_type = dasynq::clock_type;
33 using rearm = dasynq::rearm;
34 using time_val = dasynq::time_val;
36 // Find the requested service by name
37 static service_record * find_service(const std::list<service_record *> & records,
38 const char *name) noexcept
41 list<service_record *>::const_iterator i = records.begin();
42 for ( ; i != records.end(); i++ ) {
43 if (strcmp((*i)->get_name().c_str(), name) == 0) {
50 service_record * service_set::find_service(const std::string &name) noexcept
52 return ::find_service(records, name.c_str());
55 void service_set::stop_service(const std::string & name) noexcept
57 service_record *record = find_service(name);
58 if (record != nullptr) {
64 // Called when a service has actually stopped; dependents have stopped already, unless this stop
65 // is due to an unexpected process termination.
66 void service_record::stopped() noexcept
68 if (onstart_flags.runs_on_console) {
69 tcsetpgrp(0, getpgrp());
70 discard_console_log_buffer();
76 // If we are a soft dependency of another target, break the acquisition from that target now:
77 for (auto & dependent : dependents) {
78 if (dependent->dep_type != dependency_type::REGULAR) {
79 if (dependent->holding_acq) {
80 dependent->holding_acq = false;
86 bool will_restart = (desired_state == service_state_t::STARTED)
87 && services->get_auto_restart();
89 for (auto dependency : depends_on) {
90 // we signal dependencies in case they are waiting for us to stop:
91 dependency.get_to()->dependent_stopped();
94 service_state = service_state_t::STOPPED;
97 // Desired state is "started".
102 if (socket_fd != -1) {
107 if (start_explicit) {
108 start_explicit = false;
111 else if (required_by == 0) {
112 services->service_inactive(this);
116 log_service_stopped(service_name);
117 notify_listeners(service_event_t::STOPPED);
120 dasynq::rearm service_child_watcher::status_change(eventloop_t &loop, pid_t child, int status) noexcept
122 base_process_service *sr = service;
125 sr->exit_status = status;
127 // Ok, for a process service, any process death which we didn't rig
128 // ourselves is a bit... unexpected. Probably, the child died because
129 // we asked it to (sr->service_state == STOPPING). But even if
130 // we didn't, there's not much we can do.
132 if (sr->waiting_for_execstat) {
133 // We still don't have an exec() status from the forked child, wait for that
134 // before doing any further processing.
135 return dasynq::rearm::NOOP; // hold watch reservation
138 // Must stop watch now since handle_exit_status might result in re-launch:
139 // (stop_watch instead of deregister, so that we hold watch reservation).
142 if (sr->stop_timer_armed) {
143 sr->restart_timer.stop_timer(loop);
144 sr->stop_timer_armed = false;
147 sr->handle_exit_status(status);
148 return dasynq::rearm::NOOP;
151 bool service_record::do_auto_restart() noexcept
154 return services->get_auto_restart();
159 void service_record::emergency_stop() noexcept
161 if (! do_auto_restart() && start_explicit) {
162 start_explicit = false;
170 void base_process_service::do_smooth_recovery() noexcept
172 if (! restart_ps_process()) {
174 services->process_queues();
178 void process_service::handle_exit_status(int exit_status) noexcept
180 bool did_exit = WIFEXITED(exit_status);
181 bool was_signalled = WIFSIGNALED(exit_status);
183 auto service_state = get_state();
185 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
187 log(loglevel_t::ERROR, "Service ", get_name(), " process terminated with exit code ",
188 WEXITSTATUS(exit_status));
190 else if (was_signalled) {
191 log(loglevel_t::ERROR, "Service ", get_name(), " terminated due to signal ",
192 WTERMSIG(exit_status));
196 if (service_state == service_state_t::STARTING) {
197 if (did_exit && WEXITSTATUS(exit_status) == 0) {
204 else if (service_state == service_state_t::STOPPING) {
205 // We won't log a non-zero exit status or termination due to signal here -
206 // we assume that the process died because we signalled it.
209 else if (smooth_recovery && service_state == service_state_t::STARTED
210 && get_target_state() == service_state_t::STARTED) {
211 do_smooth_recovery();
217 services->process_queues();
220 void process_service::exec_failed(int errcode) noexcept
222 log(loglevel_t::ERROR, get_name(), ": execution failed: ", strerror(errcode));
223 if (get_state() == service_state_t::STARTING) {
227 // Process service in smooth recovery:
232 void bgproc_service::handle_exit_status(int exit_status) noexcept
235 bool did_exit = WIFEXITED(exit_status);
236 bool was_signalled = WIFSIGNALED(exit_status);
237 auto service_state = get_state();
239 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
241 log(loglevel_t::ERROR, "Service ", get_name(), " process terminated with exit code ",
242 WEXITSTATUS(exit_status));
244 else if (was_signalled) {
245 log(loglevel_t::ERROR, "Service ", get_name(), " terminated due to signal ",
246 WTERMSIG(exit_status));
250 // This may be a "smooth recovery" where we are restarting the process while leaving the
251 // service in the STARTED state.
252 if (restarting && service_state == service_state_t::STARTED) {
254 bool need_stop = false;
255 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
259 // We need to re-read the PID, since it has now changed.
260 if (pid_file.length() != 0) {
261 auto pid_result = read_pid_file(&exit_status);
262 switch (pid_result) {
263 case pid_result_t::FAILED:
264 // Failed startup: no auto-restart.
267 case pid_result_t::TERMINATED:
269 case pid_result_t::OK:
276 // Failed startup: no auto-restart.
278 services->process_queues();
285 if (service_state == service_state_t::STARTING) {
286 // POSIX requires that if the process exited clearly with a status code of 0,
287 // the exit status value will be 0:
288 if (exit_status == 0) {
289 auto pid_result = read_pid_file(&exit_status);
290 switch (pid_result) {
291 case pid_result_t::FAILED:
292 // Failed startup: no auto-restart.
295 case pid_result_t::TERMINATED:
296 // started, but immediately terminated
299 case pid_result_t::OK:
308 else if (service_state == service_state_t::STOPPING) {
309 // We won't log a non-zero exit status or termination due to signal here -
310 // we assume that the process died because we signalled it.
314 // we must be STARTED
315 if (smooth_recovery && get_target_state() == service_state_t::STARTED) {
316 do_smooth_recovery();
319 if (! do_auto_restart() && start_explicit) {
320 start_explicit = false;
327 services->process_queues();
330 void bgproc_service::exec_failed(int errcode) noexcept
332 log(loglevel_t::ERROR, get_name(), ": execution failed: ", strerror(errcode));
333 // Only time we execute is for startup:
337 void scripted_service::handle_exit_status(int exit_status) noexcept
339 bool did_exit = WIFEXITED(exit_status);
340 bool was_signalled = WIFSIGNALED(exit_status);
341 auto service_state = get_state();
343 // For a scripted service, a termination occurs in one of three main cases:
344 // - the start script completed (or failed), when service was STARTING
345 // - the start script was interrupted to cancel startup; state is STOPPING
346 // - the stop script complete (or failed), state is STOPPING
348 if (service_state == service_state_t::STOPPING) {
349 // We might be running the stop script, or we might be running the start script and have issued
350 // a cancel order via SIGINT:
351 if (did_exit && WEXITSTATUS(exit_status) == 0) {
352 if (interrupting_start) {
353 interrupting_start = false;
354 // launch stop script:
358 // We were running the stop script and finished successfully
363 if (interrupting_start) {
364 // We issued a start interrupt, so we expected this failure:
366 log(loglevel_t::INFO, "Service ", get_name(), " start cancelled; exit code ",
367 WEXITSTATUS(exit_status));
369 else if (was_signalled) {
370 log(loglevel_t::INFO, "Service ", get_name(), " start cancelled from signal ",
371 WTERMSIG(exit_status));
375 // ??? failed to stop! Let's log it as warning:
377 log(loglevel_t::WARN, "Service ", get_name(), " stop command failed with exit code ",
378 WEXITSTATUS(exit_status));
380 else if (was_signalled) {
381 log(loglevel_t::WARN, "Service ", get_name(), " stop command terminated due to signal ",
382 WTERMSIG(exit_status));
385 // Even if the stop script failed, assume that service is now stopped, so that any dependencies
386 // can be stopped. There's not really any other useful course of action here.
387 interrupting_start = false;
390 services->process_queues();
393 if (exit_status == 0) {
399 log(loglevel_t::ERROR, "Service ", get_name(), " command failed with exit code ",
400 WEXITSTATUS(exit_status));
402 else if (was_signalled) {
403 log(loglevel_t::ERROR, "Service ", get_name(), " command terminated due to signal ",
404 WTERMSIG(exit_status));
408 services->process_queues();
412 void scripted_service::exec_failed(int errcode) noexcept
414 log(loglevel_t::ERROR, get_name(), ": execution failed: ", strerror(errcode));
415 auto service_state = get_state();
416 if (service_state == service_state_t::STARTING) {
419 else if (service_state == service_state_t::STOPPING) {
420 // We've logged the failure, but it's probably better not to leave the service in
426 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
428 base_process_service *sr = service;
429 sr->waiting_for_execstat = false;
432 int r = read(get_watched_fd(), &exec_status, sizeof(int));
434 close(get_watched_fd());
437 // We read an errno code; exec() failed, and the service startup failed.
439 sr->child_listener.deregister(event_loop, sr->pid);
440 sr->reserved_child_watch = false;
441 if (sr->stop_timer_armed) {
442 sr->restart_timer.stop_timer(loop);
443 sr->stop_timer_armed = false;
447 sr->exec_failed(exec_status);
451 if (sr->get_type() == service_type_t::PROCESS) {
452 // This could be a smooth recovery (state already STARTED). Even more, the process
453 // might be stopped (and killed via a signal) during smooth recovery. We don't to
454 // process startup again in either case, so we check for state STARTING:
455 if (sr->get_state() == service_state_t::STARTING) {
458 else if (sr->get_state() == service_state_t::STOPPING) {
459 // stopping, but smooth recovery was in process. That's now over so we can
460 // commence normal stop. Note that if pid == -1 the process already stopped(!),
461 // that's handled below.
462 if (sr->pid != -1 && sr->stop_check_dependents()) {
469 // Somehow the process managed to complete before we even saw the status.
470 sr->handle_exit_status(sr->exit_status);
474 sr->services->process_queues();
476 return rearm::REMOVED;
479 void service_record::require() noexcept
481 if (required_by++ == 0) {
482 prop_require = !prop_release;
483 prop_release = false;
484 services->add_prop_queue(this);
488 void service_record::release() noexcept
490 if (--required_by == 0) {
491 desired_state = service_state_t::STOPPED;
493 // Can stop, and can release dependencies now. We don't need to issue a release if
494 // the require was pending though:
495 prop_release = !prop_require;
496 prop_require = false;
497 services->add_prop_queue(this);
499 if (service_state == service_state_t::STOPPED) {
500 services->service_inactive(this);
508 void service_record::release_dependencies() noexcept
510 for (auto & dependency : depends_on) {
511 service_record * dep_to = dependency.get_to();
512 if (dependency.holding_acq) {
514 dependency.holding_acq = false;
519 void service_record::start(bool activate) noexcept
521 if (activate && ! start_explicit) {
523 start_explicit = true;
526 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
528 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
529 desired_state = service_state_t::STARTED;
531 if (service_state != service_state_t::STOPPED) {
532 // We're already starting/started, or we are stopping and need to wait for
533 // that the complete.
534 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
537 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
538 // but if so they are waiting (for us), so they too can be instantly returned to
540 notify_listeners(service_event_t::STOPCANCELLED);
542 else if (! was_active) {
543 services->service_active(this);
546 service_state = service_state_t::STARTING;
547 waiting_for_deps = true;
549 if (start_check_dependencies()) {
550 services->add_transition_queue(this);
554 void service_record::do_propagation() noexcept
557 // Need to require all our dependencies
558 for (auto & dep : depends_on) {
559 dep.get_to()->require();
560 dep.holding_acq = true;
562 prop_require = false;
566 release_dependencies();
567 prop_release = false;
571 prop_failure = false;
572 failed_to_start(true);
586 void service_record::execute_transition() noexcept
588 // state is STARTED with restarting set true if we are running a smooth recovery.
589 if (service_state == service_state_t::STARTING || (service_state == service_state_t::STARTED
591 if (check_deps_started()) {
592 bool have_console = service_state == service_state_t::STARTED && onstart_flags.runs_on_console;
593 all_deps_started(have_console);
596 else if (service_state == service_state_t::STOPPING) {
597 if (stop_check_dependents()) {
603 void service_record::do_start() noexcept
605 if (pinned_stopped) return;
607 if (service_state != service_state_t::STARTING) {
611 service_state = service_state_t::STARTING;
613 waiting_for_deps = true;
615 // Ask dependencies to start, mark them as being waited on.
616 if (check_deps_started()) {
617 // Once all dependencies are started, we start properly:
622 void service_record::dependency_started() noexcept
624 if ((service_state == service_state_t::STARTING || service_state == service_state_t::STARTED)
625 && waiting_for_deps) {
626 services->add_transition_queue(this);
630 bool service_record::start_check_dependencies() noexcept
632 bool all_deps_started = true;
634 for (auto & dep : depends_on) {
635 service_record * to = dep.get_to();
636 if (to->service_state != service_state_t::STARTED) {
637 if (to->service_state != service_state_t::STARTING) {
638 to->prop_start = true;
639 services->add_prop_queue(to);
641 dep.waiting_on = true;
642 all_deps_started = false;
646 return all_deps_started;
649 bool service_record::check_deps_started() noexcept
651 for (auto & dep : depends_on) {
652 if (dep.waiting_on) {
660 bool service_record::open_socket() noexcept
662 if (socket_path.empty() || socket_fd != -1) {
663 // No socket, or already open
667 const char * saddrname = socket_path.c_str();
669 // Check the specified socket path
670 struct stat stat_buf;
671 if (stat(saddrname, &stat_buf) == 0) {
672 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
674 log(loglevel_t::ERROR, service_name, ": Activation socket file exists (and is not a socket)");
678 else if (errno != ENOENT) {
680 log(loglevel_t::ERROR, service_name, ": Error checking activation socket: ", strerror(errno));
684 // Remove stale socket file (if it exists).
685 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
686 // error when we try to create the socket anyway.
689 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
690 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
691 if (name == nullptr) {
692 log(loglevel_t::ERROR, service_name, ": Opening activation socket: out of memory");
696 name->sun_family = AF_UNIX;
697 strcpy(name->sun_path, saddrname);
699 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
701 log(loglevel_t::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
706 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
707 log(loglevel_t::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
715 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
716 // use chown and chmod instead.
717 if (chown(saddrname, socket_uid, socket_gid)) {
718 log(loglevel_t::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
723 if (chmod(saddrname, socket_perms) == -1) {
724 log(loglevel_t::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
729 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
730 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));
739 void service_record::all_deps_started(bool has_console) noexcept
741 if (onstart_flags.starts_on_console && ! has_console) {
742 waiting_for_deps = true;
747 waiting_for_deps = false;
749 if (! can_proceed_to_start()) {
750 waiting_for_deps = true;
754 if (! open_socket()) {
758 bool start_success = bring_up();
759 if (! start_success) {
764 void service_record::acquired_console() noexcept
766 if (service_state != service_state_t::STARTING) {
767 // We got the console but no longer want it.
770 else if (check_deps_started()) {
771 all_deps_started(true);
774 // We got the console but can't use it yet.
779 bgproc_service::pid_result_t
780 bgproc_service::read_pid_file(int *exit_status) noexcept
782 const char *pid_file_c = pid_file.c_str();
783 int fd = open(pid_file_c, O_CLOEXEC);
785 log(loglevel_t::ERROR, get_name(), ": read pid file: ", strerror(errno));
786 return pid_result_t::FAILED;
789 char pidbuf[21]; // just enough to hold any 64-bit integer
790 int r = ss_read(fd, pidbuf, 20);
792 // Could not read from PID file
793 log(loglevel_t::ERROR, get_name(), ": could not read from pidfile; ", strerror(errno));
795 return pid_result_t::FAILED;
799 pidbuf[r] = 0; // store nul terminator
801 bool valid_pid = false;
803 unsigned long long v = std::stoull(pidbuf, nullptr, 0);
804 if (v <= std::numeric_limits<pid_t>::max()) {
809 catch (std::out_of_range &exc) {
812 catch (std::invalid_argument &exc) {
813 // Ok, so it doesn't look like a number: proceed...
817 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
818 if (wait_r == -1 && errno == ECHILD) {
819 // We can't track this child - check process exists:
820 if (kill(pid, 0) == 0 || errno != ESRCH) {
821 tracking_child = false;
822 return pid_result_t::OK;
825 log(loglevel_t::ERROR, get_name(), ": pid read from pidfile (", pid, ") is not valid");
827 return pid_result_t::FAILED;
830 else if (wait_r == pid) {
832 return pid_result_t::TERMINATED;
834 else if (wait_r == 0) {
835 // We can track the child
836 child_listener.add_reserved(event_loop, pid, dasynq::DEFAULT_PRIORITY - 10);
837 tracking_child = true;
838 reserved_child_watch = true;
839 return pid_result_t::OK;
843 log(loglevel_t::ERROR, get_name(), ": pid read from pidfile (", pid, ") is not valid");
845 return pid_result_t::FAILED;
848 void service_record::started() noexcept
850 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
851 tcsetpgrp(0, getpgrp());
855 log_service_started(get_name());
856 service_state = service_state_t::STARTED;
857 notify_listeners(service_event_t::STARTED);
859 if (onstart_flags.rw_ready) {
860 open_control_socket();
862 if (onstart_flags.log_ready) {
863 setup_external_log();
866 if (force_stop || desired_state == service_state_t::STOPPED) {
872 // Notify any dependents whose desired state is STARTED:
873 for (auto dept : dependents) {
874 dept->get_from()->dependency_started();
875 dept->waiting_on = false;
879 void service_record::failed_to_start(bool depfailed) noexcept
881 if (!depfailed && onstart_flags.starts_on_console) {
882 tcsetpgrp(0, getpgrp());
886 log_service_failed(get_name());
887 service_state = service_state_t::STOPPED;
888 if (start_explicit) {
889 start_explicit = false;
892 notify_listeners(service_event_t::FAILEDSTART);
894 // Cancel start of dependents:
895 for (auto & dept : dependents) {
896 switch (dept->dep_type) {
897 case dependency_type::REGULAR:
898 case dependency_type::MILESTONE:
899 if (dept->get_from()->service_state == service_state_t::STARTING) {
900 dept->get_from()->prop_failure = true;
901 services->add_prop_queue(dept->get_from());
904 case dependency_type::WAITS_FOR:
905 case dependency_type::SOFT:
906 if (dept->waiting_on) {
907 dept->waiting_on = false;
908 dept->get_from()->dependency_started();
910 if (dept->holding_acq) {
911 dept->holding_acq = false;
918 bool service_record::bring_up() noexcept
920 // default implementation: there is no process, so we are started.
925 bool base_process_service::bring_up() noexcept
929 return restart_ps_process();
934 event_loop.get_time(restart_interval_time, clock_type::MONOTONIC);
935 restart_interval_count = 0;
936 if (start_ps_process(exec_arg_parts, onstart_flags.starts_on_console)) {
937 if (start_timeout != time_val(0,0)) {
938 restart_timer.arm_timer_rel(event_loop, start_timeout);
939 stop_timer_armed = true;
941 else if (stop_timer_armed) {
942 restart_timer.stop_timer(event_loop);
943 stop_timer_armed = false;
951 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
953 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
954 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
955 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
956 // is written to the pipe, and the parent can read it.
958 event_loop.get_time(last_start_time, clock_type::MONOTONIC);
961 if (dasynq::pipe2(pipefd, O_CLOEXEC)) {
962 log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
966 const char * logfile = this->logfile.c_str();
968 logfile = "/dev/null";
971 bool child_status_registered = false;
972 control_conn_t *control_conn = nullptr;
974 int control_socket[2] = {-1, -1};
975 if (onstart_flags.pass_cs_fd) {
976 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
977 log(loglevel_t::ERROR, get_name(), ": can't create control socket: ", strerror(errno));
981 // Make the server side socket close-on-exec:
982 int fdflags = fcntl(control_socket[0], F_GETFD);
983 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
986 control_conn = new control_conn_t(event_loop, services, control_socket[0]);
988 catch (std::exception &exc) {
989 log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
994 // Set up complete, now fork and exec:
999 child_status_listener.add_watch(event_loop, pipefd[0], dasynq::IN_EVENTS);
1000 child_status_registered = true;
1002 // We specify a high priority (i.e. low priority value) so that process termination is
1003 // handled early. This means we have always recorded that the process is terminated by the
1004 // time that we handle events that might otherwise cause us to signal the process, so we
1005 // avoid sending a signal to an invalid (and possibly recycled) process ID.
1006 forkpid = child_listener.fork(event_loop, reserved_child_watch, dasynq::DEFAULT_PRIORITY - 10);
1007 reserved_child_watch = true;
1009 catch (std::exception &e) {
1010 log(loglevel_t::ERROR, get_name(), ": Could not fork: ", e.what());
1015 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
1019 close(pipefd[1]); // close the 'other end' fd
1020 if (control_socket[1] != -1) {
1021 close(control_socket[1]);
1025 waiting_for_execstat = true;
1032 if (child_status_registered) {
1033 child_status_listener.deregister(event_loop);
1036 if (onstart_flags.pass_cs_fd) {
1037 delete control_conn;
1040 close(control_socket[0]);
1041 close(control_socket[1]);
1051 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
1052 int wpipefd, int csfd) noexcept
1054 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
1055 // from here until exit().
1057 // If the console already has a session leader, presumably it is us. On the other hand
1058 // if it has no session leader, and we don't create one, then control inputs such as
1059 // ^C will have no effect.
1060 bool do_set_ctty = (tcgetsid(0) == -1);
1062 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
1063 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
1064 sigset_t sigwait_set;
1065 sigset_t sigall_set;
1066 sigfillset(&sigall_set);
1067 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
1068 sigdelset(&sigwait_set, SIGCHLD);
1069 sigdelset(&sigwait_set, SIGINT);
1070 sigdelset(&sigwait_set, SIGTERM);
1071 sigdelset(&sigwait_set, SIGQUIT);
1073 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
1074 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
1075 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
1076 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
1079 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
1080 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
1081 char csenvbuf[csenvbufsz];
1083 int minfd = (socket_fd == -1) ? 3 : 4;
1085 // Move wpipefd/csfd to another fd if necessary
1086 if (wpipefd < minfd) {
1087 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
1088 if (wpipefd == -1) goto failure_out;
1091 if (csfd != -1 && csfd < minfd) {
1092 csfd = fcntl(csfd, F_DUPFD, minfd);
1093 if (csfd == -1) goto failure_out;
1096 if (socket_fd != -1) {
1098 if (dup2(socket_fd, 3) == -1) goto failure_out;
1099 if (socket_fd != 3) {
1103 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
1104 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
1105 if (putenv(nbuf)) goto failure_out;
1109 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
1110 if (putenv(csenvbuf)) goto failure_out;
1114 // Re-set stdin, stdout, stderr
1115 close(0); close(1); close(2);
1117 if (open("/dev/null", O_RDONLY) == 0) {
1118 // stdin = 0. That's what we should have; proceed with opening
1119 // stdout and stderr.
1120 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1123 if (dup2(1, 2) != 2) {
1127 else goto failure_out;
1129 // We have the option of creating a session and process group, or just a new process
1130 // group. If we just create a new process group, the child process cannot make itself
1131 // a session leader if it wants to do that (eg getty/login will generally want this).
1132 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1133 // will also affect the child process (which probably isn't so bad, though since we
1134 // will handle the shutdown ourselves it's not necessary). Creating a new session
1135 // (and a new process group as part of that) seems like a safe bet, and has the
1136 // advantage of letting us signal the process as part of a process group.
1140 // "run on console" - run as a foreground job on the terminal/console device
1142 // if do_set_ctty is false, we are the session leader; we are probably running
1143 // as a user process. Don't create a new session leader in that case, and run
1144 // as part of the parent session. Otherwise, the new session cannot claim the
1145 // terminal as a controlling terminal (it is already claimed), meaning that it
1146 // will not see control signals from ^C etc.
1149 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1150 signal(SIGTSTP, SIG_IGN);
1152 // Become session leader
1154 ioctl(0, TIOCSCTTY, 0);
1157 tcsetpgrp(0, getpgrp());
1160 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1162 execvp(args[0], const_cast<char **>(args));
1164 // If we got here, the exec failed:
1166 int exec_status = errno;
1167 write(wpipefd, &exec_status, sizeof(int));
1171 // Mark this and all dependent services as force-stopped.
1172 void service_record::forced_stop() noexcept
1174 if (service_state != service_state_t::STOPPED) {
1176 services->add_transition_queue(this);
1180 void service_record::dependent_stopped() noexcept
1182 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1183 services->add_transition_queue(this);
1187 void service_record::stop(bool bring_down) noexcept
1189 if (start_explicit) {
1190 start_explicit = false;
1199 void service_record::do_stop() noexcept
1201 if (pinned_started) return;
1203 if (start_explicit && ! do_auto_restart()) {
1204 start_explicit = false;
1206 if (required_by == 0) return; // release will re-call us anyway
1209 bool all_deps_stopped = stop_dependents();
1211 if (service_state != service_state_t::STARTED) {
1212 if (service_state == service_state_t::STARTING) {
1213 if (! can_interrupt_start()) {
1214 // Well this is awkward: we're going to have to continue starting. We can stop once we've
1215 // reached the started state.
1219 if (! interrupt_start()) {
1220 // Now wait for service startup to actually end; we don't need to handle it here.
1224 // We must have had desired_state == STARTED.
1225 notify_listeners(service_event_t::STARTCANCELLED);
1227 // Reaching this point, we are starting interruptibly - so we
1228 // stop now (by falling through to below).
1231 // If we're starting we need to wait for that to complete.
1232 // If we're already stopping/stopped there's nothing to do.
1237 service_state = service_state_t::STOPPING;
1238 waiting_for_deps = true;
1239 if (all_deps_stopped) {
1240 services->add_transition_queue(this);
1244 bool service_record::stop_check_dependents() noexcept
1246 bool all_deps_stopped = true;
1247 for (auto dept : dependents) {
1248 if (dept->dep_type == dependency_type::REGULAR && ! dept->get_from()->is_stopped()) {
1249 all_deps_stopped = false;
1254 return all_deps_stopped;
1257 bool service_record::stop_dependents() noexcept
1259 bool all_deps_stopped = true;
1260 for (auto dept : dependents) {
1261 if (dept->dep_type == dependency_type::REGULAR) {
1262 if (! dept->get_from()->is_stopped()) {
1263 // Note we check *first* since if the dependent service is not stopped,
1264 // 1. We will issue a stop to it shortly and
1265 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1266 // check is run anyway.
1267 all_deps_stopped = false;
1271 // If this service is to be forcefully stopped, dependents must also be.
1272 dept->get_from()->forced_stop();
1275 dept->get_from()->prop_stop = true;
1276 services->add_prop_queue(dept->get_from());
1280 return all_deps_stopped;
1283 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1284 void service_record::bring_down() noexcept
1286 waiting_for_deps = false;
1290 void base_process_service::kill_pg(int signo) noexcept
1292 pid_t pgid = getpgid(pid);
1294 // only should happen if pid is invalid, which should never happen...
1295 log(loglevel_t::ERROR, get_name(), ": can't signal process: ", strerror(errno));
1301 void base_process_service::bring_down() noexcept
1303 waiting_for_deps = false;
1305 // The process is still kicking on - must actually kill it. We signal the process
1306 // group (-pid) rather than just the process as there's less risk then of creating
1307 // an orphaned process group:
1308 if (! onstart_flags.no_sigterm) {
1311 if (term_signal != -1) {
1312 kill_pg(term_signal);
1315 // In most cases, the rest is done in handle_exit_status.
1316 // If we are a BGPROCESS and the process is not our immediate child, however, that
1317 // won't work - check for this now:
1318 if (get_type() == service_type_t::BGPROCESS && ! tracking_child) {
1321 else if (stop_timeout != time_val(0,0)) {
1322 restart_timer.arm_timer_rel(event_loop, stop_timeout);
1323 stop_timer_armed = true;
1327 // The process is already dead.
1332 void process_service::bring_down() noexcept
1334 waiting_for_deps = false;
1335 if (waiting_for_execstat) {
1336 // The process is still starting. This should be uncommon, but can occur during
1337 // smooth recovery. We can't do much now; we have to wait until we get the
1338 // status, and then act appropriately.
1341 else if (pid != -1) {
1342 // The process is still kicking on - must actually kill it. We signal the process
1343 // group (-pid) rather than just the process as there's less risk then of creating
1344 // an orphaned process group:
1345 if (! onstart_flags.no_sigterm) {
1348 if (term_signal != -1) {
1349 kill_pg(term_signal);
1352 // In most cases, the rest is done in handle_exit_status.
1353 // If we are a BGPROCESS and the process is not our immediate child, however, that
1354 // won't work - check for this now:
1355 if (get_type() == service_type_t::BGPROCESS && ! tracking_child) {
1358 else if (stop_timeout != time_val(0,0)) {
1359 restart_timer.arm_timer_rel(event_loop, stop_timeout);
1360 stop_timer_armed = true;
1364 // The process is already dead.
1369 void scripted_service::bring_down() noexcept
1371 waiting_for_deps = false;
1372 if (stop_command.length() == 0) {
1375 else if (! start_ps_process(stop_arg_parts, false)) {
1376 // Couldn't execute stop script, but there's not much we can do:
1380 // successfully started stop script: start kill timer:
1381 if (stop_timeout != time_val(0,0)) {
1382 restart_timer.arm_timer_rel(event_loop, stop_timeout);
1383 stop_timer_armed = true;
1388 void service_record::unpin() noexcept
1390 if (pinned_started) {
1391 pinned_started = false;
1392 if (desired_state == service_state_t::STOPPED || force_stop) {
1394 services->process_queues();
1397 if (pinned_stopped) {
1398 pinned_stopped = false;
1399 if (desired_state == service_state_t::STARTED) {
1401 services->process_queues();
1406 void service_record::queue_for_console() noexcept
1408 services->append_console_queue(this);
1411 void service_record::release_console() noexcept
1413 services->pull_console_queue();
1416 bool service_record::interrupt_start() noexcept
1418 services->unqueue_console(this);
1422 void service_set::service_active(service_record *sr) noexcept
1427 void service_set::service_inactive(service_record *sr) noexcept
1432 base_process_service::base_process_service(service_set *sset, string name,
1433 service_type_t service_type_p, string &&command,
1434 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1435 const std::list<prelim_dep> &deplist_p)
1436 : service_record(sset, name, service_type_p, deplist_p), child_listener(this),
1437 child_status_listener(this), restart_timer(this)
1439 program_name = std::move(command);
1440 exec_arg_parts = separate_args(program_name, command_offsets);
1442 restart_interval_count = 0;
1443 restart_interval_time = {0, 0};
1444 restart_timer.service = this;
1445 restart_timer.add_timer(event_loop);
1447 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1448 restart_interval.seconds() = 10;
1449 restart_interval.nseconds() = 0;
1450 max_restart_interval_count = 3;
1452 waiting_restart_timer = false;
1453 reserved_child_watch = false;
1454 tracking_child = false;
1455 stop_timer_armed = false;
1456 start_is_interruptible = false;
1459 void base_process_service::do_restart() noexcept
1461 waiting_restart_timer = false;
1462 restart_interval_count++;
1463 auto service_state = get_state();
1465 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1466 // the process should be granted access to the console:
1467 bool on_console = service_state == service_state_t::STARTING
1468 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1470 if (service_state == service_state_t::STARTING) {
1471 // for a smooth recovery, we want to check dependencies are available before actually
1473 if (! check_deps_started()) {
1474 waiting_for_deps = true;
1479 if (! start_ps_process(exec_arg_parts, on_console)) {
1481 if (service_state == service_state_t::STARTING) {
1485 // desired_state = service_state_t::STOPPED;
1488 services->process_queues();
1492 bool base_process_service::restart_ps_process() noexcept
1494 using time_val = dasynq::time_val;
1496 time_val current_time;
1497 event_loop.get_time(current_time, clock_type::MONOTONIC);
1499 if (max_restart_interval_count != 0) {
1500 // Check whether we're still in the most recent restart check interval:
1501 time_val int_diff = current_time - restart_interval_time;
1502 if (int_diff < restart_interval) {
1503 if (restart_interval_count >= max_restart_interval_count) {
1504 log(loglevel_t::ERROR, "Service ", get_name(), " restarting too quickly; stopping.");
1509 restart_interval_time = current_time;
1510 restart_interval_count = 0;
1514 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1515 time_val tdiff = current_time - last_start_time;
1516 if (restart_delay <= tdiff) {
1517 // > restart delay (normally 200ms)
1521 time_val timeout = restart_delay - tdiff;
1522 restart_timer.arm_timer_rel(event_loop, timeout);
1523 waiting_restart_timer = true;
1528 bool base_process_service::interrupt_start() noexcept
1530 if (waiting_restart_timer) {
1531 restart_timer.stop_timer(event_loop);
1532 waiting_restart_timer = false;
1533 return service_record::interrupt_start();
1536 log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid, " (with SIGINT).");
1538 if (stop_timeout != time_val(0,0)) {
1539 restart_timer.arm_timer(event_loop, stop_timeout);
1540 stop_timer_armed = true;
1542 else if (stop_timer_armed) {
1543 restart_timer.stop_timer(event_loop);
1544 stop_timer_armed = false;
1546 set_state(service_state_t::STOPPING);
1551 void base_process_service::kill_with_fire() noexcept
1554 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid, " exceeded allowed stop time; killing.");
1559 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1561 service->stop_timer_armed = false;
1563 // Timer expires if:
1564 // We are stopping, including after having startup cancelled (stop timeout, state is STOPPING); We are
1565 // starting (start timeout, state is STARTING); We are waiting for restart timer before restarting,
1566 // including smooth recovery (restart timeout, state is STARTING or STARTED).
1567 if (service->get_state() == service_state_t::STOPPING) {
1568 service->kill_with_fire();
1570 else if (service->pid != -1) {
1571 // Starting, start timed out.
1572 service->interrupt_start();
1575 // STARTING / STARTED, and we have a pid: must be restarting (smooth recovery if STARTED)
1576 service->do_restart();
1579 // Leave the timer disabled, or, if it has been reset by any processing above, leave it armed:
1580 return dasynq::rearm::NOOP;