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)->getServiceName().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::stopService(const std::string & name) noexcept
53 service_record *record = find_service(name);
54 if (record != nullptr) {
60 // Called when a service has actually stopped; dependents have stopped already, unless this stop
61 // is due to an unexpected process termination.
62 void service_record::stopped() noexcept
64 if (onstart_flags.runs_on_console) {
65 tcsetpgrp(0, getpgrp());
66 discard_console_log_buffer();
72 // If we are a soft dependency of another target, break the acquisition from that target now:
73 for (auto dependent : soft_dpts) {
74 if (dependent->holding_acq) {
75 dependent->holding_acq = false;
80 bool will_restart = (desired_state == service_state_t::STARTED)
81 && services->get_auto_restart();
83 for (auto dependency : depends_on) {
84 // we signal dependencies in case they are waiting for us to stop:
85 dependency->dependent_stopped();
88 service_state = service_state_t::STOPPED;
91 // Desired state is "started".
96 if (socket_fd != -1) {
101 if (start_explicit) {
102 start_explicit = false;
105 else if (required_by == 0) {
106 services->service_inactive(this);
110 logServiceStopped(service_name);
111 notify_listeners(service_event::STOPPED);
114 dasynq::rearm service_child_watcher::status_change(eventloop_t &loop, pid_t child, int status) noexcept
116 base_process_service *sr = service;
119 sr->exit_status = status;
121 // Ok, for a process service, any process death which we didn't rig
122 // ourselves is a bit... unexpected. Probably, the child died because
123 // we asked it to (sr->service_state == STOPPING). But even if
124 // we didn't, there's not much we can do.
126 if (sr->waiting_for_execstat) {
127 // We still don't have an exec() status from the forked child, wait for that
128 // before doing any further processing.
129 return rearm::NOOP; // hold watch reservation
132 // Must stop watch now since handle_exit_status might result in re-launch:
133 // (stop_watch instead of deregister, so that we hold watch reservation).
136 sr->handle_exit_status(status);
140 bool service_record::do_auto_restart() noexcept
143 return services->get_auto_restart();
148 void service_record::emergency_stop() noexcept
150 if (! do_auto_restart() && start_explicit) {
151 start_explicit = false;
159 void process_service::handle_exit_status(int exit_status) noexcept
161 bool did_exit = WIFEXITED(exit_status);
162 bool was_signalled = WIFSIGNALED(exit_status);
164 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
166 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
168 else if (was_signalled) {
169 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
173 if (service_state == service_state_t::STARTING) {
174 if (did_exit && WEXITSTATUS(exit_status) == 0) {
181 else if (service_state == service_state_t::STOPPING) {
182 // We won't log a non-zero exit status or termination due to signal here -
183 // we assume that the process died because we signalled it.
186 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
187 // TODO if we are pinned-started then we should probably check
188 // that dependencies have started before trying to re-start the
190 if (! restart_ps_process()) {
192 services->process_queues();
199 services->process_queues();
202 void bgproc_service::handle_exit_status(int exit_status) noexcept
205 bool did_exit = WIFEXITED(exit_status);
206 bool was_signalled = WIFSIGNALED(exit_status);
208 if (exit_status != 0 && service_state != service_state_t::STOPPING) {
210 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
212 else if (was_signalled) {
213 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
217 if (doing_recovery) {
218 doing_recovery = false;
219 bool need_stop = false;
220 if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
224 // We need to re-read the PID, since it has now changed.
225 if (pid_file.length() != 0) {
226 auto pid_result = read_pid_file(&exit_status);
227 switch (pid_result) {
228 case pid_result_t::FAILED:
229 // Failed startup: no auto-restart.
232 case pid_result_t::TERMINATED:
234 case pid_result_t::OK:
241 // Failed startup: no auto-restart.
243 services->process_queues();
249 if (service_state == service_state_t::STARTING) {
250 // POSIX requires that if the process exited clearly with a status code of 0,
251 // the exit status value will be 0:
252 if (exit_status == 0) {
253 auto pid_result = read_pid_file(&exit_status);
254 switch (pid_result) {
255 case pid_result_t::FAILED:
256 // Failed startup: no auto-restart.
259 case pid_result_t::TERMINATED:
260 // started, but immediately terminated
263 case pid_result_t::OK:
272 else if (service_state == service_state_t::STOPPING) {
273 // We won't log a non-zero exit status or termination due to signal here -
274 // we assume that the process died because we signalled it.
277 else if (smooth_recovery && service_state == service_state_t::STARTED && desired_state == service_state_t::STARTED) {
278 // TODO if we are pinned-started then we should probably check
279 // that dependencies have started before trying to re-start the
281 doing_recovery = true;
282 if (! restart_ps_process()) {
284 services->process_queues();
289 // we must be STARTED
290 if (! do_auto_restart() && start_explicit) {
291 start_explicit = false;
298 services->process_queues();
301 void scripted_service::handle_exit_status(int exit_status) noexcept
303 bool did_exit = WIFEXITED(exit_status);
304 bool was_signalled = WIFSIGNALED(exit_status);
306 if (service_state == service_state_t::STOPPING) {
307 if (did_exit && WEXITSTATUS(exit_status) == 0) {
311 // ??? failed to stop! Let's log it as info:
313 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
315 else if (was_signalled) {
316 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
318 // Just assume that we stopped, so that any dependencies
322 services->process_queues();
325 if (exit_status == 0) {
331 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
333 else if (was_signalled) {
334 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
338 services->process_queues();
342 rearm exec_status_pipe_watcher::fd_event(eventloop_t &loop, int fd, int flags) noexcept
344 base_process_service *sr = service;
345 sr->waiting_for_execstat = false;
348 int r = read(get_watched_fd(), &exec_status, sizeof(int));
350 close(get_watched_fd());
353 // We read an errno code; exec() failed, and the service startup failed.
355 sr->child_listener.deregister(eventLoop, sr->pid);
356 sr->reserved_child_watch = false;
359 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
360 if (sr->service_state == service_state_t::STARTING) {
361 sr->failed_to_start();
363 else if (sr->service_state == service_state_t::STOPPING) {
364 // Must be a scripted service. We've logged the failure, but it's probably better
365 // not to leave the service in STARTED state:
371 if (sr->record_type == service_type::PROCESS) {
372 // This could be a smooth recovery (state already STARTED). Even more, the process
373 // might be stopped (and killed via a signal) during smooth recovery. We don't to
374 // process startup again in either case, so we check for state STARTING:
375 if (sr->service_state == service_state_t::STARTING) {
381 // Somehow the process managed to complete before we even saw the status.
382 sr->handle_exit_status(sr->exit_status);
386 sr->services->process_queues();
388 return rearm::REMOVED;
391 void service_record::require() noexcept
393 if (required_by++ == 0) {
394 prop_require = !prop_release;
395 prop_release = false;
396 services->addToPropQueue(this);
400 void service_record::release() noexcept
402 if (--required_by == 0) {
403 desired_state = service_state_t::STOPPED;
405 // Can stop, and can release dependencies now. We don't need to issue a release if
406 // the require was pending though:
407 prop_release = !prop_require;
408 prop_require = false;
409 services->addToPropQueue(this);
411 if (service_state == service_state_t::STOPPED) {
412 services->service_inactive(this);
420 void service_record::release_dependencies() noexcept
422 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
426 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
427 service_record * to = i->getTo();
428 if (i->holding_acq) {
430 i->holding_acq = false;
435 void service_record::start(bool activate) noexcept
437 if (activate && ! start_explicit) {
439 start_explicit = true;
442 if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
444 bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
445 desired_state = service_state_t::STARTED;
447 if (service_state != service_state_t::STOPPED) {
448 // We're already starting/started, or we are stopping and need to wait for
449 // that the complete.
450 if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
453 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
454 // but if so they are waiting (for us), so they too can be instantly returned to
456 notify_listeners(service_event::STOPCANCELLED);
458 else if (! was_active) {
459 services->service_active(this);
462 service_state = service_state_t::STARTING;
463 waiting_for_deps = true;
465 if (start_check_dependencies(true)) {
466 services->addToStartQueue(this);
470 void service_record::do_propagation() noexcept
473 // Need to require all our dependencies
474 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
478 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
479 service_record * to = i->getTo();
481 i->holding_acq = true;
484 prop_require = false;
488 release_dependencies();
489 prop_release = false;
493 prop_failure = false;
494 failed_to_start(true);
508 void service_record::execute_transition() noexcept
510 if (service_state == service_state_t::STARTING) {
511 if (start_check_dependencies(false)) {
512 all_deps_started(false);
515 else if (service_state == service_state_t::STOPPING) {
516 if (stop_check_dependents()) {
522 void service_record::do_start() noexcept
524 if (pinned_stopped) return;
526 if (service_state != service_state_t::STARTING) {
530 service_state = service_state_t::STARTING;
532 waiting_for_deps = true;
534 // Ask dependencies to start, mark them as being waited on.
535 if (start_check_dependencies(false)) {
536 // Once all dependencies are started, we start properly:
541 void service_record::dependencyStarted() noexcept
543 if (service_state == service_state_t::STARTING && waiting_for_deps) {
544 services->addToStartQueue(this);
548 bool service_record::start_check_dependencies(bool start_deps) noexcept
550 bool all_deps_started = true;
552 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
553 if ((*i)->service_state != service_state_t::STARTED) {
555 all_deps_started = false;
556 (*i)->prop_start = true;
557 services->addToPropQueue(*i);
565 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
566 service_record * to = i->getTo();
568 if (to->service_state != service_state_t::STARTED) {
569 to->prop_start = true;
570 services->addToPropQueue(to);
571 i->waiting_on = true;
572 all_deps_started = false;
575 i->waiting_on = false;
578 else if (i->waiting_on) {
579 if (to->service_state != service_state_t::STARTING) {
580 // Service has either started or is no longer starting
581 i->waiting_on = false;
584 // We are still waiting on this service
590 return all_deps_started;
593 bool service_record::open_socket() noexcept
595 if (socket_path.empty() || socket_fd != -1) {
596 // No socket, or already open
600 const char * saddrname = socket_path.c_str();
602 // Check the specified socket path
603 struct stat stat_buf;
604 if (stat(saddrname, &stat_buf) == 0) {
605 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
607 log(LogLevel::ERROR, service_name, ": Activation socket file exists (and is not a socket)");
611 else if (errno != ENOENT) {
613 log(LogLevel::ERROR, service_name, ": Error checking activation socket: ", strerror(errno));
617 // Remove stale socket file (if it exists).
618 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
619 // error when we try to create the socket anyway.
622 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
623 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
624 if (name == nullptr) {
625 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
629 name->sun_family = AF_UNIX;
630 strcpy(name->sun_path, saddrname);
632 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
634 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
639 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
640 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
648 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
649 // use chown and chmod instead.
650 if (chown(saddrname, socket_uid, socket_gid)) {
651 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
656 if (chmod(saddrname, socket_perms) == -1) {
657 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
662 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
663 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
672 void service_record::all_deps_started(bool has_console) noexcept
674 if (onstart_flags.starts_on_console && ! has_console) {
675 waiting_for_deps = true;
680 waiting_for_deps = false;
682 // We overload can_interrupt_start to check whether there is any other
683 // process (eg restart timer) that needs to finish before starting.
684 if (can_interrupt_start()) {
685 waiting_for_deps = true;
689 if (! open_socket()) {
693 bool start_success = start_ps_process();
694 if (! start_success) {
699 void service_record::acquiredConsole() noexcept
701 if (service_state != service_state_t::STARTING) {
702 // We got the console but no longer want it.
705 else if (start_check_dependencies(false)) {
706 all_deps_started(true);
709 // We got the console but can't use it yet.
714 bgproc_service::pid_result_t
715 bgproc_service::read_pid_file(int *exit_status) noexcept
717 const char *pid_file_c = pid_file.c_str();
718 int fd = open(pid_file_c, O_CLOEXEC);
720 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
721 return pid_result_t::FAILED;
724 char pidbuf[21]; // just enough to hold any 64-bit integer
725 int r = ss_read(fd, pidbuf, 20);
727 // Could not read from PID file
728 log(LogLevel::ERROR, service_name, ": could not read from pidfile; ", strerror(errno));
730 return pid_result_t::FAILED;
734 pidbuf[r] = 0; // store nul terminator
736 bool valid_pid = false;
738 unsigned long long v = std::stoull(pidbuf, nullptr, 0);
739 if (v <= std::numeric_limits<pid_t>::max()) {
744 catch (std::out_of_range &exc) {
747 catch (std::invalid_argument &exc) {
748 // Ok, so it doesn't look like a number: proceed...
752 pid_t wait_r = waitpid(pid, exit_status, WNOHANG);
753 if (wait_r == -1 && errno == ECHILD) {
754 // We can't track this child - check process exists:
755 if (kill(pid, 0) == 0 || errno != ESRCH) {
756 tracking_child = false;
757 return pid_result_t::OK;
760 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
762 return pid_result_t::FAILED;
765 else if (wait_r == pid) {
767 return pid_result_t::TERMINATED;
769 else if (wait_r == 0) {
770 // We can track the child
771 child_listener.add_reserved(eventLoop, pid, DEFAULT_PRIORITY - 10);
772 tracking_child = true;
773 reserved_child_watch = true;
774 return pid_result_t::OK;
778 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
780 return pid_result_t::FAILED;
783 void service_record::started() noexcept
785 if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
786 tcsetpgrp(0, getpgrp());
790 logServiceStarted(service_name);
791 service_state = service_state_t::STARTED;
792 notify_listeners(service_event::STARTED);
794 if (onstart_flags.rw_ready) {
795 open_control_socket();
797 if (onstart_flags.log_ready) {
798 setup_external_log();
801 if (force_stop || desired_state == service_state_t::STOPPED) {
807 // Notify any dependents whose desired state is STARTED:
808 for (auto i = dependents.begin(); i != dependents.end(); i++) {
809 (*i)->dependencyStarted();
811 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
812 (*i)->getFrom()->dependencyStarted();
816 void service_record::failed_to_start(bool depfailed) noexcept
818 if (!depfailed && onstart_flags.starts_on_console) {
819 tcsetpgrp(0, getpgrp());
823 logServiceFailed(service_name);
824 service_state = service_state_t::STOPPED;
825 if (start_explicit) {
826 start_explicit = false;
829 notify_listeners(service_event::FAILEDSTART);
831 // Cancel start of dependents:
832 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
833 if ((*i)->service_state == service_state_t::STARTING) {
834 (*i)->prop_failure = true;
835 services->addToPropQueue(*i);
838 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
839 // We can send 'start', because this is only a soft dependency.
840 // Our startup failure means that they don't have to wait for us.
841 if ((*i)->waiting_on) {
842 (*i)->holding_acq = false;
843 (*i)->waiting_on = false;
844 (*i)->getFrom()->dependencyStarted();
850 bool service_record::start_ps_process() noexcept
852 // default implementation: there is no process, so we are started.
857 bool base_process_service::start_ps_process() noexcept
860 return restart_ps_process();
863 eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
864 restart_interval_count = 0;
865 return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
869 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
871 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
872 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
873 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
874 // is written to the pipe, and the parent can read it.
876 eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
879 if (pipe2(pipefd, O_CLOEXEC)) {
880 log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
884 const char * logfile = this->logfile.c_str();
886 logfile = "/dev/null";
889 bool child_status_registered = false;
890 control_conn_t *control_conn = nullptr;
892 int control_socket[2] = {-1, -1};
893 if (onstart_flags.pass_cs_fd) {
894 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
895 log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
899 // Make the server side socket close-on-exec:
900 int fdflags = fcntl(control_socket[0], F_GETFD);
901 fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
904 control_conn = new control_conn_t(&eventLoop, services, control_socket[0]);
906 catch (std::exception &exc) {
907 log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
912 // Set up complete, now fork and exec:
917 child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
918 child_status_registered = true;
920 // We specify a high priority (i.e. low priority value) so that process termination is
921 // handled early. This means we have always recorded that the process is terminated by the
922 // time that we handle events that might otherwise cause us to signal the process, so we
923 // avoid sending a signal to an invalid (and possibly recycled) process ID.
924 forkpid = child_listener.fork(eventLoop, reserved_child_watch, DEFAULT_PRIORITY - 10);
925 reserved_child_watch = true;
927 catch (std::exception &e) {
928 log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
933 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
937 close(pipefd[1]); // close the 'other end' fd
938 if (control_socket[1] != -1) {
939 close(control_socket[1]);
943 waiting_for_execstat = true;
950 if (child_status_registered) {
951 child_status_listener.deregister(eventLoop);
954 if (onstart_flags.pass_cs_fd) {
958 close(control_socket[0]);
959 close(control_socket[1]);
969 void service_record::run_child_proc(const char * const *args, const char *logfile, bool on_console,
970 int wpipefd, int csfd) noexcept
972 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
973 // from here until exit().
975 // If the console already has a session leader, presumably it is us. On the other hand
976 // if it has no session leader, and we don't create one, then control inputs such as
977 // ^C will have no effect.
978 bool do_set_ctty = (tcgetsid(0) == -1);
980 // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
981 // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
982 sigset_t sigwait_set;
984 sigfillset(&sigall_set);
985 sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
986 sigdelset(&sigwait_set, SIGCHLD);
987 sigdelset(&sigwait_set, SIGINT);
988 sigdelset(&sigwait_set, SIGTERM);
989 sigdelset(&sigwait_set, SIGQUIT);
991 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
992 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
993 // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
994 // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
997 // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
998 constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
999 char csenvbuf[csenvbufsz];
1001 int minfd = (socket_fd == -1) ? 3 : 4;
1003 // Move wpipefd/csfd to another fd if necessary
1004 if (wpipefd < minfd) {
1005 wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
1006 if (wpipefd == -1) goto failure_out;
1009 if (csfd != -1 && csfd < minfd) {
1010 csfd = fcntl(csfd, F_DUPFD, minfd);
1011 if (csfd == -1) goto failure_out;
1014 if (socket_fd != -1) {
1016 if (dup2(socket_fd, 3) == -1) goto failure_out;
1017 if (socket_fd != 3) {
1021 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
1022 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
1023 if (putenv(nbuf)) goto failure_out;
1027 snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
1028 if (putenv(csenvbuf)) goto failure_out;
1032 // Re-set stdin, stdout, stderr
1033 close(0); close(1); close(2);
1035 if (open("/dev/null", O_RDONLY) == 0) {
1036 // stdin = 0. That's what we should have; proceed with opening
1037 // stdout and stderr.
1038 if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
1041 if (dup2(1, 2) != 2) {
1045 else goto failure_out;
1047 // We have the option of creating a session and process group, or just a new process
1048 // group. If we just create a new process group, the child process cannot make itself
1049 // a session leader if it wants to do that (eg getty/login will generally want this).
1050 // If we do neither, and we are running with a controlling terminal, a ^C or similar
1051 // will also affect the child process (which probably isn't so bad, though since we
1052 // will handle the shutdown ourselves it's not necessary). Creating a new session
1053 // (and a new process group as part of that) seems like a safe bet, and has the
1054 // advantage of letting us signal the process as part of a process group.
1058 // "run on console" - run as a foreground job on the terminal/console device
1060 // if do_set_ctty is false, we are the session leader; we are probably running
1061 // as a user process. Don't create a new session leader in that case, and run
1062 // as part of the parent session. Otherwise, the new session cannot claim the
1063 // terminal as a controlling terminal (it is already claimed), meaning that it
1064 // will not see control signals from ^C etc.
1067 // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
1068 signal(SIGTSTP, SIG_IGN);
1070 // Become session leader
1072 ioctl(0, TIOCSCTTY, 0);
1075 tcsetpgrp(0, getpgrp());
1078 sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
1080 execvp(args[0], const_cast<char **>(args));
1082 // If we got here, the exec failed:
1084 int exec_status = errno;
1085 write(wpipefd, &exec_status, sizeof(int));
1089 // Mark this and all dependent services as force-stopped.
1090 void service_record::forceStop() noexcept
1092 if (service_state != service_state_t::STOPPED) {
1094 services->addToStopQueue(this);
1098 void service_record::dependent_stopped() noexcept
1100 if (service_state == service_state_t::STOPPING && waiting_for_deps) {
1101 services->addToStopQueue(this);
1105 void service_record::stop(bool bring_down) noexcept
1107 if (start_explicit) {
1108 start_explicit = false;
1117 void service_record::do_stop() noexcept
1119 if (pinned_started) return;
1121 if (start_explicit && ! do_auto_restart()) {
1122 start_explicit = false;
1124 if (required_by == 0) return; // release will re-call us anyway
1127 if (service_state != service_state_t::STARTED) {
1128 if (service_state == service_state_t::STARTING) {
1129 if (! can_interrupt_start()) {
1130 // Well this is awkward: we're going to have to continue
1131 // starting, but we don't want any dependents to think that
1132 // they are still waiting to start.
1133 // Make sure they remain stopped:
1138 // We must have had desired_state == STARTED.
1139 notify_listeners(service_event::STARTCANCELLED);
1143 // Reaching this point, we are starting interruptibly - so we
1144 // stop now (by falling through to below).
1147 // If we're starting we need to wait for that to complete.
1148 // If we're already stopping/stopped there's nothing to do.
1153 service_state = service_state_t::STOPPING;
1154 waiting_for_deps = true;
1155 if (stop_dependents()) {
1156 services->addToStopQueue(this);
1160 bool service_record::stop_check_dependents() noexcept
1162 bool all_deps_stopped = true;
1163 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1164 if (! (*i)->is_stopped()) {
1165 all_deps_stopped = false;
1170 return all_deps_stopped;
1173 bool service_record::stop_dependents() noexcept
1175 bool all_deps_stopped = true;
1176 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1177 if (! (*i)->is_stopped()) {
1178 // Note we check *first* since if the dependent service is not stopped,
1179 // 1. We will issue a stop to it shortly and
1180 // 2. It will notify us when stopped, at which point the stop_check_dependents()
1181 // check is run anyway.
1182 all_deps_stopped = false;
1186 // If this service is to be forcefully stopped, dependents must also be.
1190 (*i)->prop_stop = true;
1191 services->addToPropQueue(*i);
1194 return all_deps_stopped;
1197 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1198 void service_record::all_deps_stopped() noexcept
1200 waiting_for_deps = false;
1204 void base_process_service::all_deps_stopped() noexcept
1206 waiting_for_deps = false;
1208 // The process is still kicking on - must actually kill it. We signal the process
1209 // group (-pid) rather than just the process as there's less risk then of creating
1210 // an orphaned process group:
1211 if (! onstart_flags.no_sigterm) {
1212 kill(-pid, SIGTERM);
1214 if (term_signal != -1) {
1215 kill(-pid, term_signal);
1218 // In most cases, the rest is done in handle_exit_status.
1219 // If we are a BGPROCESS and the process is not our immediate child, however, that
1220 // won't work - check for this now:
1221 if (record_type == service_type::BGPROCESS && ! tracking_child) {
1226 // The process is already dead.
1231 void scripted_service::all_deps_stopped() noexcept
1233 waiting_for_deps = false;
1234 if (stop_command.length() == 0) {
1237 else if (! start_ps_process(stop_arg_parts, false)) {
1238 // Couldn't execute stop script, but there's not much we can do:
1243 void service_record::unpin() noexcept
1245 if (pinned_started) {
1246 pinned_started = false;
1247 if (desired_state == service_state_t::STOPPED) {
1249 services->process_queues();
1252 if (pinned_stopped) {
1253 pinned_stopped = false;
1254 if (desired_state == service_state_t::STARTED) {
1256 services->process_queues();
1261 void service_record::queue_for_console() noexcept
1263 services->append_console_queue(this);
1266 void service_record::release_console() noexcept
1268 services->pull_console_queue();
1271 void service_record::interrupt_start() noexcept
1273 services->unqueue_console(this);
1276 void service_set::service_active(service_record *sr) noexcept
1281 void service_set::service_inactive(service_record *sr) noexcept
1286 base_process_service::base_process_service(service_set *sset, string name, service_type service_type_p, string &&command,
1287 std::list<std::pair<unsigned,unsigned>> &command_offsets,
1288 sr_list &&pdepends_on, const sr_list &pdepends_soft)
1289 : service_record(sset, name, service_type_p, std::move(command), command_offsets,
1290 std::move(pdepends_on), pdepends_soft), child_listener(this), child_status_listener(this)
1292 restart_interval_count = 0;
1293 restart_interval_time = {0, 0};
1294 restart_timer.service = this;
1295 restart_timer.add_timer(eventLoop);
1297 // By default, allow a maximum of 3 restarts within 10.0 seconds:
1298 restart_interval.tv_sec = 10;
1299 restart_interval.tv_nsec = 0;
1300 max_restart_interval_count = 3;
1302 waiting_restart_timer = false;
1303 reserved_child_watch = false;
1304 tracking_child = false;
1307 void base_process_service::do_restart() noexcept
1310 waiting_restart_timer = false;
1311 restart_interval_count++;
1313 // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1314 // the process should be granted access to the console:
1315 bool on_console = service_state == service_state_t::STARTING
1316 ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1318 if (! start_ps_process(exec_arg_parts, on_console)) {
1319 if (service_state == service_state_t::STARTING) {
1323 desired_state = service_state_t::STOPPED;
1326 services->process_queues();
1330 bool base_process_service::restart_ps_process() noexcept
1332 using time_val = eventloop_t::time_val;
1334 time_val current_time;
1335 eventLoop.get_time(current_time, clock_type::MONOTONIC);
1337 if (max_restart_interval_count != 0) {
1338 // Check whether we're still in the most recent restart check interval:
1339 time_val int_diff = current_time - restart_interval_time;
1340 if (int_diff < restart_interval) {
1341 if (restart_interval_count >= max_restart_interval_count) {
1342 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1347 restart_interval_time = current_time;
1348 restart_interval_count = 0;
1352 // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1353 time_val tdiff = current_time - last_start_time;
1354 if (restart_delay <= tdiff) {
1355 // > restart delay (normally 200ms)
1359 time_val timeout = restart_delay - tdiff;
1360 restart_timer.arm_timer_rel(eventLoop, timeout);
1361 waiting_restart_timer = true;
1366 void base_process_service::interrupt_start() noexcept
1368 // overridden in subclasses
1369 if (waiting_restart_timer) {
1370 restart_timer.stop_timer(eventLoop);
1371 waiting_restart_timer = false;
1373 service_record::interrupt_start();
1376 dasynq::rearm process_restart_timer::timer_expiry(eventloop_t &, int expiry_count)
1378 service->do_restart();
1379 return dasynq::rearm::DISARM;