Log correct information regarding reason for process termination:
[oweals/dinit.git] / src / service.cc
1 #include <cstring>
2 #include <cerrno>
3 #include <sstream>
4 #include <iterator>
5 #include <memory>
6 #include <cstddef>
7
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <sys/ioctl.h>
11 #include <sys/un.h>
12 #include <sys/socket.h>
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <termios.h>
16
17 #include "service.h"
18 #include "dinit-log.h"
19
20 /*
21  * service.cc - Service management.
22  * See service.h for details.
23  */
24
25 // from dinit.cc:
26 void open_control_socket(bool report_ro_failure = true) noexcept;
27 void setup_external_log() noexcept;
28 extern EventLoop_t eventLoop;
29
30 // Find the requested service by name
31 static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
32                                     const char *name) noexcept
33 {
34     using std::list;
35     list<ServiceRecord *>::const_iterator i = records.begin();
36     for ( ; i != records.end(); i++ ) {
37         if (strcmp((*i)->getServiceName(), name) == 0) {
38             return *i;
39         }
40     }
41     return (ServiceRecord *)0;
42 }
43
44 ServiceRecord * ServiceSet::findService(const std::string &name) noexcept
45 {
46     return ::findService(records, name.c_str());
47 }
48
49 void ServiceSet::startService(const char *name)
50 {
51     using namespace std;
52     ServiceRecord *record = loadServiceRecord(name);
53     
54     record->start();
55     processQueues(true);
56 }
57
58 void ServiceSet::stopService(const std::string & name) noexcept
59 {
60     ServiceRecord *record = findService(name);
61     if (record != nullptr) {
62         record->stop();
63         processQueues(false);
64     }
65 }
66
67 // Called when a service has actually stopped.
68 void ServiceRecord::stopped() noexcept
69 {
70     if (service_type != ServiceType::SCRIPTED && service_type != ServiceType::BGPROCESS && onstart_flags.runs_on_console) {
71         tcsetpgrp(0, getpgrp());
72         discard_console_log_buffer();
73         releaseConsole();
74     }
75
76     service_state = ServiceState::STOPPED;
77     force_stop = false;
78     
79     logServiceStopped(service_name);
80     notifyListeners(ServiceEvent::STOPPED);
81     
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();
86         }
87     }
88     
89     if (will_restart) {
90         // Desired state is "started".
91         service_set->addToStartQueue(this);
92     }
93     else {
94         if (socket_fd != -1) {
95             close(socket_fd);
96             socket_fd = -1;
97         }
98         
99         if (required_by == 0) {
100             // Service is now completely inactive.
101             release_dependencies();
102         }
103     }
104 }
105
106 dasynq::Rearm ServiceChildWatcher::childStatus(EventLoop_t &loop, pid_t child, int status) noexcept
107 {
108     ServiceRecord *sr = service;
109     
110     sr->pid = -1;
111     sr->exit_status = status;
112     
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.
117     
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;
122     }
123     
124     // Must deregister now since handle_exit_status might result in re-launch:
125     deregister(loop, child);
126     
127     sr->handle_exit_status();
128     return Rearm::REMOVED;
129 }
130
131 bool ServiceRecord::do_auto_restart() noexcept
132 {
133     if (auto_restart) {
134         return service_set->get_auto_restart();
135     }
136     return false;
137 }
138
139 void ServiceRecord::handle_exit_status() noexcept
140 {
141     bool did_exit = WIFEXITED(exit_status);
142     bool was_signalled = WIFSIGNALED(exit_status);
143
144     if (service_type != ServiceType::SCRIPTED && exit_status != 0 && service_state != ServiceState::STOPPING) {
145         if (did_exit) {
146             log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
147         }
148         else if (was_signalled) {
149             log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
150         }
151     }
152
153     if (doing_recovery) {
154         // (BGPROCESS only)
155         doing_recovery = false;
156         bool need_stop = false;
157         if (exit_status != 0) {
158             need_stop = true;
159         }
160         else {
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()) {
164                     need_stop = true;
165                 }
166             }
167         }
168         
169         if (need_stop) {
170             // Failed startup: no auto-restart.
171             desired_state = ServiceState::STOPPED;
172             forceStop();
173             service_set->processQueues(false);
174         }
175         
176         return;
177     }
178     
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) {
183                 started();
184             }
185             else {
186                 failed_to_start();
187             }
188         }
189         else if (service_state == ServiceState::STOPPING) {
190             // TODO log non-zero rstatus?
191             stopped();
192         }
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
197             //      service process.
198             doing_recovery = (service_type == ServiceType::BGPROCESS);
199             start_ps_process();
200             return;
201         }
202         else {
203             if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
204             forceStop();
205         }
206         service_set->processQueues(false);
207     }
208     else {  // SCRIPTED
209         if (service_state == ServiceState::STOPPING) {
210             if (exit_status == 0) {
211                 stopped();
212             }
213             else {
214                 // ??? failed to stop! Let's log it as info:
215                 if (did_exit) {
216                     log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
217                 }
218                 else if (was_signalled) {
219                     log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
220                 }
221                 // Just assume that we stopped, so that any dependencies
222                 // can be stopped:
223                 stopped();
224             }
225             service_set->processQueues(false);
226         }
227         else { // STARTING
228             if (exit_status == 0) {
229                 started();
230             }
231             else {
232                 // failed to start
233                 if (did_exit) {
234                     log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
235                 }
236                 else if (was_signalled) {
237                     log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
238                 }
239                 failed_to_start();
240             }
241             service_set->processQueues(true);
242         }
243     }
244 }
245
246 Rearm ServiceIoWatcher::fdEvent(EventLoop_t &loop, int fd, int flags) noexcept
247 {
248     ServiceRecord::process_child_status(&loop, this, flags);
249     return Rearm::REMOVED;
250 }
251
252 // TODO remove unused revents param
253 void ServiceRecord::process_child_status(EventLoop_t *loop, ServiceIoWatcher * stat_io, int revents) noexcept
254 {
255     ServiceRecord *sr = stat_io->service;
256     sr->waiting_for_execstat = false;
257     
258     int exec_status;
259     int r = read(stat_io->fd, &exec_status, sizeof(int));
260     close(stat_io->fd);
261     stat_io->deregister(*loop);
262     
263     if (r > 0) {
264         // We read an errno code; exec() failed, and the service startup failed.
265         sr->pid = -1;
266         log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
267         if (sr->service_state == ServiceState::STARTING) {
268             sr->failed_to_start();
269         }
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:
273             sr->stopped();
274         }
275     }
276     else {
277         // exec() succeeded.
278         if (sr->service_type == ServiceType::PROCESS) {
279             if (sr->service_state != ServiceState::STARTED) {
280                 sr->started();
281             }
282         }
283         
284         if (sr->pid == -1) {
285             // Somehow the process managed to complete before we even saw the status.
286             sr->handle_exit_status();
287         }
288     }
289 }
290
291 void ServiceRecord::require() noexcept
292 {
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) {
296             (*i)->require();
297         }
298
299         for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
300             ServiceRecord * to = i->getTo();
301             to->require();
302         }
303         
304         if (service_state == ServiceState::STOPPED) {
305             // (In any other state, the service is already considered active.)
306             service_set->service_active(this);
307         }
308     }
309 }
310
311 void ServiceRecord::release() noexcept
312 {
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();
318         }
319         else {
320             service_set->addToStopQueue(this);
321         }
322     }
323 }
324
325 void ServiceRecord::release_dependencies() noexcept
326 {
327     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
328         (*i)->release();
329     }
330
331     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
332         ServiceRecord * to = i->getTo();
333         to->release();
334     }
335     
336     service_set->service_inactive(this);
337 }
338
339 void ServiceRecord::start(bool activate) noexcept
340 {
341     if (activate && ! start_explicit) {
342         require();
343         start_explicit = true;
344     }
345     
346     if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
347     
348     if (required_by == 0) {
349         // It really doesn't make any sense to start if there is no dependent or explicit activation.
350         return;
351     }
352
353     desired_state = ServiceState::STARTED;
354     service_set->addToStartQueue(this);
355 }
356
357 void ServiceRecord::do_start() noexcept
358 {
359     if (pinned_stopped) return;
360     
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()) {
365             return;
366         }
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
369         // STARTING state.
370         notifyListeners(ServiceEvent::STOPCANCELLED);
371     }
372     
373     service_state = ServiceState::STARTING;
374
375     waiting_for_deps = true;
376
377     // Ask dependencies to start, mark them as being waited on.
378     if (! startCheckDependencies(true)) {
379         return;
380     }
381
382     // Actually start this service.
383     allDepsStarted();
384 }
385
386 void ServiceRecord::dependencyStarted() noexcept
387 {
388     if (service_state != ServiceState::STARTING || ! waiting_for_deps) {
389         return;
390     }
391
392     if (startCheckDependencies(false)) {
393         allDepsStarted();
394     }
395 }
396
397 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
398 {
399     bool all_deps_started = true;
400
401     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
402         if ((*i)->service_state != ServiceState::STARTED) {
403             if (start_deps) {
404                 all_deps_started = false;
405                 (*i)->start(false);
406             }
407             else {
408                 return false;
409             }
410         }
411     }
412
413     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
414         ServiceRecord * to = i->getTo();
415         if (start_deps) {
416             if (to->service_state != ServiceState::STARTED) {
417                 to->start(false);
418                 i->waiting_on = true;
419                 all_deps_started = false;
420             }
421             else {
422                 i->waiting_on = false;
423             }
424         }
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;
429             }
430             else {
431                 // We are still waiting on this service
432                 return false;
433             }
434         }
435     }
436     
437     return all_deps_started;
438 }
439
440 bool ServiceRecord::open_socket() noexcept
441 {
442     if (socket_path.empty() || socket_fd != -1) {
443         // No socket, or already open
444         return true;
445     }
446     
447     const char * saddrname = socket_path.c_str();
448     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
449
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");
453         return false;
454     }
455     
456     // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
457     unlink(saddrname);
458
459     name->sun_family = AF_UNIX;
460     strcpy(name->sun_path, saddrname);
461
462     int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
463     if (sockfd == -1) {
464         log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
465         free(name);
466         return false;
467     }
468
469     if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
470         log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
471         close(sockfd);
472         free(name);
473         return false;
474     }
475     
476     free(name);
477     
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));
482         close(sockfd);
483         return false;
484     }
485     
486     if (chmod(saddrname, socket_perms) == -1) {
487         log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
488         close(sockfd);
489         return false;
490     }
491
492     if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
493         log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
494         close(sockfd);
495         return false;
496     }
497     
498     socket_fd = sockfd;
499     return true;
500 }
501
502 void ServiceRecord::allDepsStarted(bool has_console) noexcept
503 {
504     if (onstart_flags.runs_on_console && ! has_console) {
505         waiting_for_deps = true;
506         queueForConsole();
507         return;
508     }
509     
510     waiting_for_deps = false;
511
512     if (! open_socket()) {
513         failed_to_start();
514     }
515
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) {
520             failed_to_start();
521         }
522     }
523     else {
524         // "internal" service
525         started();
526     }
527 }
528
529 void ServiceRecord::acquiredConsole() noexcept
530 {
531     if (service_state != ServiceState::STARTING) {
532         // We got the console but no longer want it.
533         releaseConsole();
534     }
535     else if (startCheckDependencies(false)) {
536         allDepsStarted(true);
537     }
538     else {
539         // We got the console but can't use it yet.
540         releaseConsole();
541     }
542 }
543
544 bool ServiceRecord::read_pid_file() noexcept
545 {
546     const char *pid_file_c = pid_file.c_str();
547     int fd = open(pid_file_c, O_CLOEXEC);
548     if (fd != -1) {
549         char pidbuf[21]; // just enought to hold any 64-bit integer
550         int r = read(fd, pidbuf, 20);
551         if (r > 0) {
552             pidbuf[r] = 0; // store nul terminator
553             pid = std::atoi(pidbuf);
554             if (kill(pid, 0) == 0) {                
555                 child_listener.addWatch(eventLoop, pid);
556             }
557             else {
558                 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
559                 pid = -1;
560                 close(fd);
561                 return false;
562             }
563         }
564         close(fd);
565         return true;
566     }
567     else {
568         log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
569         return false;
570     }
571 }
572
573 void ServiceRecord::started() noexcept
574 {
575     if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
576         tcsetpgrp(0, getpgrp());
577         releaseConsole();
578     }
579     
580     if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
581         if (! read_pid_file()) {
582             failed_to_start();
583             return;
584         }
585     }
586     
587     logServiceStarted(service_name);
588     service_state = ServiceState::STARTED;
589     notifyListeners(ServiceEvent::STARTED);
590
591     if (onstart_flags.rw_ready) {
592         open_control_socket();
593     }
594     if (onstart_flags.log_ready) {
595         setup_external_log();
596     }
597
598     if (force_stop || desired_state == ServiceState::STOPPED) {
599         // We must now stop.
600         service_set->addToStopQueue(this);
601         return;
602     }
603
604     // Notify any dependents whose desired state is STARTED:
605     for (auto i = dependents.begin(); i != dependents.end(); i++) {
606         (*i)->dependencyStarted();
607     }
608     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
609         (*i)->getFrom()->dependencyStarted();
610     }
611 }
612
613 void ServiceRecord::failed_to_start(bool depfailed) noexcept
614 {
615     if (!depfailed && onstart_flags.runs_on_console) {
616         tcsetpgrp(0, getpgrp());
617         releaseConsole();
618     }
619     
620     logServiceFailed(service_name);
621     service_state = ServiceState::STOPPED;
622     if (start_explicit) {
623         start_explicit = false;
624         release();
625     }
626     notifyListeners(ServiceEvent::FAILEDSTART);
627     
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);
632         }
633     }    
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();
638     }
639 }
640
641 bool ServiceRecord::start_ps_process() noexcept
642 {
643     return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
644 }
645
646 bool ServiceRecord::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
647 {
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.
652
653     int pipefd[2];
654     if (pipe2(pipefd, O_CLOEXEC)) {
655         // TODO log error
656         return false;
657     }
658     
659     // Set up the argument array and other data now (before fork), in case memory allocation fails.
660     
661     auto args = cmd.data();
662     
663     const char * logfile = this->logfile.c_str();
664     if (*logfile == 0) {
665         logfile = "/dev/null";
666     }
667
668     // TODO make sure pipefd's are not 0/1/2 (STDIN/OUT/ERR) - if they are, dup them
669     // until they are not.
670     
671     pid_t forkpid;
672     
673     bool child_status_registered = false;    
674     try {
675         child_status_listener.addWatch(eventLoop, pipefd[0], IN_EVENTS);
676         child_status_registered = true;
677         
678         forkpid = child_listener.fork(eventLoop);
679     }
680     catch (...) {
681         if (child_status_registered) {
682             child_status_listener.deregister(eventLoop);
683         }
684         close(pipefd[0]);
685         close(pipefd[1]);
686         return false;
687     }
688
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);
693
694     if (forkpid == 0) {
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.
699
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);
707
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).
712         char nbuf[bufsz];
713
714         if (socket_fd != -1) {
715             dup2(socket_fd, 3);
716             if (socket_fd != 3) {
717                 close(socket_fd);
718             }
719             
720             if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
721             
722             snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
723             
724             if (putenv(nbuf)) goto failure_out;
725         }
726
727         if (! on_console) {
728             // Re-set stdin, stdout, stderr
729             close(0); close(1); close(2);
730
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);
736               dup2(1, 2);
737             }
738         }
739         else {
740             // "run on console" - run as a foreground job on the terminal/console device
741             if (do_set_ctty) {
742                 setsid();
743                 ioctl(0, TIOCSCTTY, 0);
744             }
745             setpgid(0,0);
746             tcsetpgrp(0, getpgrp());
747             
748             // TODO disable suspend (^Z)? (via tcsetattr)
749             //      (should be done before TIOCSCTTY)
750         }
751
752         execvp(exec_arg_parts[0], const_cast<char **>(args));
753
754         // If we got here, the exec failed:
755         failure_out:
756         int exec_status = errno;
757         write(pipefd[1], &exec_status, sizeof(int));
758         _exit(0);
759     }
760     else {
761         // Parent process
762         close(pipefd[1]); // close the 'other end' fd
763         pid = forkpid;
764
765         waiting_for_execstat = true;
766         return true;
767     }
768 }
769
770 // Mark this and all dependent services as force-stopped.
771 void ServiceRecord::forceStop() noexcept
772 {
773     if (service_state != ServiceState::STOPPED) {
774         force_stop = true;
775         service_set->addToStopQueue(this);
776     }
777 }
778
779 void ServiceRecord::dependentStopped() noexcept
780 {
781     if (service_state == ServiceState::STOPPING && waiting_for_deps) {
782         // Check the other dependents before we stop.
783         if (stopCheckDependents()) {
784             allDepsStopped();
785         }
786     }
787 }
788
789 void ServiceRecord::stop(bool bring_down) noexcept
790 {
791     if (start_explicit) {
792         start_explicit = false;
793         release();
794     }
795     
796     if (bring_down && desired_state != ServiceState::STOPPED) {
797         desired_state = ServiceState::STOPPED;
798         service_set->addToStopQueue(this);
799     }
800 }
801
802 void ServiceRecord::do_stop() noexcept
803 {
804     if (pinned_started) return;
805
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:
813                 stopDependents();
814                 return;
815             }
816
817             // We must have had desired_state == STARTED.
818             notifyListeners(ServiceEvent::STARTCANCELLED);
819             
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,.
824         }
825         else {
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.
828             return;
829         }
830     }
831     
832     service_state = ServiceState::STOPPING;
833     waiting_for_deps = true;
834     
835     // If we get here, we are in STARTED state; stop all dependents.
836     if (stopDependents()) {
837         allDepsStopped();
838     }
839 }
840
841 bool ServiceRecord::stopCheckDependents() noexcept
842 {
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;
847             break;
848         }
849     }
850     
851     return all_deps_stopped;
852 }
853
854 bool ServiceRecord::stopDependents() noexcept
855 {
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;
864         }
865         if (force_stop) {
866             (*i)->forceStop();
867         }
868         else {
869             service_set->addToStopQueue(*i);
870         }
871     }
872     
873     return all_deps_stopped;
874 }
875
876 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
877 void ServiceRecord::allDepsStopped()
878 {
879     waiting_for_deps = false;
880     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
881         if (pid != -1) {
882             // The process is still kicking on - must actually kill it.
883             if (! onstart_flags.no_sigterm) {
884                 kill(pid, SIGTERM);
885             }
886             if (term_signal != -1) {
887                 kill(pid, term_signal);
888             }
889             
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) {
894                 int status;
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)
898                     stopped();
899                 }
900                 else if (r == pid) {
901                     // TODO, examine status and log anything unusual.
902                     stopped();
903                 }
904             }
905         }
906         else {
907             // The process is already dead.
908             stopped();
909         }
910     }
911     else if (service_type == ServiceType::SCRIPTED) {
912         // Scripted service.
913         if (stop_command.length() == 0) {
914             stopped();
915         }
916         else if (! start_ps_process(stop_arg_parts, false)) {
917             // Couldn't execute stop script, but there's not much we can do:
918             stopped();
919         }
920     }
921     else {
922         stopped();
923     }
924 }
925
926 void ServiceRecord::unpin() noexcept
927 {
928     if (pinned_started) {
929         pinned_started = false;
930         if (desired_state == ServiceState::STOPPED) {
931             do_stop();
932             service_set->processQueues(false);
933         }
934     }
935     if (pinned_stopped) {
936         pinned_stopped = false;
937         if (desired_state == ServiceState::STARTED) {
938             do_start();
939             service_set->processQueues(true);
940         }
941     }
942 }
943
944 void ServiceRecord::queueForConsole() noexcept
945 {
946     service_set->consoleQueueTail(this);
947 }
948
949 void ServiceRecord::releaseConsole() noexcept
950 {
951     service_set->pullConsoleQueue();
952 }
953
954 void ServiceSet::service_active(ServiceRecord *sr) noexcept
955 {
956     active_services++;
957 }
958
959 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
960 {
961     active_services--;
962 }