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_name().c_str(), name) == 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::REGULAR) {
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_t::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 base_process_service::do_smooth_recovery() noexcept
168 if (! restart_ps_process()) {
170 services->process_queues();
174 void process_service::handle_exit_status(int exit_status) noexcept
176 bool did_exit = WIFEXITED(exit_status);
177 bool was_signalled = WIFSIGNALED(exit_status);
179 auto service_state = get_state();
181 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
183 log(loglevel_t::ERROR, "Service ", get_name(), " process terminated with exit code ",
184 WEXITSTATUS(exit_status));
186 else if (was_signalled) {
187 log(loglevel_t::ERROR, "Service ", get_name(), " terminated due to signal ",
188 WTERMSIG(exit_status));
192 if (service_state == service_state_t::STARTING) {
193 if (did_exit && WEXITSTATUS(exit_status) == 0) {
200 else if (service_state == service_state_t::STOPPING) {
201 // We won't log a non-zero exit status or termination due to signal here -
202 // we assume that the process died because we signalled it.
205 else if (smooth_recovery && service_state == service_state_t::STARTED
206 && get_target_state() == service_state_t::STARTED) {
207 do_smooth_recovery();
213 services->process_queues();
216 void process_service::exec_failed(int errcode) noexcept
218 log(loglevel_t::ERROR, get_name(), ": execution failed: ", strerror(errcode));
219 if (get_state() == service_state_t::STARTING) {
223 // Process service in smooth recovery:
228 void bgproc_service::handle_exit_status(int exit_status) noexcept
231 bool did_exit = WIFEXITED(exit_status);
232 bool was_signalled = WIFSIGNALED(exit_status);
233 auto service_state = get_state();
235 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
237 log(loglevel_t::ERROR, "Service ", get_name(), " process terminated with exit code ",
238 WEXITSTATUS(exit_status));
240 else if (was_signalled) {
241 log(loglevel_t::ERROR, "Service ", get_name(), " terminated due to signal ",
242 WTERMSIG(exit_status));
246 // This may be a "smooth recovery" where we are restarting the process while leaving the
247 // service in the STARTED state.
248 if (restarting && service_state == service_state_t::STARTED) {
250 bool need_stop = false;
251 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
255 // We need to re-read the PID, since it has now changed.
256 if (pid_file.length() != 0) {
257 auto pid_result = read_pid_file(&exit_status);
258 switch (pid_result) {
259 case pid_result_t::FAILED:
260 // Failed startup: no auto-restart.
263 case pid_result_t::TERMINATED:
265 case pid_result_t::OK:
272 // Failed startup: no auto-restart.
274 services->process_queues();
281 if (service_state == service_state_t::STARTING) {
282 // POSIX requires that if the process exited clearly with a status code of 0,
283 // the exit status value will be 0:
284 if (exit_status == 0) {
285 auto pid_result = read_pid_file(&exit_status);
286 switch (pid_result) {
287 case pid_result_t::FAILED:
288 // Failed startup: no auto-restart.
291 case pid_result_t::TERMINATED:
292 // started, but immediately terminated
295 case pid_result_t::OK:
304 else if (service_state == service_state_t::STOPPING) {
305 // We won't log a non-zero exit status or termination due to signal here -
306 // we assume that the process died because we signalled it.
309 else if (smooth_recovery && service_state == service_state_t::STARTED
310 && get_target_state() == service_state_t::STARTED) {
311 do_smooth_recovery();
315 // we must be STARTED
316 if (! do_auto_restart() && start_explicit) {
317 start_explicit = false;
324 services->process_queues();
327 void bgproc_service::exec_failed(int errcode) noexcept
329 log(loglevel_t::ERROR, get_name(), ": execution failed: ", strerror(errcode));
330 // Only time we execute is for startup:
334 void scripted_service::handle_exit_status(int exit_status) noexcept
336 bool did_exit = WIFEXITED(exit_status);
337 bool was_signalled = WIFSIGNALED(exit_status);
338 auto service_state = get_state();
340 if (service_state == service_state_t::STOPPING) {
341 if (did_exit && WEXITSTATUS(exit_status) == 0) {
345 // ??? failed to stop! Let's log it as info:
347 log(loglevel_t::INFO, "Service ", get_name(), " stop command failed with exit code ",
348 WEXITSTATUS(exit_status));
350 else if (was_signalled) {
351 log(loglevel_t::INFO, "Service ", get_name(), " stop command terminated due to signal ",
352 WTERMSIG(exit_status));
354 // Just assume that we stopped, so that any dependencies
358 services->process_queues();
361 if (exit_status == 0) {
367 log(loglevel_t::ERROR, "Service ", get_name(), " command failed with exit code ",
368 WEXITSTATUS(exit_status));
370 else if (was_signalled) {
371 log(loglevel_t::ERROR, "Service ", get_name(), " command terminated due to signal ",
372 WTERMSIG(exit_status));
376 services->process_queues();
380 void scripted_service::exec_failed(int errcode) noexcept
382 log(loglevel_t::ERROR, get_name(), ": execution failed: ", strerror(errcode));
383 auto service_state = get_state();
384 if (service_state == service_state_t::STARTING) {
387 else if (service_state == service_state_t::STOPPING) {
388 // We've logged the failure, but it's probably better not to leave the service in
394 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
396 base_process_service *sr = service;
397 sr->waiting_for_execstat = false;
400 int r = read(get_watched_fd(), &exec_status, sizeof(int));
402 close(get_watched_fd());
405 // We read an errno code; exec() failed, and the service startup failed.
407 sr->child_listener.deregister(eventLoop, sr->pid);
408 sr->reserved_child_watch = false;
409 if (sr->stop_timer_armed) {
410 sr->restart_timer.stop_timer(loop);
411 sr->stop_timer_armed = false;
415 sr->exec_failed(exec_status);
419 if (sr->get_type() == service_type_t::PROCESS) {
420 // This could be a smooth recovery (state already STARTED). Even more, the process
421 // might be stopped (and killed via a signal) during smooth recovery. We don't to
422 // process startup again in either case, so we check for state STARTING:
423 if (sr->get_state() == service_state_t::STARTING) {
426 else if (sr->get_state() == service_state_t::STOPPING) {
427 // stopping, but smooth recovery was in process. That's now over so we can
428 // commence normal stop. Note that if pid == -1 the process already stopped(!),
429 // that's handled below.
430 if (sr->pid != -1 && sr->stop_check_dependents()) {
437 // Somehow the process managed to complete before we even saw the status.
438 sr->handle_exit_status(sr->exit_status);
442 sr->services->process_queues();
444 return rearm::REMOVED;
447 void service_record::require() noexcept
449 if (required_by++ == 0) {
450 prop_require = !prop_release;
451 prop_release = false;
452 services->add_prop_queue(this);
456 void service_record::release() noexcept
458 if (--required_by == 0) {
459 desired_state = service_state_t::STOPPED;
461 // Can stop, and can release dependencies now. We don't need to issue a release if
462 // the require was pending though:
463 prop_release = !prop_require;
464 prop_require = false;
465 services->add_prop_queue(this);
467 if (service_state == service_state_t::STOPPED) {
468 services->service_inactive(this);
476 void service_record::release_dependencies() noexcept
478 for (auto & dependency : depends_on) {
479 service_record * dep_to = dependency.get_to();
480 if (dependency.holding_acq) {
482 dependency.holding_acq = false;
487 void service_record::start(bool activate) noexcept
489 if (activate && ! start_explicit) {
491 start_explicit = true;
494 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
496 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
497 desired_state = service_state_t::STARTED;
499 if (service_state != service_state_t::STOPPED) {
500 // We're already starting/started, or we are stopping and need to wait for
501 // that the complete.
502 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
505 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
506 // but if so they are waiting (for us), so they too can be instantly returned to
508 notify_listeners(service_event_t::STOPCANCELLED);
510 else if (! was_active) {
511 services->service_active(this);
514 service_state = service_state_t::STARTING;
515 waiting_for_deps = true;
517 if (start_check_dependencies()) {
518 services->add_transition_queue(this);
522 void service_record::do_propagation() noexcept
525 // Need to require all our dependencies
526 for (auto & dep : depends_on) {
527 dep.get_to()->require();
528 dep.holding_acq = true;
530 prop_require = false;
534 release_dependencies();
535 prop_release = false;
539 prop_failure = false;
540 failed_to_start(true);
554 void service_record::execute_transition() noexcept
556 // state is STARTED with restarting set true if we are running a smooth recovery.
557 if (service_state == service_state_t::STARTING || (service_state == service_state_t::STARTED
559 if (check_deps_started()) {
560 bool have_console = service_state == service_state_t::STARTED && onstart_flags.runs_on_console;
561 all_deps_started(have_console);
564 else if (service_state == service_state_t::STOPPING) {
565 if (stop_check_dependents()) {
571 void service_record::do_start() noexcept
573 if (pinned_stopped) return;
575 if (service_state != service_state_t::STARTING) {
579 service_state = service_state_t::STARTING;
581 waiting_for_deps = true;
583 // Ask dependencies to start, mark them as being waited on.
584 if (check_deps_started()) {
585 // Once all dependencies are started, we start properly:
590 void service_record::dependency_started() noexcept
592 if ((service_state == service_state_t::STARTING || service_state == service_state_t::STARTED)
593 && waiting_for_deps) {
594 services->add_transition_queue(this);
598 bool service_record::start_check_dependencies() noexcept
600 bool all_deps_started = true;
602 for (auto & dep : depends_on) {
603 service_record * to = dep.get_to();
604 if (to->service_state != service_state_t::STARTED) {
605 if (to->service_state != service_state_t::STARTING) {
606 to->prop_start = true;
607 services->add_prop_queue(to);
609 dep.waiting_on = true;
610 all_deps_started = false;
614 return all_deps_started;
617 bool service_record::check_deps_started() noexcept
619 for (auto & dep : depends_on) {
620 if (dep.waiting_on) {
628 bool service_record::open_socket() noexcept
630 if (socket_path.empty() || socket_fd != -1) {
631 // No socket, or already open
635 const char * saddrname = socket_path.c_str();
637 // Check the specified socket path
638 struct stat stat_buf;
639 if (stat(saddrname, &stat_buf) == 0) {
640 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
642 log(loglevel_t::ERROR, service_name, ": Activation socket file exists (and is not a socket)");
646 else if (errno != ENOENT) {
648 log(loglevel_t::ERROR, service_name, ": Error checking activation socket: ", strerror(errno));
652 // Remove stale socket file (if it exists).
653 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
654 // error when we try to create the socket anyway.
657 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
658 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
659 if (name == nullptr) {
660 log(loglevel_t::ERROR, service_name, ": Opening activation socket: out of memory");
664 name->sun_family = AF_UNIX;
665 strcpy(name->sun_path, saddrname);
667 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
669 log(loglevel_t::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
674 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
675 log(loglevel_t::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
683 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
684 // use chown and chmod instead.
685 if (chown(saddrname, socket_uid, socket_gid)) {
686 log(loglevel_t::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
691 if (chmod(saddrname, socket_perms) == -1) {
692 log(loglevel_t::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
697 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
698 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));
707 void service_record::all_deps_started(bool has_console) noexcept
709 if (onstart_flags.starts_on_console && ! has_console) {
710 waiting_for_deps = true;
715 waiting_for_deps = false;
717 if (! can_proceed_to_start()) {
718 waiting_for_deps = true;
722 if (! open_socket()) {
726 bool start_success = bring_up();
727 if (! start_success) {
732 void service_record::acquired_console() noexcept
734 if (service_state != service_state_t::STARTING) {
735 // We got the console but no longer want it.
738 else if (check_deps_started()) {
739 all_deps_started(true);
742 // We got the console but can't use it yet.
747 bgproc_service::pid_result_t
748 bgproc_service::read_pid_file(int *exit_status) noexcept
750 const char *pid_file_c = pid_file.c_str();
751 int fd = open(pid_file_c, O_CLOEXEC);
753 log(loglevel_t::ERROR, get_name(), ": read pid file: ", strerror(errno));
754 return pid_result_t::FAILED;
757 char pidbuf[21]; // just enough to hold any 64-bit integer
758 int r = ss_read(fd, pidbuf, 20);
760 // Could not read from PID file
761 log(loglevel_t::ERROR, get_name(), ": could not read from pidfile; ", strerror(errno));
763 return pid_result_t::FAILED;
767 pidbuf[r] = 0; // store nul terminator
769 bool valid_pid = false;
771 unsigned long long v = std::stoull(pidbuf, nullptr, 0);
772 if (v <= std::numeric_limits<pid_t>::max()) {
777 catch (std::out_of_range &exc) {
780 catch (std::invalid_argument &exc) {
781 // Ok, so it doesn't look like a number: proceed...
785 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
786 if (wait_r == -1 && errno == ECHILD) {
787 // We can't track this child - check process exists:
788 if (kill(pid, 0) == 0 || errno != ESRCH) {
789 tracking_child = false;
790 return pid_result_t::OK;
793 log(loglevel_t::ERROR, get_name(), ": pid read from pidfile (", pid, ") is not valid");
795 return pid_result_t::FAILED;
798 else if (wait_r == pid) {
800 return pid_result_t::TERMINATED;
802 else if (wait_r == 0) {
803 // We can track the child
804 child_listener.add_reserved(eventLoop, pid, DEFAULT_PRIORITY - 10);
805 tracking_child = true;
806 reserved_child_watch = true;
807 return pid_result_t::OK;
811 log(loglevel_t::ERROR, get_name(), ": pid read from pidfile (", pid, ") is not valid");
813 return pid_result_t::FAILED;
816 void service_record::started() noexcept
818 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
819 tcsetpgrp(0, getpgrp());
823 log_service_started(get_name());
824 service_state = service_state_t::STARTED;
825 notify_listeners(service_event_t::STARTED);
827 if (onstart_flags.rw_ready) {
828 open_control_socket();
830 if (onstart_flags.log_ready) {
831 setup_external_log();
834 if (force_stop || desired_state == service_state_t::STOPPED) {
840 // Notify any dependents whose desired state is STARTED:
841 for (auto dept : dependents) {
842 dept->get_from()->dependency_started();
843 dept->waiting_on = false;
847 void service_record::failed_to_start(bool depfailed) noexcept
849 if (!depfailed && onstart_flags.starts_on_console) {
850 tcsetpgrp(0, getpgrp());
854 log_service_failed(get_name());
855 service_state = service_state_t::STOPPED;
856 if (start_explicit) {
857 start_explicit = false;
860 notify_listeners(service_event_t::FAILEDSTART);
862 // Cancel start of dependents:
863 for (auto & dept : dependents) {
864 switch (dept->dep_type) {
865 case dependency_type::REGULAR:
866 case dependency_type::MILESTONE:
867 if (dept->get_from()->service_state == service_state_t::STARTING) {
868 dept->get_from()->prop_failure = true;
869 services->add_prop_queue(dept->get_from());
872 case dependency_type::WAITS_FOR:
873 case dependency_type::SOFT:
874 if (dept->waiting_on) {
875 dept->waiting_on = false;
876 dept->get_from()->dependency_started();
878 if (dept->holding_acq) {
879 dept->holding_acq = false;
886 bool service_record::bring_up() noexcept
888 // default implementation: there is no process, so we are started.
893 bool base_process_service::bring_up() noexcept
897 return restart_ps_process();
902 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
903 restart_interval_count = 0;
904 if (start_ps_process(exec_arg_parts, onstart_flags.starts_on_console)) {
905 if (start_timeout != time_val(0,0)) {
906 restart_timer.arm_timer_rel(eventLoop, start_timeout);
907 stop_timer_armed = true;
909 else if (stop_timer_armed) {
910 restart_timer.stop_timer(eventLoop);
911 stop_timer_armed = false;
919 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
921 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
922 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
923 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
924 // is written to the pipe, and the parent can read it.
926 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
929 if (pipe2(pipefd, O_CLOEXEC)) {
930 log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
934 const char * logfile = this->logfile.c_str();
936 logfile = "/dev/null";
939 bool child_status_registered = false;
940 control_conn_t *control_conn = nullptr;
942 int control_socket[2] = {-1, -1};
943 if (onstart_flags.pass_cs_fd) {
944 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
945 log(loglevel_t::ERROR, get_name(), ": can't create control socket: ", strerror(errno));
949 // Make the server side socket close-on-exec:
950 int fdflags = fcntl(control_socket[0], F_GETFD);
951 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
954 control_conn = new control_conn_t(eventLoop, services, control_socket[0]);
956 catch (std::exception &exc) {
957 log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
962 // Set up complete, now fork and exec:
967 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
968 child_status_registered = true;
970 // We specify a high priority (i.e. low priority value) so that process termination is
971 // handled early. This means we have always recorded that the process is terminated by the
972 // time that we handle events that might otherwise cause us to signal the process, so we
973 // avoid sending a signal to an invalid (and possibly recycled) process ID.
974 forkpid = child_listener.fork(eventLoop, reserved_child_watch, DEFAULT_PRIORITY - 10);
975 reserved_child_watch = true;
977 catch (std::exception &e) {
978 log(loglevel_t::ERROR, get_name(), ": Could not fork: ", e.what());
983 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
987 close(pipefd[1]); // close the 'other end' fd
988 if (control_socket[1] != -1) {
989 close(control_socket[1]);
993 waiting_for_execstat = true;
1000 if (child_status_registered) {
1001 child_status_listener.deregister(eventLoop);
1004 if (onstart_flags.pass_cs_fd) {
1005 delete control_conn;
1008 close(control_socket[0]);
1009 close(control_socket[1]);
1019 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
1020 int wpipefd, int csfd) noexcept
1022 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
1023 // from here until exit().
1025 // If the console already has a session leader, presumably it is us. On the other hand
1026 // if it has no session leader, and we don't create one, then control inputs such as
1027 // ^C will have no effect.
1028 bool do_set_ctty = (tcgetsid(0) == -1);
1030 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
1031 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
1032 sigset_t sigwait_set;
1033 sigset_t sigall_set;
1034 sigfillset(&sigall_set);
1035 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
1036 sigdelset(&sigwait_set, SIGCHLD);
1037 sigdelset(&sigwait_set, SIGINT);
1038 sigdelset(&sigwait_set, SIGTERM);
1039 sigdelset(&sigwait_set, SIGQUIT);
1041 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
1042 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
1043 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
1044 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
1047 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
1048 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
1049 char csenvbuf[csenvbufsz];
1051 int minfd = (socket_fd == -1) ? 3 : 4;
1053 // Move wpipefd/csfd to another fd if necessary
1054 if (wpipefd < minfd) {
1055 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
1056 if (wpipefd == -1) goto failure_out;
1059 if (csfd != -1 && csfd < minfd) {
1060 csfd = fcntl(csfd, F_DUPFD, minfd);
1061 if (csfd == -1) goto failure_out;
1064 if (socket_fd != -1) {
1066 if (dup2(socket_fd, 3) == -1) goto failure_out;
1067 if (socket_fd != 3) {
1071 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
1072 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
1073 if (putenv(nbuf)) goto failure_out;
1077 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
1078 if (putenv(csenvbuf)) goto failure_out;
1082 // Re-set stdin, stdout, stderr
1083 close(0); close(1); close(2);
1085 if (open("/dev/null", O_RDONLY) == 0) {
1086 // stdin = 0. That's what we should have; proceed with opening
1087 // stdout and stderr.
1088 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1091 if (dup2(1, 2) != 2) {
1095 else goto failure_out;
1097 // We have the option of creating a session and process group, or just a new process
1098 // group. If we just create a new process group, the child process cannot make itself
1099 // a session leader if it wants to do that (eg getty/login will generally want this).
1100 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1101 // will also affect the child process (which probably isn't so bad, though since we
1102 // will handle the shutdown ourselves it's not necessary). Creating a new session
1103 // (and a new process group as part of that) seems like a safe bet, and has the
1104 // advantage of letting us signal the process as part of a process group.
1108 // "run on console" - run as a foreground job on the terminal/console device
1110 // if do_set_ctty is false, we are the session leader; we are probably running
1111 // as a user process. Don't create a new session leader in that case, and run
1112 // as part of the parent session. Otherwise, the new session cannot claim the
1113 // terminal as a controlling terminal (it is already claimed), meaning that it
1114 // will not see control signals from ^C etc.
1117 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1118 signal(SIGTSTP, SIG_IGN);
1120 // Become session leader
1122 ioctl(0, TIOCSCTTY, 0);
1125 tcsetpgrp(0, getpgrp());
1128 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1130 execvp(args[0], const_cast<char **>(args));
1132 // If we got here, the exec failed:
1134 int exec_status = errno;
1135 write(wpipefd, &exec_status, sizeof(int));
1139 // Mark this and all dependent services as force-stopped.
1140 void service_record::forced_stop() noexcept
1142 if (service_state != service_state_t::STOPPED) {
1144 services->add_transition_queue(this);
1148 void service_record::dependent_stopped() noexcept
1150 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1151 services->add_transition_queue(this);
1155 void service_record::stop(bool bring_down) noexcept
1157 if (start_explicit) {
1158 start_explicit = false;
1167 void service_record::do_stop() noexcept
1169 if (pinned_started) return;
1171 if (start_explicit && ! do_auto_restart()) {
1172 start_explicit = false;
1174 if (required_by == 0) return; // release will re-call us anyway
1177 bool all_deps_stopped = stop_dependents();
1179 if (service_state != service_state_t::STARTED) {
1180 if (service_state == service_state_t::STARTING) {
1181 if (! can_interrupt_start()) {
1182 // Well this is awkward: we're going to have to continue starting. We can stop once we've
1183 // reached the started state.
1187 if (! interrupt_start()) {
1188 // Now wait for service startup to actually end
1192 // We must have had desired_state == STARTED.
1193 notify_listeners(service_event_t::STARTCANCELLED);
1195 // Reaching this point, we are starting interruptibly - so we
1196 // stop now (by falling through to below).
1199 // If we're starting we need to wait for that to complete.
1200 // If we're already stopping/stopped there's nothing to do.
1205 service_state = service_state_t::STOPPING;
1206 waiting_for_deps = true;
1207 if (all_deps_stopped) {
1208 services->add_transition_queue(this);
1212 bool service_record::stop_check_dependents() noexcept
1214 bool all_deps_stopped = true;
1215 for (auto dept : dependents) {
1216 if (dept->dep_type == dependency_type::REGULAR && ! dept->get_from()->is_stopped()) {
1217 all_deps_stopped = false;
1222 return all_deps_stopped;
1225 bool service_record::stop_dependents() noexcept
1227 bool all_deps_stopped = true;
1228 for (auto dept : dependents) {
1229 if (dept->dep_type == dependency_type::REGULAR) {
1230 if (! dept->get_from()->is_stopped()) {
1231 // Note we check *first* since if the dependent service is not stopped,
1232 // 1. We will issue a stop to it shortly and
1233 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1234 // check is run anyway.
1235 all_deps_stopped = false;
1239 // If this service is to be forcefully stopped, dependents must also be.
1240 dept->get_from()->forced_stop();
1243 dept->get_from()->prop_stop = true;
1244 services->add_prop_queue(dept->get_from());
1248 return all_deps_stopped;
1251 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1252 void service_record::bring_down() noexcept
1254 waiting_for_deps = false;
1258 void base_process_service::kill_pg(int signo) noexcept
1260 pid_t pgid = getpgid(pid);
1262 // only should happen if pid is invalid, which should never happen...
1263 log(loglevel_t::ERROR, get_name(), ": can't signal process: ", strerror(errno));
1269 void base_process_service::bring_down() noexcept
1271 waiting_for_deps = false;
1273 // The process is still kicking on - must actually kill it. We signal the process
1274 // group (-pid) rather than just the process as there's less risk then of creating
1275 // an orphaned process group:
1276 if (! onstart_flags.no_sigterm) {
1279 if (term_signal != -1) {
1280 kill_pg(term_signal);
1283 // In most cases, the rest is done in handle_exit_status.
1284 // If we are a BGPROCESS and the process is not our immediate child, however, that
1285 // won't work - check for this now:
1286 if (get_type() == service_type_t::BGPROCESS && ! tracking_child) {
1289 else if (stop_timeout != time_val(0,0)) {
1290 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1291 stop_timer_armed = true;
1295 // The process is already dead.
1300 void process_service::bring_down() noexcept
1302 waiting_for_deps = false;
1303 if (waiting_for_execstat) {
1304 // The process is still starting. This should be uncommon, but can occur during
1305 // smooth recovery. We can't do much now; we have to wait until we get the
1306 // status, and then act appropriately.
1309 else if (pid != -1) {
1310 // The process is still kicking on - must actually kill it. We signal the process
1311 // group (-pid) rather than just the process as there's less risk then of creating
1312 // an orphaned process group:
1313 if (! onstart_flags.no_sigterm) {
1316 if (term_signal != -1) {
1317 kill_pg(term_signal);
1320 // In most cases, the rest is done in handle_exit_status.
1321 // If we are a BGPROCESS and the process is not our immediate child, however, that
1322 // won't work - check for this now:
1323 if (get_type() == service_type_t::BGPROCESS && ! tracking_child) {
1326 else if (stop_timeout != time_val(0,0)) {
1327 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1328 stop_timer_armed = true;
1332 // The process is already dead.
1337 void scripted_service::bring_down() noexcept
1339 waiting_for_deps = false;
1340 if (stop_command.length() == 0) {
1343 else if (! start_ps_process(stop_arg_parts, false)) {
1344 // Couldn't execute stop script, but there's not much we can do:
1348 // successfully started stop script: start kill timer:
1349 if (stop_timeout != time_val(0,0)) {
1350 restart_timer.arm_timer_rel(eventLoop, stop_timeout);
1351 stop_timer_armed = true;
1356 void service_record::unpin() noexcept
1358 if (pinned_started) {
1359 pinned_started = false;
1360 if (desired_state == service_state_t::STOPPED || force_stop) {
1362 services->process_queues();
1365 if (pinned_stopped) {
1366 pinned_stopped = false;
1367 if (desired_state == service_state_t::STARTED) {
1369 services->process_queues();
1374 void service_record::queue_for_console() noexcept
1376 services->append_console_queue(this);
1379 void service_record::release_console() noexcept
1381 services->pull_console_queue();
1384 bool service_record::interrupt_start() noexcept
1386 services->unqueue_console(this);
1390 void service_set::service_active(service_record *sr) noexcept
1395 void service_set::service_inactive(service_record *sr) noexcept
1400 base_process_service::base_process_service(service_set *sset, string name,
1401 service_type_t service_type_p, string &&command,
1402 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1403 const std::list<prelim_dep> &deplist_p)
1404 : service_record(sset, name, service_type_p, deplist_p), child_listener(this),
1405 child_status_listener(this), restart_timer(this)
1407 program_name = std::move(command);
1408 exec_arg_parts = separate_args(program_name, command_offsets);
1410 restart_interval_count = 0;
1411 restart_interval_time = {0, 0};
1412 restart_timer.service = this;
1413 restart_timer.add_timer(eventLoop);
1415 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1416 restart_interval.seconds() = 10;
1417 restart_interval.nseconds() = 0;
1418 max_restart_interval_count = 3;
1420 waiting_restart_timer = false;
1421 reserved_child_watch = false;
1422 tracking_child = false;
1423 stop_timer_armed = false;
1424 start_is_interruptible = false;
1427 void base_process_service::do_restart() noexcept
1429 waiting_restart_timer = false;
1430 restart_interval_count++;
1431 auto service_state = get_state();
1433 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1434 // the process should be granted access to the console:
1435 bool on_console = service_state == service_state_t::STARTING
1436 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1438 if (service_state == service_state_t::STARTING) {
1439 // for a smooth recovery, we want to check dependencies are available before actually
1441 if (! check_deps_started()) {
1442 waiting_for_deps = true;
1447 if (! start_ps_process(exec_arg_parts, on_console)) {
1449 if (service_state == service_state_t::STARTING) {
1453 // desired_state = service_state_t::STOPPED;
1456 services->process_queues();
1460 bool base_process_service::restart_ps_process() noexcept
1462 using time_val = dasynq::time_val;
1464 time_val current_time;
1465 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1467 if (max_restart_interval_count != 0) {
1468 // Check whether we're still in the most recent restart check interval:
1469 time_val int_diff = current_time - restart_interval_time;
1470 if (int_diff < restart_interval) {
1471 if (restart_interval_count >= max_restart_interval_count) {
1472 log(loglevel_t::ERROR, "Service ", get_name(), " restarting too quickly; stopping.");
1477 restart_interval_time = current_time;
1478 restart_interval_count = 0;
1482 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1483 time_val tdiff = current_time - last_start_time;
1484 if (restart_delay <= tdiff) {
1485 // > restart delay (normally 200ms)
1489 time_val timeout = restart_delay - tdiff;
1490 restart_timer.arm_timer_rel(eventLoop, timeout);
1491 waiting_restart_timer = true;
1496 bool base_process_service::interrupt_start() noexcept
1498 if (waiting_restart_timer) {
1499 restart_timer.stop_timer(eventLoop);
1500 waiting_restart_timer = false;
1501 return service_record::interrupt_start();
1504 log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid, " (with SIGINT).");
1506 if (stop_timeout != time_val(0,0)) {
1507 restart_timer.arm_timer(eventLoop, stop_timeout);
1508 stop_timer_armed = true;
1510 else if (stop_timer_armed) {
1511 restart_timer.stop_timer(eventLoop);
1512 stop_timer_armed = false;
1514 set_state(service_state_t::STOPPING);
1519 void base_process_service::kill_with_fire() noexcept
1522 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid, " exceeded allowed stop time; killing.");
1527 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1529 service->stop_timer_armed = false;
1531 // Timer expires if:
1532 // We are stopping, including after having startup cancelled (stop timeout, state is STOPPING); We are
1533 // starting (start timeout, state is STARTING); We are waiting for restart timer before restarting,
1534 // including smooth recovery (restart timeout, state is STARTING or STARTED).
1535 if (service->get_state() == service_state_t::STOPPING) {
1536 service->kill_with_fire();
1538 else if (service->pid != -1) {
1539 // Starting, start timed out.
1540 service->interrupt_start();
1543 // STARTING / STARTED, and we have a pid: must be restarting (smooth recovery if STARTED)
1544 service->do_restart();
1547 // Leave the timer disabled, or, if it has been reset by any processing above, leave it armed:
1548 return dasynq::rearm::NOOP;