Make "pinStart" and "start", and "pinStop" and "stop", separate
[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 // from dinit.cc:
21 void open_control_socket(struct ev_loop *loop) noexcept;
22
23
24 // Find the requested service by name
25 static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
26                                     const char *name) noexcept
27 {
28     using std::list;
29     list<ServiceRecord *>::const_iterator i = records.begin();
30     for ( ; i != records.end(); i++ ) {
31         if (strcmp((*i)->getServiceName(), name) == 0) {
32             return *i;
33         }
34     }
35     return (ServiceRecord *)0;
36 }
37
38 ServiceRecord * ServiceSet::findService(const std::string &name) noexcept
39 {
40     return ::findService(records, name.c_str());
41 }
42
43 void ServiceSet::startService(const char *name)
44 {
45     using namespace std;
46     ServiceRecord *record = loadServiceRecord(name);
47     
48     record->start();
49 }
50
51 void ServiceSet::stopService(const std::string & name) noexcept
52 {
53     ServiceRecord *record = findService(name);
54     if (record != nullptr) {
55         record->stop();
56     }
57 }
58
59 // Called when a service has actually stopped.
60 void ServiceRecord::stopped() noexcept
61 {
62     if (service_type != ServiceType::SCRIPTED && service_type != ServiceType::BGPROCESS && onstart_flags.runs_on_console) {
63         tcsetpgrp(0, getpgrp());
64         releaseConsole();
65     }
66
67     logServiceStopped(service_name);
68     service_state = ServiceState::STOPPED;
69     force_stop = false;
70     
71     notifyListeners(ServiceEvent::STOPPED);
72     
73     for (auto dependency : depends_on) {
74         dependency->dependentStopped();
75     }
76     
77     if (desired_state == ServiceState::STARTED && service_set->get_auto_restart()) {
78         // Desired state is "started".
79         do_start();
80     }
81     else {
82         if (socket_fd != -1) {
83             close(socket_fd);
84             socket_fd = -1;
85         }
86         
87         if (required_by == 0) {
88             // Service is now completely inactive.
89             release_dependencies();
90         }
91     }
92 }
93
94 void ServiceRecord::process_child_callback(struct ev_loop *loop, ev_child *w, int revents) noexcept
95 {
96     ServiceRecord *sr = (ServiceRecord *) w->data;
97
98     sr->pid = -1;
99     sr->exit_status = w->rstatus;
100     ev_child_stop(loop, w);
101     
102     // Ok, for a process service, any process death which we didn't rig
103     // ourselves is a bit... unexpected. Probably, the child died because
104     // we asked it to (sr->service_state == STOPPING). But even if
105     // we didn't, there's not much we can do.
106     
107     if (sr->waiting_for_execstat) {
108         // We still don't have an exec() status from the forked child, wait for that
109         // before doing any further processing.
110         return;
111     }
112     
113     sr->handle_exit_status();
114 }
115
116 bool ServiceRecord::do_auto_restart() noexcept
117 {
118     if (auto_restart) {
119         return service_set->get_auto_restart();
120     }
121     return false;
122 }
123
124 void ServiceRecord::handle_exit_status() noexcept
125 {
126     if (exit_status != 0 && service_state != ServiceState::STOPPING) {
127         log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", exit_status);
128     }
129
130     if (doing_recovery) {
131         // (BGPROCESS only)
132         doing_recovery = false;
133         bool need_stop = false;
134         if (exit_status != 0) {
135             need_stop = true;
136         }
137         else {
138             // We need to re-read the PID, since it has now changed.
139             if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
140                 if (! read_pid_file()) {
141                     need_stop = true;
142                 }
143             }
144         }
145         
146         if (need_stop) {
147             // Failed startup: no auto-restart.
148             desired_state = ServiceState::STOPPED;
149             do_stop();
150         }
151         
152         return;
153     }
154     
155     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
156         if (service_state == ServiceState::STARTING) {
157             // (only applies to BGPROCESS)
158             if (exit_status == 0) {
159                 started();
160             }
161             else {
162                 failed_to_start();
163             }
164         }
165         else if (service_state == ServiceState::STOPPING) {
166             // TODO log non-zero rstatus?
167             stopped();
168         }
169         else if (smooth_recovery && service_state == ServiceState::STARTED) {
170             // TODO ensure a minimum time between restarts
171             // TODO if we are pinned-started then we should probably check
172             //      that dependencies have started before trying to re-start the
173             //      service process.
174             doing_recovery = (service_type == ServiceType::BGPROCESS);
175             start_ps_process();
176             return;
177         }
178         else {
179             if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
180             forceStop();
181         }
182     }
183     else {  // SCRIPTED
184         if (service_state == ServiceState::STOPPING) {
185             if (exit_status == 0) {
186                 stopped();
187             }
188             else {
189                 // ??? failed to stop! Let's log it as info:
190                 log(LogLevel::INFO, "service ", service_name, " stop command failed with exit code ", exit_status);
191                 // Just assume that we stopped, so that any dependencies
192                 // can be stopped:
193                 stopped();
194             }
195         }
196         else { // STARTING
197             if (exit_status == 0) {
198                 started();
199             }
200             else {
201                 // failed to start
202                 log(LogLevel::ERROR, "service ", service_name, " command failed with exit code ", exit_status);
203                 failed_to_start();
204             }
205         }
206     }
207 }
208
209 void ServiceRecord::process_child_status(struct ev_loop *loop, ev_io * stat_io, int revents) noexcept
210 {
211     ServiceRecord *sr = (ServiceRecord *) stat_io->data;
212     sr->waiting_for_execstat = false;
213     
214     int exec_status;
215     int r = read(stat_io->fd, &exec_status, sizeof(int));
216     close(stat_io->fd);
217     ev_io_stop(loop, stat_io);
218     
219     if (r != 0) {
220         // We read an errno code; exec() failed, and the service startup failed.
221         sr->pid = -1;
222         log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
223         if (sr->service_state == ServiceState::STARTING) {
224             sr->failed_to_start();
225         }
226         else if (sr->service_state == ServiceState::STOPPING) {
227             // Must be a scripted servce. We've logged the failure, but it's probably better
228             // not to leave the service in STARTED state:
229             sr->stopped();
230         }
231     }
232     else {
233         // exec() succeeded.
234         if (sr->service_type == ServiceType::PROCESS) {
235             if (sr->service_state != ServiceState::STARTED) {
236                 sr->started();
237             }
238         }
239         
240         if (sr->pid == -1) {
241             // Somehow the process managed to complete before we even saw the status.
242             sr->handle_exit_status();
243         }
244     }
245 }
246
247 void ServiceRecord::require() noexcept
248 {
249     if (required_by++ == 0) {
250         // Need to require all our dependencies
251         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
252             (*i)->require();
253         }
254
255         for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
256             ServiceRecord * to = i->getTo();
257             to->require();
258         }
259         
260         if (service_state == ServiceState::STOPPED) {
261             // (In any other state, the service is already considered active.)
262             service_set->service_active(this);
263         }
264     }
265 }
266
267 void ServiceRecord::release() noexcept
268 {
269     if (--required_by == 0) {
270         desired_state = ServiceState::STOPPED;
271         // Can stop, and release dependencies once we're stopped.
272         if (service_state == ServiceState::STOPPED) {
273             release_dependencies();
274         }
275         else {
276             do_stop();
277         }
278     }
279 }
280
281 void ServiceRecord::release_dependencies() noexcept
282 {
283     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
284         (*i)->release();
285     }
286
287     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
288         ServiceRecord * to = i->getTo();
289         to->release();
290     }
291     
292     service_set->service_inactive(this);
293 }
294
295 void ServiceRecord::start(bool activate) noexcept
296 {
297     if (activate) {
298         if (!start_explicit) require();
299         start_explicit = true;
300     }
301     
302     if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
303     
304     if (required_by == 0) {
305         service_set->service_active(this);
306     }
307
308     desired_state = ServiceState::STARTED;
309     do_start();
310 }
311
312 void ServiceRecord::do_start() noexcept
313 {
314     if (pinned_stopped) return;
315     
316     if (service_state != ServiceState::STOPPED) {
317         // We're already starting/started, or we are stopping and need to wait for
318         // that the complete.
319         if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
320             return;
321         }
322         // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
323         // but if so they are waiting (for us), so they too can be instantly returned to
324         // STARTING state.
325         notifyListeners(ServiceEvent::STOPCANCELLED);
326     }
327     
328     service_state = ServiceState::STARTING;
329
330     waiting_for_deps = true;
331
332     // Ask dependencies to start, mark them as being waited on.
333     if (! startCheckDependencies(true)) {
334         return;
335     }
336
337     // Actually start this service.
338     allDepsStarted();
339 }
340
341 void ServiceRecord::dependencyStarted() noexcept
342 {
343     if (service_state != ServiceState::STARTING || ! waiting_for_deps) {
344         return;
345     }
346
347     if (startCheckDependencies(false)) {
348         allDepsStarted();
349     }
350 }
351
352 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
353 {
354     bool all_deps_started = true;
355
356     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
357         if ((*i)->service_state != ServiceState::STARTED) {
358             if (start_deps) {
359                 all_deps_started = false;
360                 (*i)->start(false);
361             }
362             else {
363                 return false;
364             }
365         }
366     }
367
368     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
369         ServiceRecord * to = i->getTo();
370         if (start_deps) {
371             if (to->service_state != ServiceState::STARTED) {
372                 to->start(false);
373                 i->waiting_on = true;
374                 all_deps_started = false;
375             }
376             else {
377                 i->waiting_on = false;
378             }
379         }
380         else if (i->waiting_on) {
381             if (to->service_state != ServiceState::STARTING) {
382                 // Service has either started or is no longer starting
383                 i->waiting_on = false;
384             }
385             else {
386                 // We are still waiting on this service
387                 return false;
388             }
389         }
390     }
391     
392     return all_deps_started;
393 }
394
395 bool ServiceRecord::open_socket() noexcept
396 {
397     if (socket_path.empty() || socket_fd != -1) {
398         // No socket, or already open
399         return true;
400     }
401     
402     const char * saddrname = socket_path.c_str();
403     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
404
405     struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
406     if (name == nullptr) {
407         log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
408         return false;
409     }
410     
411     // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
412     unlink(saddrname);
413
414     name->sun_family = AF_UNIX;
415     strcpy(name->sun_path, saddrname);
416
417     int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
418     if (sockfd == -1) {
419         log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
420         free(name);
421         return false;
422     }
423
424     if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
425         log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
426         close(sockfd);
427         free(name);
428         return false;
429     }
430     
431     free(name);
432     
433     // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
434     // use chown and chmod instead.
435     if (chown(saddrname, socket_uid, socket_gid)) {
436         log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
437         close(sockfd);
438         return false;
439     }
440     
441     if (chmod(saddrname, socket_perms) == -1) {
442         log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
443         close(sockfd);
444         return false;
445     }
446
447     if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
448         log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
449         close(sockfd);
450         return false;
451     }
452     
453     socket_fd = sockfd;
454     return true;
455 }
456
457 void ServiceRecord::allDepsStarted(bool has_console) noexcept
458 {
459     if (onstart_flags.runs_on_console && ! has_console) {
460         waiting_for_deps = true;
461         queueForConsole();
462         return;
463     }
464     
465     waiting_for_deps = false;
466
467     if (! open_socket()) {
468         failed_to_start();
469     }
470
471     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS
472             || service_type == ServiceType::SCRIPTED) {
473         bool start_success = start_ps_process();
474         if (! start_success) {
475             failed_to_start();
476         }
477     }
478     else {
479         // "internal" service
480         started();
481     }
482 }
483
484 void ServiceRecord::acquiredConsole() noexcept
485 {
486     if (service_state != ServiceState::STARTING) {
487         // We got the console but no longer want it.
488         releaseConsole();
489     }
490     else if (startCheckDependencies(false)) {
491         log_to_console = false;
492         allDepsStarted(true);
493     }
494     else {
495         // We got the console but can't use it yet.
496         releaseConsole();
497     }
498 }
499
500 bool ServiceRecord::read_pid_file() noexcept
501 {
502     const char *pid_file_c = pid_file.c_str();
503     int fd = open(pid_file_c, O_CLOEXEC);
504     if (fd != -1) {
505         char pidbuf[21]; // just enought to hold any 64-bit integer
506         int r = read(fd, pidbuf, 20);
507         if (r > 0) {
508             pidbuf[r] = 0; // store nul terminator
509             pid = std::atoi(pidbuf);
510             if (kill(pid, 0) == 0) {
511                 ev_child_init(&child_listener, process_child_callback, pid, 0);
512                 child_listener.data = this;
513                 ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
514             }
515             else {
516                 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
517                 pid = -1;
518                 close(fd);
519                 return false;
520             }
521         }
522         close(fd);
523         return true;
524     }
525     else {
526         log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
527         return false;
528     }
529 }
530
531 void ServiceRecord::started() noexcept
532 {
533     if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
534         tcsetpgrp(0, getpgrp());
535         releaseConsole();
536     }
537     
538     if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
539         if (! read_pid_file()) {
540             failed_to_start();
541             return;
542         }
543     }
544     
545     logServiceStarted(service_name);
546     service_state = ServiceState::STARTED;
547     notifyListeners(ServiceEvent::STARTED);
548
549     if (onstart_flags.rw_ready) {
550         open_control_socket(ev_default_loop(EVFLAG_AUTO));
551     }
552
553     if (force_stop || desired_state == ServiceState::STOPPED) {
554         // We must now stop.
555         do_stop();
556         return;
557     }
558
559     // Notify any dependents whose desired state is STARTED:
560     for (auto i = dependents.begin(); i != dependents.end(); i++) {
561         (*i)->dependencyStarted();
562     }
563     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
564         (*i)->getFrom()->dependencyStarted();
565     }
566 }
567
568 void ServiceRecord::failed_to_start(bool depfailed) noexcept
569 {
570     if (!depfailed && onstart_flags.runs_on_console) {
571         tcsetpgrp(0, getpgrp());
572         releaseConsole();
573     }
574     
575     logServiceFailed(service_name);
576     service_state = ServiceState::STOPPED;
577     notifyListeners(ServiceEvent::FAILEDSTART);
578     
579     // Cancel start of dependents:
580     for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
581         if ((*i)->service_state == ServiceState::STARTING) {
582             (*i)->failed_to_start(true);
583         }
584     }    
585     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
586         // We can send 'start', because this is only a soft dependency.
587         // Our startup failure means that they don't have to wait for us.
588         (*i)->getFrom()->dependencyStarted();
589     }
590 }
591
592 bool ServiceRecord::start_ps_process() noexcept
593 {
594     return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
595 }
596
597 bool ServiceRecord::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
598 {
599     // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
600     // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
601     // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
602     // is written to the pipe, and the parent can read it.
603
604     int pipefd[2];
605     if (pipe2(pipefd, O_CLOEXEC)) {
606         // TODO log error
607         return false;
608     }
609     
610     // Set up the argument array and other data now (before fork), in case memory allocation fails.
611     
612     auto args = cmd.data();
613     
614     const char * logfile = this->logfile.c_str();
615     if (*logfile == 0) {
616         logfile = "/dev/null";
617     }
618
619     // TODO make sure pipefd's are not 0/1/2 (STDIN/OUT/ERR) - if they are, dup them
620     // until they are not.
621
622     pid_t forkpid = fork();
623     if (forkpid == -1) {
624         // TODO log error
625         close(pipefd[0]);
626         close(pipefd[1]);
627         return false;
628     }
629
630     // If the console already has a session leader, presumably it is us. On the other hand
631     // if it has no session leader, and we don't create one, then control inputs such as
632     // ^C will have no effect.
633     bool do_set_ctty = (tcgetsid(0) == -1);
634
635     if (forkpid == 0) {
636         // Child process. Must not allocate memory (or otherwise risk throwing any exception)
637         // from here until exit().
638         ev_default_destroy(); // won't need that on this side, free up fds.
639
640         constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t) - 1) / 3 + 2) + 11;
641         // "LISTEN_PID=" - 11 characters
642         char nbuf[bufsz];
643
644         if (socket_fd != -1) {
645             dup2(socket_fd, 3);
646             if (socket_fd != 3) {
647                 close(socket_fd);
648             }
649             
650             if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
651             
652             snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
653             
654             if (putenv(nbuf)) goto failure_out;
655         }
656
657         if (! on_console) {
658             // Re-set stdin, stdout, stderr
659             close(0); close(1); close(2);
660
661             // TODO rethink this logic. If we open it at not-0, shouldn't we just dup it to 0?:
662             if (open("/dev/null", O_RDONLY) == 0) {
663               // stdin = 0. That's what we should have; proceed with opening
664               // stdout and stderr.
665               open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
666               dup2(1, 2);
667             }
668         }
669         else {
670             // "run on console" - run as a foreground job on the terminal/console device
671             if (do_set_ctty) {
672                 setsid();
673                 ioctl(0, TIOCSCTTY, 0);
674             }
675             setpgid(0,0);
676             tcsetpgrp(0, getpgrp());
677             
678             // TODO disable suspend (^Z)? (via tcsetattr)
679             //      (should be done before TIOCSCTTY)
680         }
681
682         execvp(exec_arg_parts[0], const_cast<char **>(args));
683
684         // If we got here, the exec failed:
685         failure_out:
686         int exec_status = errno;
687         write(pipefd[1], &exec_status, sizeof(int));
688         exit(0);
689     }
690     else {
691         // Parent process
692         close(pipefd[1]); // close the 'other end' fd
693
694         pid = forkpid;
695
696         // Listen for status
697         ev_io_init(&child_status_listener, process_child_status, pipefd[0], EV_READ);
698         child_status_listener.data = this;
699         ev_io_start(ev_default_loop(EVFLAG_AUTO), &child_status_listener);
700
701         // Add a process listener so we can detect when the
702         // service stops
703         ev_child_init(&child_listener, process_child_callback, pid, 0);
704         child_listener.data = this;
705         ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
706         waiting_for_execstat = true;
707         return true;
708     }
709 }
710
711 // Mark this and all dependent services as force-stopped.
712 void ServiceRecord::forceStop() noexcept
713 {
714     if (service_state != ServiceState::STOPPED) {
715         force_stop = true;
716         do_stop();
717     }
718 }
719
720 void ServiceRecord::dependentStopped() noexcept
721 {
722     if (service_state == ServiceState::STOPPING && waiting_for_deps) {
723         // Check the other dependents before we stop.
724         if (stopCheckDependents()) {
725             allDepsStopped();
726         }
727     }
728 }
729
730 void ServiceRecord::stop(bool bring_down) noexcept
731 {
732     if (start_explicit) {
733         start_explicit = false;
734         release();
735     }
736     
737     if (bring_down) {
738         desired_state = ServiceState::STOPPED;
739         do_stop();
740     }
741 }
742
743 void ServiceRecord::do_stop() noexcept
744 {
745     if (pinned_started) return;
746
747     if (service_state != ServiceState::STARTED) {
748         if (service_state == ServiceState::STARTING) {
749             if (! can_interrupt_start()) {
750                 // Well this is awkward: we're going to have to continue
751                 // starting, but we don't want any dependents to think that
752                 // they are still waiting to start.
753                 // Make sure they remain stopped:
754                 stopDependents();
755                 return;
756             }
757
758             // We must have had desired_state == STARTED.
759             notifyListeners(ServiceEvent::STARTCANCELLED);
760             
761             // Reaching this point, we have can_interrupt_start() == true. So,
762             // we can stop. Dependents might be starting, but they must be
763             // waiting on us, so they should also be immediately stoppable.
764             // Fall through to below,.
765         }
766         else {
767             // If we're starting we need to wait for that to complete.
768             // If we're already stopping/stopped there's nothing to do.
769             return;
770         }
771     }
772     
773     service_state = ServiceState::STOPPING;
774     waiting_for_deps = true;
775     
776     // If we get here, we are in STARTED state; stop all dependents.
777     if (stopDependents()) {
778         allDepsStopped();
779     }
780 }
781
782 bool ServiceRecord::stopCheckDependents() noexcept
783 {
784     bool all_deps_stopped = true;
785     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
786         if (! (*i)->is_stopped()) {
787             all_deps_stopped = false;
788             break;
789         }
790     }
791     
792     return all_deps_stopped;
793 }
794
795 bool ServiceRecord::stopDependents() noexcept
796 {
797     bool all_deps_stopped = true;
798     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
799         if (! (*i)->is_stopped()) {
800             all_deps_stopped = false;
801         }
802         if (force_stop) {
803             (*i)->forceStop();
804         }
805         else {
806             (*i)->do_stop();
807         }
808     }
809     
810     return all_deps_stopped;
811 }
812
813 // Dependency stopped or is stopping; we must stop too.
814 void ServiceRecord::allDepsStopped()
815 {
816     waiting_for_deps = false;
817     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
818         if (pid != -1) {
819             // The process is still kicking on - must actually kill it.
820             if (! onstart_flags.no_sigterm) {
821                 kill(pid, SIGTERM);
822             }
823             if (term_signal != -1) {
824                 kill(pid, term_signal);
825             }
826             // Now we wait; the rest is done in process_child_callback
827         }
828         else {
829             // The process is already dead.
830             stopped();
831         }
832     }
833     else if (service_type == ServiceType::SCRIPTED) {
834         // Scripted service.
835         if (stop_command.length() == 0) {
836             stopped();
837         }
838         else if (! start_ps_process(stop_arg_parts, false)) {
839             // Couldn't execute stop script, but there's not much we can do:
840             stopped();
841         }
842     }
843     else {
844         stopped();
845     }
846 }
847
848 void ServiceRecord::unpin() noexcept
849 {
850     if (pinned_started) {
851         pinned_started = false;
852         if (desired_state == ServiceState::STOPPED) {
853             stop();
854         }
855     }
856     if (pinned_stopped) {
857         pinned_stopped = false;
858         if (desired_state == ServiceState::STARTED) {
859             do_start();
860         }
861     }
862 }
863
864 void ServiceRecord::queueForConsole() noexcept
865 {
866     next_for_console = nullptr;
867     auto tail = service_set->consoleQueueTail(this);
868     if (tail == nullptr) {
869         acquiredConsole();
870     }
871     else {
872         tail->next_for_console = this;
873     }
874 }
875
876 void ServiceRecord::releaseConsole() noexcept
877 {
878     log_to_console = true;
879     if (next_for_console != nullptr) {
880         next_for_console->acquiredConsole();
881     }
882     else {
883         service_set->consoleQueueTail(nullptr);
884     }
885 }
886
887 void ServiceSet::service_active(ServiceRecord *sr) noexcept
888 {
889     active_services++;
890 }
891
892 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
893 {
894     active_services--;
895 }