service: only force stop dependents if necessary.
[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 #include "dinit-socket.h"
20
21 /*
22  * service.cc - Service management.
23  * See service.h for details.
24  */
25
26 // from dinit.cc:
27 void open_control_socket(bool report_ro_failure = true) noexcept;
28 void setup_external_log() noexcept;
29 extern EventLoop_t eventLoop;
30
31 // Find the requested service by name
32 static ServiceRecord * find_service(const std::list<ServiceRecord *> & records,
33                                     const char *name) noexcept
34 {
35     using std::list;
36     list<ServiceRecord *>::const_iterator i = records.begin();
37     for ( ; i != records.end(); i++ ) {
38         if (strcmp((*i)->getServiceName().c_str(), name) == 0) {
39             return *i;
40         }
41     }
42     return (ServiceRecord *)0;
43 }
44
45 ServiceRecord * ServiceSet::find_service(const std::string &name) noexcept
46 {
47     return ::find_service(records, name.c_str());
48 }
49
50 void ServiceSet::startService(const char *name)
51 {
52     using namespace std;
53     ServiceRecord *record = loadServiceRecord(name);
54     
55     record->start();
56     processQueues(true);
57 }
58
59 void ServiceSet::stopService(const std::string & name) noexcept
60 {
61     ServiceRecord *record = find_service(name);
62     if (record != nullptr) {
63         record->stop();
64         processQueues(false);
65     }
66 }
67
68 // Called when a service has actually stopped; dependents have stopped already, unless this stop
69 // is due to an unexpected process termination.
70 void ServiceRecord::stopped() noexcept
71 {
72     if (onstart_flags.runs_on_console) {
73         tcsetpgrp(0, getpgrp());
74         discard_console_log_buffer();
75         releaseConsole();
76     }
77
78     force_stop = false;
79
80     // If we are a soft dependency of another target, break the acquisition from that target now:
81     bool will_restart = (desired_state == ServiceState::STARTED)
82             && service_set->get_auto_restart();
83
84     if (! will_restart) {
85         for (auto dependency : soft_dpts) {
86             if (dependency->holding_acq) {
87                 dependency->holding_acq = false;
88                 release();
89             }
90         }
91     }
92
93     for (auto dependency : depends_on) {
94         // we signal dependencies in case they are waiting for us to stop - but only if we won't
95         // restart or if they are stopping uninterruptibly.
96         if (! will_restart || ! dependency->can_interrupt_stop()) {
97             dependency->dependentStopped();
98         }
99     }
100
101     service_state = ServiceState::STOPPED;
102
103     if (will_restart) {
104         // Desired state is "started".
105         restarting = true;
106         service_set->addToStartQueue(this);
107     }
108     else {
109         if (socket_fd != -1) {
110             close(socket_fd);
111             socket_fd = -1;
112         }
113         
114         if (start_explicit) {
115             start_explicit = false;
116             release();
117         }
118         else if (required_by == 0) {
119             service_set->service_inactive(this);
120         }
121     }
122
123     logServiceStopped(service_name);
124     notifyListeners(ServiceEvent::STOPPED);
125 }
126
127 dasynq::rearm ServiceChildWatcher::status_change(EventLoop_t &loop, pid_t child, int status) noexcept
128 {
129     base_process_service *sr = service;
130     
131     sr->pid = -1;
132     sr->exit_status = status;
133     
134     // Ok, for a process service, any process death which we didn't rig
135     // ourselves is a bit... unexpected. Probably, the child died because
136     // we asked it to (sr->service_state == STOPPING). But even if
137     // we didn't, there's not much we can do.
138     
139     if (sr->waiting_for_execstat) {
140         // We still don't have an exec() status from the forked child, wait for that
141         // before doing any further processing.
142         return rearm::REMOVE;
143     }
144     
145     // Must deregister now since handle_exit_status might result in re-launch:
146     deregister(loop, child);
147     
148     sr->handle_exit_status(status);
149     return rearm::REMOVED;
150 }
151
152 bool ServiceRecord::do_auto_restart() noexcept
153 {
154     if (auto_restart) {
155         return service_set->get_auto_restart();
156     }
157     return false;
158 }
159
160 void process_service::handle_exit_status(int exit_status) noexcept
161 {
162     bool did_exit = WIFEXITED(exit_status);
163     bool was_signalled = WIFSIGNALED(exit_status);
164
165     if (exit_status != 0 && service_state != ServiceState::STOPPING) {
166         if (did_exit) {
167             log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
168         }
169         else if (was_signalled) {
170             log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
171         }
172     }
173
174     if (service_state == ServiceState::STARTING) {
175         if (did_exit && WEXITSTATUS(exit_status) == 0) {
176             started();
177         }
178         else {
179             failed_to_start();
180         }
181     }
182     else if (service_state == ServiceState::STOPPING) {
183         // We won't log a non-zero exit status or termination due to signal here -
184         // we assume that the process died because we signalled it.
185         stopped();
186     }
187     else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
188         // TODO if we are pinned-started then we should probably check
189         //      that dependencies have started before trying to re-start the
190         //      service process.
191         if (! restart_ps_process()) {
192             desired_state = ServiceState::STOPPED;
193             forceStop();
194         }
195         return;
196     }
197     else {
198         if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
199         forceStop();
200     }
201     service_set->processQueues(false);
202 }
203
204 void bgproc_service::handle_exit_status(int exit_status) noexcept
205 {
206     bool did_exit = WIFEXITED(exit_status);
207     bool was_signalled = WIFSIGNALED(exit_status);
208
209     if (exit_status != 0 && service_state != ServiceState::STOPPING) {
210         if (did_exit) {
211             log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
212         }
213         else if (was_signalled) {
214             log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
215         }
216     }
217
218     if (doing_recovery) {
219         // (BGPROCESS only)
220         doing_recovery = false;
221         bool need_stop = false;
222         if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
223             need_stop = true;
224         }
225         else {
226             // We need to re-read the PID, since it has now changed.
227             if (pid_file.length() != 0) {
228                 if (! read_pid_file()) {
229                     need_stop = true;
230                 }
231             }
232         }
233
234         if (need_stop) {
235             // Failed startup: no auto-restart.
236             desired_state = ServiceState::STOPPED;
237             forceStop();
238             service_set->processQueues(false);
239         }
240
241         return;
242     }
243
244     if (service_state == ServiceState::STARTING) {
245         // POSIX requires that if the process exited clearly with a status code of 0,
246         // the exit status value will be 0:
247         if (exit_status == 0) {
248             if (pid_file.length() != 0 && ! read_pid_file()) {
249                 failed_to_start();
250             }
251             else {
252                 started();
253             }
254         }
255         else {
256             failed_to_start();
257         }
258     }
259     else if (service_state == ServiceState::STOPPING) {
260         // We won't log a non-zero exit status or termination due to signal here -
261         // we assume that the process died because we signalled it.
262         stopped();
263     }
264     else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
265         // TODO if we are pinned-started then we should probably check
266         //      that dependencies have started before trying to re-start the
267         //      service process.
268         doing_recovery = true;
269         if (! restart_ps_process()) {
270             desired_state = ServiceState::STOPPED;
271             forceStop();
272         }
273         return;
274     }
275     else {
276         if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
277         forceStop();
278     }
279     service_set->processQueues(false);
280 }
281
282 void scripted_service::handle_exit_status(int exit_status) noexcept
283 {
284     bool did_exit = WIFEXITED(exit_status);
285     bool was_signalled = WIFSIGNALED(exit_status);
286
287     if (service_state == ServiceState::STOPPING) {
288         if (did_exit && WEXITSTATUS(exit_status) == 0) {
289             stopped();
290         }
291         else {
292             // ??? failed to stop! Let's log it as info:
293             if (did_exit) {
294                 log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
295             }
296             else if (was_signalled) {
297                 log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
298             }
299             // Just assume that we stopped, so that any dependencies
300             // can be stopped:
301             stopped();
302         }
303         service_set->processQueues(false);
304     }
305     else { // STARTING
306         if (exit_status == 0) {
307             started();
308         }
309         else {
310             // failed to start
311             if (did_exit) {
312                 log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
313             }
314             else if (was_signalled) {
315                 log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
316             }
317             failed_to_start();
318         }
319         service_set->processQueues(true);
320     }
321 }
322
323 rearm ServiceIoWatcher::fd_event(EventLoop_t &loop, int fd, int flags) noexcept
324 {
325     base_process_service *sr = service;
326     sr->waiting_for_execstat = false;
327     
328     int exec_status;
329     int r = read(get_watched_fd(), &exec_status, sizeof(int));
330     deregister(loop);
331     close(get_watched_fd());
332     
333     if (r > 0) {
334         // We read an errno code; exec() failed, and the service startup failed.
335         sr->pid = -1;
336         log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
337         if (sr->service_state == ServiceState::STARTING) {
338             sr->failed_to_start();
339         }
340         else if (sr->service_state == ServiceState::STOPPING) {
341             // Must be a scripted service. We've logged the failure, but it's probably better
342             // not to leave the service in STARTED state:
343             sr->stopped();
344         }
345     }
346     else {
347         // exec() succeeded.
348         if (sr->service_type == ServiceType::PROCESS) {
349             // This could be a smooth recovery (state already STARTED). Even more, the process
350             // might be stopped (and killed via a signal) during smooth recovery.  We don't to
351             // process startup again in either case, so we check for state STARTING:
352             if (sr->service_state == ServiceState::STARTING) {
353                 sr->started();
354             }
355         }
356         
357         if (sr->pid == -1) {
358             // Somehow the process managed to complete before we even saw the status.
359             sr->handle_exit_status(sr->exit_status);
360         }
361     }
362     
363     sr->service_set->processQueues(true);
364     
365     return rearm::REMOVED;
366 }
367
368 void ServiceRecord::require() noexcept
369 {
370     if (required_by++ == 0) {
371         
372         if (! prop_require) {
373             prop_require = true;
374             prop_release = false;
375             service_set->addToPropQueue(this);
376         }
377         
378         if (service_state == ServiceState::STOPPED) {
379             // (In any other state, the service is already considered active.)
380             service_set->service_active(this);
381         }
382     }
383 }
384
385 void ServiceRecord::release() noexcept
386 {
387     if (--required_by == 0) {
388         desired_state = ServiceState::STOPPED;
389         // Can stop, and can release dependencies now:
390         prop_release = true;
391         prop_require = false;
392         service_set->addToPropQueue(this);
393         if (service_state != ServiceState::STOPPED) {
394             service_set->addToStopQueue(this);
395         }
396         else {
397             service_set->service_inactive(this);
398         }
399     }
400 }
401
402 void ServiceRecord::release_dependencies() noexcept
403 {
404     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
405         (*i)->release();
406     }
407
408     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
409         ServiceRecord * to = i->getTo();
410         if (i->holding_acq) {
411             to->release();
412             i->holding_acq = false;
413         }
414     }
415 }
416
417 void ServiceRecord::start(bool activate) noexcept
418 {
419     if (activate && ! start_explicit) {
420         require();
421         start_explicit = true;
422     }
423     
424     if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
425     
426     desired_state = ServiceState::STARTED;
427     service_set->addToStartQueue(this);
428 }
429
430 void ServiceRecord::do_propagation() noexcept
431 {
432     if (prop_require) {
433         // Need to require all our dependencies
434         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
435             (*i)->require();
436         }
437
438         for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
439             ServiceRecord * to = i->getTo();
440             to->require();
441             i->holding_acq = true;
442         }
443         
444         prop_require = false;
445     }
446     
447     if (prop_release) {
448         release_dependencies();
449         prop_release = false;
450     }
451     
452     if (prop_failure) {
453         prop_failure = false;
454         failed_to_start(true);
455     }
456     
457     if (waiting_for_deps) {
458         if (service_state == ServiceState::STARTING) {
459             if (startCheckDependencies(false)) {
460                 allDepsStarted();
461             }
462         }
463         else if (service_state == ServiceState::STOPPING) {
464             if (stopCheckDependents()) {
465                 all_deps_stopped();
466             }
467         }
468     }
469 }
470
471 void ServiceRecord::execute_transition() noexcept
472 {
473     bool is_started = (service_state == ServiceState::STARTED)
474             || (service_state == ServiceState::STARTING && can_interrupt_start());
475     bool is_stopped = (service_state == ServiceState::STOPPED)
476             || (service_state == ServiceState::STOPPING && can_interrupt_stop());
477
478     if (is_started && (desired_state == ServiceState::STOPPED || force_stop)) {
479         if (! pinned_started) {
480             do_stop();
481         }
482     }
483     else if (is_stopped && desired_state == ServiceState::STARTED) {
484         if (! pinned_stopped) {
485             do_start();
486         }
487     }
488 }
489
490 void ServiceRecord::do_start() noexcept
491 {
492     if (pinned_stopped) return;
493     
494     if (service_state != ServiceState::STOPPED) {
495         // We're already starting/started, or we are stopping and need to wait for
496         // that the complete.
497         if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
498             return;
499         }
500         // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
501         // but if so they are waiting (for us), so they too can be instantly returned to
502         // STARTING state.
503         notifyListeners(ServiceEvent::STOPCANCELLED);
504     }
505     
506     service_state = ServiceState::STARTING;
507
508     waiting_for_deps = true;
509
510     // Ask dependencies to start, mark them as being waited on.
511     if (! startCheckDependencies(true)) {
512         return;
513     }
514
515     // Actually start this service.
516     allDepsStarted();
517 }
518
519 void ServiceRecord::dependencyStarted() noexcept
520 {
521     if (service_state == ServiceState::STARTING && waiting_for_deps) {
522         service_set->addToPropQueue(this);
523     }
524 }
525
526 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
527 {
528     bool all_deps_started = true;
529
530     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
531         if ((*i)->service_state != ServiceState::STARTED) {
532             if (start_deps) {
533                 all_deps_started = false;
534                 (*i)->start(false);
535             }
536             else {
537                 return false;
538             }
539         }
540     }
541
542     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
543         ServiceRecord * to = i->getTo();
544         if (start_deps) {
545             if (to->service_state != ServiceState::STARTED) {
546                 to->start(false);
547                 i->waiting_on = true;
548                 all_deps_started = false;
549             }
550             else {
551                 i->waiting_on = false;
552             }
553         }
554         else if (i->waiting_on) {
555             if (to->service_state != ServiceState::STARTING) {
556                 // Service has either started or is no longer starting
557                 i->waiting_on = false;
558             }
559             else {
560                 // We are still waiting on this service
561                 return false;
562             }
563         }
564     }
565     
566     return all_deps_started;
567 }
568
569 bool ServiceRecord::open_socket() noexcept
570 {
571     if (socket_path.empty() || socket_fd != -1) {
572         // No socket, or already open
573         return true;
574     }
575     
576     const char * saddrname = socket_path.c_str();
577     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
578
579     struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
580     if (name == nullptr) {
581         log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
582         return false;
583     }
584     
585     // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
586     unlink(saddrname);
587
588     name->sun_family = AF_UNIX;
589     strcpy(name->sun_path, saddrname);
590
591     int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
592     if (sockfd == -1) {
593         log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
594         free(name);
595         return false;
596     }
597
598     if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
599         log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
600         close(sockfd);
601         free(name);
602         return false;
603     }
604     
605     free(name);
606     
607     // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
608     // use chown and chmod instead.
609     if (chown(saddrname, socket_uid, socket_gid)) {
610         log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
611         close(sockfd);
612         return false;
613     }
614     
615     if (chmod(saddrname, socket_perms) == -1) {
616         log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
617         close(sockfd);
618         return false;
619     }
620
621     if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
622         log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
623         close(sockfd);
624         return false;
625     }
626     
627     socket_fd = sockfd;
628     return true;
629 }
630
631 void ServiceRecord::allDepsStarted(bool has_console) noexcept
632 {
633     if (onstart_flags.starts_on_console && ! has_console) {
634         waiting_for_deps = true;
635         queueForConsole();
636         return;
637     }
638     
639     waiting_for_deps = false;
640
641     if (! open_socket()) {
642         failed_to_start();
643     }
644
645     bool start_success = start_ps_process();
646     if (! start_success) {
647         failed_to_start();
648     }
649 }
650
651 void ServiceRecord::acquiredConsole() noexcept
652 {
653     if (service_state != ServiceState::STARTING) {
654         // We got the console but no longer want it.
655         releaseConsole();
656     }
657     else if (startCheckDependencies(false)) {
658         allDepsStarted(true);
659     }
660     else {
661         // We got the console but can't use it yet.
662         releaseConsole();
663     }
664 }
665
666 bool bgproc_service::read_pid_file() noexcept
667 {
668     const char *pid_file_c = pid_file.c_str();
669     int fd = open(pid_file_c, O_CLOEXEC);
670     if (fd != -1) {
671         char pidbuf[21]; // just enought to hold any 64-bit integer
672         int r = read(fd, pidbuf, 20);
673         if (r > 0) {
674             pidbuf[r] = 0; // store nul terminator
675             pid = std::atoi(pidbuf);
676             if (kill(pid, 0) == 0) {                
677                 child_listener.add_watch(eventLoop, pid);
678             }
679             else {
680                 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
681                 pid = -1;
682                 close(fd);
683                 return false;
684             }
685         }
686         close(fd);
687         return true;
688     }
689     else {
690         log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
691         return false;
692     }
693 }
694
695 void ServiceRecord::started() noexcept
696 {
697     if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
698         tcsetpgrp(0, getpgrp());
699         releaseConsole();
700     }
701
702     logServiceStarted(service_name);
703     service_state = ServiceState::STARTED;
704     notifyListeners(ServiceEvent::STARTED);
705
706     if (onstart_flags.rw_ready) {
707         open_control_socket();
708     }
709     if (onstart_flags.log_ready) {
710         setup_external_log();
711     }
712
713     if (force_stop || desired_state == ServiceState::STOPPED) {
714         // We must now stop.
715         service_set->addToStopQueue(this);
716         return;
717     }
718
719     // Notify any dependents whose desired state is STARTED:
720     for (auto i = dependents.begin(); i != dependents.end(); i++) {
721         (*i)->dependencyStarted();
722     }
723     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
724         (*i)->getFrom()->dependencyStarted();
725     }
726 }
727
728 void ServiceRecord::failed_to_start(bool depfailed) noexcept
729 {
730     if (!depfailed && onstart_flags.starts_on_console) {
731         tcsetpgrp(0, getpgrp());
732         releaseConsole();
733     }
734     
735     logServiceFailed(service_name);
736     service_state = ServiceState::STOPPED;
737     if (start_explicit) {
738         start_explicit = false;
739         release();
740     }
741     notifyListeners(ServiceEvent::FAILEDSTART);
742     
743     // Cancel start of dependents:
744     for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
745         if ((*i)->service_state == ServiceState::STARTING) {
746             (*i)->prop_failure = true;
747             service_set->addToPropQueue(*i);
748         }
749     }    
750     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
751         // We can send 'start', because this is only a soft dependency.
752         // Our startup failure means that they don't have to wait for us.
753         if ((*i)->waiting_on) {
754             (*i)->holding_acq = false;
755             (*i)->waiting_on = false;
756             (*i)->getFrom()->dependencyStarted();
757             release();
758         }
759     }
760 }
761
762 bool ServiceRecord::start_ps_process() noexcept
763 {
764     // default implementation: there is no process, so we are started.
765     started();
766     return true;
767 }
768
769 bool base_process_service::start_ps_process() noexcept
770 {
771     if (restarting) {
772         return restart_ps_process();
773     }
774     else {
775         eventLoop.get_time(restart_interval_time, clock_type::MONOTONIC);
776         restart_interval_count = 0;
777         return start_ps_process(exec_arg_parts, onstart_flags.starts_on_console);
778     }
779 }
780
781 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
782 {
783     // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
784     // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
785     // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
786     // is written to the pipe, and the parent can read it.
787
788     eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
789
790     int pipefd[2];
791     if (pipe2(pipefd, O_CLOEXEC)) {
792         log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
793         return false;
794     }
795
796     const char * logfile = this->logfile.c_str();
797     if (*logfile == 0) {
798         logfile = "/dev/null";
799     }
800
801     bool child_status_registered = false;
802     ControlConn *control_conn = nullptr;
803     
804     int control_socket[2] = {-1, -1};
805     if (onstart_flags.pass_cs_fd) {
806         if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
807             log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
808             goto out_p;
809         }
810         
811         // Make the server side socket close-on-exec:
812         int fdflags = fcntl(control_socket[0], F_GETFD);
813         fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
814         
815         try {
816             control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
817         }
818         catch (std::exception &exc) {
819             log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
820             goto out_cs;
821         }
822     }
823     
824     // Set up complete, now fork and exec:
825     
826     pid_t forkpid;
827     
828     try {
829         child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
830         child_status_registered = true;
831         
832         forkpid = child_listener.fork(eventLoop);
833     }
834     catch (std::exception &e) {
835         log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
836         goto out_cs_h;
837     }
838
839     if (forkpid == 0) {
840         run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
841     }
842     else {
843         // Parent process
844         close(pipefd[1]); // close the 'other end' fd
845         if (control_socket[1] != -1) {
846             close(control_socket[1]);
847         }
848         pid = forkpid;
849
850         waiting_for_execstat = true;
851         return true;
852     }
853
854     // Failure exit:
855     
856     out_cs_h:
857     if (child_status_registered) {
858         child_status_listener.deregister(eventLoop);
859     }
860     
861     if (onstart_flags.pass_cs_fd) {
862         delete control_conn;
863     
864         out_cs:
865         close(control_socket[0]);
866         close(control_socket[1]);
867     }
868     
869     out_p:
870     close(pipefd[0]);
871     close(pipefd[1]);
872     
873     return false;
874 }
875
876 void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
877         int wpipefd, int csfd) noexcept
878 {
879     // Child process. Must not allocate memory (or otherwise risk throwing any exception)
880     // from here until exit().
881
882     // If the console already has a session leader, presumably it is us. On the other hand
883     // if it has no session leader, and we don't create one, then control inputs such as
884     // ^C will have no effect.
885     bool do_set_ctty = (tcgetsid(0) == -1);
886     
887     // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
888     // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
889     sigset_t sigwait_set;
890     sigset_t sigall_set;
891     sigfillset(&sigall_set);
892     sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
893     sigdelset(&sigwait_set, SIGCHLD);
894     sigdelset(&sigwait_set, SIGINT);
895     sigdelset(&sigwait_set, SIGTERM);
896     sigdelset(&sigwait_set, SIGQUIT);
897     
898     constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
899     // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
900     // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
901     // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
902     char nbuf[bufsz];
903     
904     // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
905     constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
906     char csenvbuf[csenvbufsz];
907     
908     int minfd = (socket_fd == -1) ? 3 : 4;
909
910     // Move wpipefd/csfd to another fd if necessary
911     if (wpipefd < minfd) {
912         wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
913         if (wpipefd == -1) goto failure_out;
914     }
915     
916     if (csfd != -1 && csfd < minfd) {
917         csfd = fcntl(csfd, F_DUPFD, minfd);
918         if (csfd == -1) goto failure_out;
919     }
920     
921     if (socket_fd != -1) {
922         
923         if (dup2(socket_fd, 3) == -1) goto failure_out;
924         if (socket_fd != 3) {
925             close(socket_fd);
926         }
927         
928         if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
929         snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
930         if (putenv(nbuf)) goto failure_out;
931     }
932     
933     if (csfd != -1) {
934         snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
935         if (putenv(csenvbuf)) goto failure_out;
936     }
937
938     if (! on_console) {
939         // Re-set stdin, stdout, stderr
940         close(0); close(1); close(2);
941
942         if (open("/dev/null", O_RDONLY) == 0) {
943             // stdin = 0. That's what we should have; proceed with opening
944             // stdout and stderr.
945             if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
946                 goto failure_out;
947             }
948             if (dup2(1, 2) != 2) {
949                 goto failure_out;
950             }
951         }
952         else goto failure_out;
953         
954         // We have the option of creating a new process group and/or session. If
955         // we just create a new process group, the child process cannot make itself
956         // a session leader if it wants to do that (eg getty/login will generally
957         // want this). If we do neither, and we are running with a controlling
958         // terminal, a ^C or similar will also affect the child process.
959         setsid();
960     }
961     else {
962         // "run on console" - run as a foreground job on the terminal/console device
963         
964         // if do_set_ctty is false, we are the session leader; we are probably running
965         // as a user process. Don't create a new session leader in that case, and run
966         // as part of the parent session. Otherwise, the new session cannot claim the
967         // terminal as a controlling terminal (it is already claimed), meaning that it
968         // will not see control signals from ^C etc.
969         
970         if (do_set_ctty) {
971             // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
972             signal(SIGTSTP, SIG_IGN);
973             
974             // Become session leader
975             setsid();
976             ioctl(0, TIOCSCTTY, 0);
977         }
978         setpgid(0,0);
979         tcsetpgrp(0, getpgrp());
980     }
981     
982     sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
983     
984     execvp(args[0], const_cast<char **>(args));
985     
986     // If we got here, the exec failed:
987     failure_out:
988     int exec_status = errno;
989     write(wpipefd, &exec_status, sizeof(int));
990     _exit(0);
991 }
992
993 // Mark this and all dependent services as force-stopped.
994 void ServiceRecord::forceStop() noexcept
995 {
996     if (service_state != ServiceState::STOPPED) {
997         force_stop = true;
998         service_set->addToStopQueue(this);
999     }
1000 }
1001
1002 void ServiceRecord::dependentStopped() noexcept
1003 {
1004     if (service_state == ServiceState::STOPPING && waiting_for_deps) {
1005         service_set->addToPropQueue(this);
1006     }
1007 }
1008
1009 void ServiceRecord::stop(bool bring_down) noexcept
1010 {
1011     if (start_explicit) {
1012         start_explicit = false;
1013         release();
1014     }
1015     
1016     if (bring_down && desired_state != ServiceState::STOPPED) {
1017         desired_state = ServiceState::STOPPED;
1018         service_set->addToStopQueue(this);
1019     }
1020 }
1021
1022 void ServiceRecord::do_stop() noexcept
1023 {
1024     if (pinned_started) return;
1025
1026     if (service_state != ServiceState::STARTED) {
1027         if (service_state == ServiceState::STARTING) {
1028             if (! can_interrupt_start()) {
1029                 // Well this is awkward: we're going to have to continue
1030                 // starting, but we don't want any dependents to think that
1031                 // they are still waiting to start.
1032                 // Make sure they remain stopped:
1033                 stopDependents();
1034                 return;
1035             }
1036
1037             // We must have had desired_state == STARTED.
1038             notifyListeners(ServiceEvent::STARTCANCELLED);
1039             
1040             // Reaching this point, we have can_interrupt_start() == true. So,
1041             // we can stop. Dependents might be starting, but they must be
1042             // waiting on us, so they should also be immediately stoppable.
1043             // Fall through to below,.
1044         }
1045         else {
1046             // If we're starting we need to wait for that to complete.
1047             // If we're already stopping/stopped there's nothing to do.
1048             return;
1049         }
1050     }
1051
1052     service_state = ServiceState::STOPPING;
1053     waiting_for_deps = true;
1054
1055     // If we get here, we are in STARTED state; stop all dependents.
1056     if (stopDependents()) {
1057         all_deps_stopped();
1058     }
1059 }
1060
1061 bool ServiceRecord::stopCheckDependents() noexcept
1062 {
1063     bool all_deps_stopped = true;
1064     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1065         if (! (*i)->is_stopped()) {
1066             all_deps_stopped = false;
1067             break;
1068         }
1069     }
1070     
1071     return all_deps_stopped;
1072 }
1073
1074 bool ServiceRecord::stopDependents() noexcept
1075 {
1076     bool all_deps_stopped = true;
1077     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1078         if (! (*i)->is_stopped()) {
1079             // Note we check *first* since if the dependent service is not stopped,
1080             // 1. We will issue a stop to it shortly and
1081             // 2. It will notify us when stopped, at which point the stopCheckDependents()
1082             //    check is run anyway.
1083             all_deps_stopped = false;
1084         }
1085
1086         if (force_stop) {
1087             // If this service is to be forcefully stopped, dependents must also be.
1088             (*i)->forceStop();
1089         }
1090
1091         (*i)->do_stop();
1092     }
1093
1094     return all_deps_stopped;
1095 }
1096
1097 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1098 void ServiceRecord::all_deps_stopped() noexcept
1099 {
1100     waiting_for_deps = false;
1101     stopped();
1102 }
1103
1104 void base_process_service::all_deps_stopped() noexcept
1105 {
1106     waiting_for_deps = false;
1107     if (pid != -1) {
1108         // The process is still kicking on - must actually kill it.
1109         if (! onstart_flags.no_sigterm) {
1110             kill(pid, SIGTERM);
1111         }
1112         if (term_signal != -1) {
1113             kill(pid, term_signal);
1114         }
1115
1116         // In most cases, the rest is done in process_child_callback.
1117         // If we are a BGPROCESS and the process is not our immediate child, however, that
1118         // won't work - check for this now:
1119         if (service_type == ServiceType::BGPROCESS) {
1120             int status;
1121             pid_t r = waitpid(pid, &status, WNOHANG);
1122             if (r == -1 && errno == ECHILD) {
1123                 // We can't track this child (or it's terminated already)
1124                 stopped();
1125             }
1126             else if (r == pid) {
1127                 // Process may have died due to signal since we explicitly requested it to
1128                 // stop by signalling it; no need to log any termination status.
1129                 stopped();
1130             }
1131         }
1132     }
1133     else {
1134         // The process is already dead.
1135         stopped();
1136     }
1137 }
1138
1139 void scripted_service::all_deps_stopped() noexcept
1140 {
1141     waiting_for_deps = false;
1142     if (stop_command.length() == 0) {
1143         stopped();
1144     }
1145     else if (! start_ps_process(stop_arg_parts, false)) {
1146         // Couldn't execute stop script, but there's not much we can do:
1147         stopped();
1148     }
1149 }
1150
1151 void ServiceRecord::unpin() noexcept
1152 {
1153     if (pinned_started) {
1154         pinned_started = false;
1155         if (desired_state == ServiceState::STOPPED) {
1156             do_stop();
1157             service_set->processQueues(false);
1158         }
1159     }
1160     if (pinned_stopped) {
1161         pinned_stopped = false;
1162         if (desired_state == ServiceState::STARTED) {
1163             do_start();
1164             service_set->processQueues(true);
1165         }
1166     }
1167 }
1168
1169 void ServiceRecord::queueForConsole() noexcept
1170 {
1171     service_set->append_console_queue(this);
1172 }
1173
1174 void ServiceRecord::releaseConsole() noexcept
1175 {
1176     service_set->pullConsoleQueue();
1177 }
1178
1179 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1180 {
1181     active_services++;
1182 }
1183
1184 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
1185 {
1186     active_services--;
1187 }
1188
1189 base_process_service::base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
1190         std::list<std::pair<unsigned,unsigned>> &command_offsets,
1191         sr_list * pdepends_on, sr_list * pdepends_soft)
1192      : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
1193          pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
1194 {
1195     restart_interval_count = 0;
1196     restart_interval_time = {0, 0};
1197     restart_timer.service = this;
1198     restart_timer.add_timer(eventLoop);
1199
1200     // By default, allow a maximum of 3 restarts within 10.0 seconds:
1201     restart_interval.tv_sec = 10;
1202     restart_interval.tv_nsec = 0;
1203     max_restart_interval_count = 3;
1204 }
1205
1206 void base_process_service::do_restart() noexcept
1207 {
1208     restarting = false;
1209     waiting_restart_timer = false;
1210
1211     // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1212     // the process should be granted access to the console:
1213     bool on_console = service_state == ServiceState::STARTING
1214             ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1215
1216     if (! start_ps_process(exec_arg_parts, on_console)) {
1217         if (service_state == ServiceState::STARTING) {
1218             failed_to_start();
1219         }
1220         else {
1221             desired_state = ServiceState::STOPPED;
1222             forceStop();
1223         }
1224         service_set->processQueues();
1225     }
1226 }
1227
1228 // Calculate different between two times (a more recent time, "now", and a previuos time "then").
1229 static timespec diff_time(timespec now, timespec then)
1230 {
1231     timespec r;
1232     r.tv_sec = now.tv_sec - then.tv_sec;
1233     if (now.tv_nsec >= then.tv_nsec) {
1234         r.tv_nsec = now.tv_nsec - then.tv_nsec;
1235     }
1236     else {
1237         r.tv_sec -= 1;
1238         r.tv_nsec = 1000000000 - (then.tv_nsec - now.tv_nsec);
1239     }
1240     return r;
1241 }
1242
1243 static bool operator<(const timespec &a, const timespec &b)
1244 {
1245     if (a.tv_sec < b.tv_sec) return true;
1246     if (a.tv_sec == b.tv_sec && a.tv_nsec < b.tv_nsec) return true;
1247     return false;
1248 }
1249
1250 bool base_process_service::restart_ps_process() noexcept
1251 {
1252     timespec current_time;
1253     eventLoop.get_time(current_time, clock_type::MONOTONIC);
1254
1255     if (max_restart_interval_count != 0) {
1256         // Check whether we're still in the most recent restart check interval:
1257         timespec int_diff = diff_time(current_time, restart_interval_time);
1258         if (int_diff < restart_interval) {
1259             if (++restart_interval_count >= max_restart_interval_count) {
1260                 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1261                 return false;
1262             }
1263         }
1264         else {
1265             restart_interval_time = current_time;
1266             restart_interval_count = 0;
1267         }
1268     }
1269
1270     // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1271     timespec tdiff = diff_time(current_time, last_start_time);
1272     if (restart_delay < tdiff) {
1273         // > restart delay (normally 200ms)
1274         do_restart();
1275     }
1276     else {
1277         timespec timeout = diff_time(restart_delay, tdiff);
1278         restart_timer.arm_timer_rel(eventLoop, timeout);
1279         waiting_restart_timer = true;
1280     }
1281     return true;
1282 }
1283
1284 void base_process_service::interrupt_start() noexcept
1285 {
1286     // overridden in subclasses
1287     if (waiting_restart_timer) {
1288         restart_timer.stop_timer(eventLoop);
1289         waiting_restart_timer = false;
1290     }
1291 }
1292
1293 dasynq::rearm process_restart_timer::timer_expiry(EventLoop_t &, int expiry_count)
1294 {
1295     service->do_restart();
1296     return dasynq::rearm::DISARM;
1297 }