10 #include <sys/ioctl.h>
12 #include <sys/socket.h>
18 #include "dinit-log.h"
21 * service.cc - Service management.
22 * See service.h for details.
26 void open_control_socket(bool report_ro_failure = true) noexcept;
27 void setup_external_log() noexcept;
28 extern EventLoop_t eventLoop;
30 // Find the requested service by name
31 static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
32 const char *name) noexcept
35 list<ServiceRecord *>::const_iterator i = records.begin();
36 for ( ; i != records.end(); i++ ) {
37 if (strcmp((*i)->getServiceName(), name) == 0) {
41 return (ServiceRecord *)0;
44 ServiceRecord * ServiceSet::findService(const std::string &name) noexcept
46 return ::findService(records, name.c_str());
49 void ServiceSet::startService(const char *name)
52 ServiceRecord *record = loadServiceRecord(name);
58 void ServiceSet::stopService(const std::string & name) noexcept
60 ServiceRecord *record = findService(name);
61 if (record != nullptr) {
67 // Called when a service has actually stopped.
68 void ServiceRecord::stopped() noexcept
70 if (service_type != ServiceType::SCRIPTED && service_type != ServiceType::BGPROCESS && onstart_flags.runs_on_console) {
71 tcsetpgrp(0, getpgrp());
72 discard_console_log_buffer();
76 service_state = ServiceState::STOPPED;
79 logServiceStopped(service_name);
80 notifyListeners(ServiceEvent::STOPPED);
82 bool will_restart = (desired_state == ServiceState::STARTED) && service_set->get_auto_restart();
83 for (auto dependency : depends_on) {
84 if (! will_restart || ! dependency->can_interrupt_stop()) {
85 dependency->dependentStopped();
90 // Desired state is "started".
91 service_set->addToStartQueue(this);
94 if (socket_fd != -1) {
99 if (required_by == 0) {
100 // Service is now completely inactive.
101 release_dependencies();
106 dasynq::Rearm ServiceChildWatcher::childStatus(EventLoop_t &loop, pid_t child, int status) noexcept
108 ServiceRecord *sr = service;
111 sr->exit_status = status;
113 // Ok, for a process service, any process death which we didn't rig
114 // ourselves is a bit... unexpected. Probably, the child died because
115 // we asked it to (sr->service_state == STOPPING). But even if
116 // we didn't, there's not much we can do.
118 if (sr->waiting_for_execstat) {
119 // We still don't have an exec() status from the forked child, wait for that
120 // before doing any further processing.
121 return Rearm::REMOVE;
124 // Must deregister now since handle_exit_status might result in re-launch:
125 deregister(loop, child);
127 sr->handle_exit_status();
128 return Rearm::REMOVED;
131 bool ServiceRecord::do_auto_restart() noexcept
134 return service_set->get_auto_restart();
139 void ServiceRecord::handle_exit_status() noexcept
141 bool did_exit = WIFEXITED(exit_status);
142 bool was_signalled = WIFSIGNALED(exit_status);
144 if (service_type != ServiceType::SCRIPTED && exit_status != 0 && service_state != ServiceState::STOPPING) {
146 log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
148 else if (was_signalled) {
149 log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
153 if (doing_recovery) {
155 doing_recovery = false;
156 bool need_stop = false;
157 if (exit_status != 0) {
161 // We need to re-read the PID, since it has now changed.
162 if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
163 if (! read_pid_file()) {
170 // Failed startup: no auto-restart.
171 desired_state = ServiceState::STOPPED;
173 service_set->processQueues(false);
179 if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
180 if (service_state == ServiceState::STARTING) {
181 // (only applies to BGPROCESS)
182 if (exit_status == 0) {
189 else if (service_state == ServiceState::STOPPING) {
190 // TODO log non-zero rstatus?
193 else if (smooth_recovery && service_state == ServiceState::STARTED) {
194 // TODO ensure a minimum time between restarts
195 // TODO if we are pinned-started then we should probably check
196 // that dependencies have started before trying to re-start the
198 doing_recovery = (service_type == ServiceType::BGPROCESS);
203 if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
206 service_set->processQueues(false);
209 if (service_state == ServiceState::STOPPING) {
210 if (exit_status == 0) {
214 // ??? failed to stop! Let's log it as info:
216 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
218 else if (was_signalled) {
219 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
221 // Just assume that we stopped, so that any dependencies
225 service_set->processQueues(false);
228 if (exit_status == 0) {
234 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
236 else if (was_signalled) {
237 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
241 service_set->processQueues(true);
246 Rearm ServiceIoWatcher::fdEvent(EventLoop_t &loop, int fd, int flags) noexcept
248 ServiceRecord::process_child_status(&loop, this, flags);
249 return Rearm::REMOVED;
252 // TODO remove unused revents param
253 void ServiceRecord::process_child_status(EventLoop_t *loop, ServiceIoWatcher * stat_io, int revents) noexcept
255 ServiceRecord *sr = stat_io->service;
256 sr->waiting_for_execstat = false;
259 int r = read(stat_io->fd, &exec_status, sizeof(int));
261 stat_io->deregister(*loop);
264 // We read an errno code; exec() failed, and the service startup failed.
266 log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
267 if (sr->service_state == ServiceState::STARTING) {
268 sr->failed_to_start();
270 else if (sr->service_state == ServiceState::STOPPING) {
271 // Must be a scripted service. We've logged the failure, but it's probably better
272 // not to leave the service in STARTED state:
278 if (sr->service_type == ServiceType::PROCESS) {
279 if (sr->service_state != ServiceState::STARTED) {
285 // Somehow the process managed to complete before we even saw the status.
286 sr->handle_exit_status();
291 void ServiceRecord::require() noexcept
293 if (required_by++ == 0) {
294 // Need to require all our dependencies
295 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
299 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
300 ServiceRecord * to = i->getTo();
304 if (service_state == ServiceState::STOPPED) {
305 // (In any other state, the service is already considered active.)
306 service_set->service_active(this);
311 void ServiceRecord::release() noexcept
313 if (--required_by == 0) {
314 desired_state = ServiceState::STOPPED;
315 // Can stop, and release dependencies once we're stopped.
316 if (service_state == ServiceState::STOPPED) {
317 release_dependencies();
320 service_set->addToStopQueue(this);
325 void ServiceRecord::release_dependencies() noexcept
327 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
331 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
332 ServiceRecord * to = i->getTo();
336 service_set->service_inactive(this);
339 void ServiceRecord::start(bool activate) noexcept
341 if (activate && ! start_explicit) {
343 start_explicit = true;
346 if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
348 if (required_by == 0) {
349 // It really doesn't make any sense to start if there is no dependent or explicit activation.
353 desired_state = ServiceState::STARTED;
354 service_set->addToStartQueue(this);
357 void ServiceRecord::do_start() noexcept
359 if (pinned_stopped) return;
361 if (service_state != ServiceState::STOPPED) {
362 // We're already starting/started, or we are stopping and need to wait for
363 // that the complete.
364 if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
367 // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
368 // but if so they are waiting (for us), so they too can be instantly returned to
370 notifyListeners(ServiceEvent::STOPCANCELLED);
373 service_state = ServiceState::STARTING;
375 waiting_for_deps = true;
377 // Ask dependencies to start, mark them as being waited on.
378 if (! startCheckDependencies(true)) {
382 // Actually start this service.
386 void ServiceRecord::dependencyStarted() noexcept
388 if (service_state != ServiceState::STARTING || ! waiting_for_deps) {
392 if (startCheckDependencies(false)) {
397 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
399 bool all_deps_started = true;
401 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
402 if ((*i)->service_state != ServiceState::STARTED) {
404 all_deps_started = false;
413 for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
414 ServiceRecord * to = i->getTo();
416 if (to->service_state != ServiceState::STARTED) {
418 i->waiting_on = true;
419 all_deps_started = false;
422 i->waiting_on = false;
425 else if (i->waiting_on) {
426 if (to->service_state != ServiceState::STARTING) {
427 // Service has either started or is no longer starting
428 i->waiting_on = false;
431 // We are still waiting on this service
437 return all_deps_started;
440 bool ServiceRecord::open_socket() noexcept
442 if (socket_path.empty() || socket_fd != -1) {
443 // No socket, or already open
447 const char * saddrname = socket_path.c_str();
448 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
450 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
451 if (name == nullptr) {
452 log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
456 // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
459 name->sun_family = AF_UNIX;
460 strcpy(name->sun_path, saddrname);
462 int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
464 log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
469 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
470 log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
478 // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
479 // use chown and chmod instead.
480 if (chown(saddrname, socket_uid, socket_gid)) {
481 log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
486 if (chmod(saddrname, socket_perms) == -1) {
487 log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
492 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
493 log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
502 void ServiceRecord::allDepsStarted(bool has_console) noexcept
504 if (onstart_flags.runs_on_console && ! has_console) {
505 waiting_for_deps = true;
510 waiting_for_deps = false;
512 if (! open_socket()) {
516 if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS
517 || service_type == ServiceType::SCRIPTED) {
518 bool start_success = start_ps_process();
519 if (! start_success) {
524 // "internal" service
529 void ServiceRecord::acquiredConsole() noexcept
531 if (service_state != ServiceState::STARTING) {
532 // We got the console but no longer want it.
535 else if (startCheckDependencies(false)) {
536 allDepsStarted(true);
539 // We got the console but can't use it yet.
544 bool ServiceRecord::read_pid_file() noexcept
546 const char *pid_file_c = pid_file.c_str();
547 int fd = open(pid_file_c, O_CLOEXEC);
549 char pidbuf[21]; // just enought to hold any 64-bit integer
550 int r = read(fd, pidbuf, 20);
552 pidbuf[r] = 0; // store nul terminator
553 pid = std::atoi(pidbuf);
554 if (kill(pid, 0) == 0) {
555 child_listener.addWatch(eventLoop, pid);
558 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
568 log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
573 void ServiceRecord::started() noexcept
575 if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
576 tcsetpgrp(0, getpgrp());
580 if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
581 if (! read_pid_file()) {
587 logServiceStarted(service_name);
588 service_state = ServiceState::STARTED;
589 notifyListeners(ServiceEvent::STARTED);
591 if (onstart_flags.rw_ready) {
592 open_control_socket();
594 if (onstart_flags.log_ready) {
595 setup_external_log();
598 if (force_stop || desired_state == ServiceState::STOPPED) {
600 service_set->addToStopQueue(this);
604 // Notify any dependents whose desired state is STARTED:
605 for (auto i = dependents.begin(); i != dependents.end(); i++) {
606 (*i)->dependencyStarted();
608 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
609 (*i)->getFrom()->dependencyStarted();
613 void ServiceRecord::failed_to_start(bool depfailed) noexcept
615 if (!depfailed && onstart_flags.runs_on_console) {
616 tcsetpgrp(0, getpgrp());
620 logServiceFailed(service_name);
621 service_state = ServiceState::STOPPED;
622 if (start_explicit) {
623 start_explicit = false;
626 notifyListeners(ServiceEvent::FAILEDSTART);
628 // Cancel start of dependents:
629 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
630 if ((*i)->service_state == ServiceState::STARTING) {
631 (*i)->failed_to_start(true);
634 for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
635 // We can send 'start', because this is only a soft dependency.
636 // Our startup failure means that they don't have to wait for us.
637 (*i)->getFrom()->dependencyStarted();
641 bool ServiceRecord::start_ps_process() noexcept
643 return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
646 bool ServiceRecord::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
648 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
649 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
650 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
651 // is written to the pipe, and the parent can read it.
654 if (pipe2(pipefd, O_CLOEXEC)) {
659 // Set up the argument array and other data now (before fork), in case memory allocation fails.
661 auto args = cmd.data();
663 const char * logfile = this->logfile.c_str();
665 logfile = "/dev/null";
668 // TODO make sure pipefd's are not 0/1/2 (STDIN/OUT/ERR) - if they are, dup them
669 // until they are not.
673 bool child_status_registered = false;
675 child_status_listener.addWatch(eventLoop, pipefd[0], IN_EVENTS);
676 child_status_registered = true;
678 forkpid = child_listener.fork(eventLoop);
681 if (child_status_registered) {
682 child_status_listener.deregister(eventLoop);
689 // If the console already has a session leader, presumably it is us. On the other hand
690 // if it has no session leader, and we don't create one, then control inputs such as
691 // ^C will have no effect.
692 bool do_set_ctty = (tcgetsid(0) == -1);
695 // Child process. Must not allocate memory (or otherwise risk throwing any exception)
696 // from here until exit().
697 // TODO: we may need an equivalent for the following:
698 // ev_default_destroy(); // won't need that on this side, free up fds.
700 // Unmask signals that we masked on startup:
701 sigset_t sigwait_set;
702 sigemptyset(&sigwait_set);
703 sigaddset(&sigwait_set, SIGCHLD);
704 sigaddset(&sigwait_set, SIGINT);
705 sigaddset(&sigwait_set, SIGTERM);
706 sigprocmask(SIG_UNBLOCK, &sigwait_set, NULL);
708 constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
709 // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
710 // on the maxiumum number of bytes required for LISTEN=xxx, including nul terminator,
711 // where xxx is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
714 if (socket_fd != -1) {
716 if (socket_fd != 3) {
720 if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
722 snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
724 if (putenv(nbuf)) goto failure_out;
728 // Re-set stdin, stdout, stderr
729 close(0); close(1); close(2);
731 // TODO rethink this logic. If we open it at not-0, shouldn't we just dup it to 0?:
732 if (open("/dev/null", O_RDONLY) == 0) {
733 // stdin = 0. That's what we should have; proceed with opening
734 // stdout and stderr.
735 open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
740 // "run on console" - run as a foreground job on the terminal/console device
743 ioctl(0, TIOCSCTTY, 0);
746 tcsetpgrp(0, getpgrp());
748 // TODO disable suspend (^Z)? (via tcsetattr)
749 // (should be done before TIOCSCTTY)
752 execvp(exec_arg_parts[0], const_cast<char **>(args));
754 // If we got here, the exec failed:
756 int exec_status = errno;
757 write(pipefd[1], &exec_status, sizeof(int));
762 close(pipefd[1]); // close the 'other end' fd
765 waiting_for_execstat = true;
770 // Mark this and all dependent services as force-stopped.
771 void ServiceRecord::forceStop() noexcept
773 if (service_state != ServiceState::STOPPED) {
775 service_set->addToStopQueue(this);
779 void ServiceRecord::dependentStopped() noexcept
781 if (service_state == ServiceState::STOPPING && waiting_for_deps) {
782 // Check the other dependents before we stop.
783 if (stopCheckDependents()) {
789 void ServiceRecord::stop(bool bring_down) noexcept
791 if (start_explicit) {
792 start_explicit = false;
796 if (bring_down && desired_state != ServiceState::STOPPED) {
797 desired_state = ServiceState::STOPPED;
798 service_set->addToStopQueue(this);
802 void ServiceRecord::do_stop() noexcept
804 if (pinned_started) return;
806 if (service_state != ServiceState::STARTED) {
807 if (service_state == ServiceState::STARTING) {
808 if (! can_interrupt_start()) {
809 // Well this is awkward: we're going to have to continue
810 // starting, but we don't want any dependents to think that
811 // they are still waiting to start.
812 // Make sure they remain stopped:
817 // We must have had desired_state == STARTED.
818 notifyListeners(ServiceEvent::STARTCANCELLED);
820 // Reaching this point, we have can_interrupt_start() == true. So,
821 // we can stop. Dependents might be starting, but they must be
822 // waiting on us, so they should also be immediately stoppable.
823 // Fall through to below,.
826 // If we're starting we need to wait for that to complete.
827 // If we're already stopping/stopped there's nothing to do.
832 service_state = ServiceState::STOPPING;
833 waiting_for_deps = true;
835 // If we get here, we are in STARTED state; stop all dependents.
836 if (stopDependents()) {
841 bool ServiceRecord::stopCheckDependents() noexcept
843 bool all_deps_stopped = true;
844 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
845 if (! (*i)->is_stopped()) {
846 all_deps_stopped = false;
851 return all_deps_stopped;
854 bool ServiceRecord::stopDependents() noexcept
856 bool all_deps_stopped = true;
857 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
858 if (! (*i)->is_stopped()) {
859 // Note we check *first* since if the dependent service is not stopped,
860 // 1. We will issue a stop to it shortly and
861 // 2. It will notify us when stopped, at which point the stopCheckDependents()
862 // check is run anyway.
863 all_deps_stopped = false;
869 service_set->addToStopQueue(*i);
873 return all_deps_stopped;
876 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
877 void ServiceRecord::allDepsStopped()
879 waiting_for_deps = false;
880 if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
882 // The process is still kicking on - must actually kill it.
883 if (! onstart_flags.no_sigterm) {
886 if (term_signal != -1) {
887 kill(pid, term_signal);
890 // In most cases, the rest is done in process_child_callback.
891 // If we are a BGPROCESS and the process is not our immediate child, however, that
892 // won't work - check for this now:
893 if (service_type == ServiceType::BGPROCESS) {
895 pid_t r = waitpid(pid, &status, WNOHANG);
896 if (r == -1 && errno == ECHILD) {
897 // We can't track this child (or it's terminated already)
901 // TODO, examine status and log anything unusual.
907 // The process is already dead.
911 else if (service_type == ServiceType::SCRIPTED) {
913 if (stop_command.length() == 0) {
916 else if (! start_ps_process(stop_arg_parts, false)) {
917 // Couldn't execute stop script, but there's not much we can do:
926 void ServiceRecord::unpin() noexcept
928 if (pinned_started) {
929 pinned_started = false;
930 if (desired_state == ServiceState::STOPPED) {
932 service_set->processQueues(false);
935 if (pinned_stopped) {
936 pinned_stopped = false;
937 if (desired_state == ServiceState::STARTED) {
939 service_set->processQueues(true);
944 void ServiceRecord::queueForConsole() noexcept
946 service_set->consoleQueueTail(this);
949 void ServiceRecord::releaseConsole() noexcept
951 service_set->pullConsoleQueue();
954 void ServiceSet::service_active(ServiceRecord *sr) noexcept
959 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept