Allow service start to be interrupted when waiting for restart timer.
[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     
897     constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
898     // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
899     // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
900     // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
901     char nbuf[bufsz];
902     
903     // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
904     constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
905     char csenvbuf[csenvbufsz];
906     
907     int minfd = (socket_fd == -1) ? 3 : 4;
908
909     // Move wpipefd/csfd to another fd if necessary
910     if (wpipefd < minfd) {
911         wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
912         if (wpipefd == -1) goto failure_out;
913     }
914     
915     if (csfd != -1 && csfd < minfd) {
916         csfd = fcntl(csfd, F_DUPFD, minfd);
917         if (csfd == -1) goto failure_out;
918     }
919     
920     if (socket_fd != -1) {
921         
922         if (dup2(socket_fd, 3) == -1) goto failure_out;
923         if (socket_fd != 3) {
924             close(socket_fd);
925         }
926         
927         if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
928         snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
929         if (putenv(nbuf)) goto failure_out;
930     }
931     
932     if (csfd != -1) {
933         snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
934         if (putenv(csenvbuf)) goto failure_out;
935     }
936
937     if (! on_console) {
938         // Re-set stdin, stdout, stderr
939         close(0); close(1); close(2);
940
941         if (open("/dev/null", O_RDONLY) == 0) {
942             // stdin = 0. That's what we should have; proceed with opening
943             // stdout and stderr.
944             if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
945                 goto failure_out;
946             }
947             if (dup2(1, 2) != 2) {
948                 goto failure_out;
949             }
950         }
951         else goto failure_out;
952         
953         // We have the option of creating a new process group and/or session. If
954         // we just create a new process group, the child process cannot make itself
955         // a session leader if it wants to do that (eg getty/login will generally
956         // want this). If we do neither, and we are running with a controlling
957         // terminal, a ^C or similar will also affect the child process.
958         setsid();
959     }
960     else {
961         // "run on console" - run as a foreground job on the terminal/console device
962         
963         // if do_set_ctty is false, we are the session leader; we are probably running
964         // as a user process. Don't create a new session leader in that case, and run
965         // as part of the parent session. Otherwise, the new session cannot claim the
966         // terminal as a controlling terminal (it is already claimed), meaning that it
967         // will not see control signals from ^C etc.
968         
969         if (do_set_ctty) {
970             // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
971             signal(SIGTSTP, SIG_IGN);
972             
973             // Become session leader
974             setsid();
975             ioctl(0, TIOCSCTTY, 0);
976         }
977         setpgid(0,0);
978         tcsetpgrp(0, getpgrp());
979     }
980     
981     sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
982     
983     execvp(args[0], const_cast<char **>(args));
984     
985     // If we got here, the exec failed:
986     failure_out:
987     int exec_status = errno;
988     write(wpipefd, &exec_status, sizeof(int));
989     _exit(0);
990 }
991
992 // Mark this and all dependent services as force-stopped.
993 void ServiceRecord::forceStop() noexcept
994 {
995     if (service_state != ServiceState::STOPPED) {
996         force_stop = true;
997         service_set->addToStopQueue(this);
998     }
999 }
1000
1001 void ServiceRecord::dependentStopped() noexcept
1002 {
1003     if (service_state == ServiceState::STOPPING && waiting_for_deps) {
1004         service_set->addToPropQueue(this);
1005     }
1006 }
1007
1008 void ServiceRecord::stop(bool bring_down) noexcept
1009 {
1010     if (start_explicit) {
1011         start_explicit = false;
1012         release();
1013     }
1014     
1015     if (bring_down && desired_state != ServiceState::STOPPED) {
1016         desired_state = ServiceState::STOPPED;
1017         service_set->addToStopQueue(this);
1018     }
1019 }
1020
1021 void ServiceRecord::do_stop() noexcept
1022 {
1023     if (pinned_started) return;
1024
1025     if (service_state != ServiceState::STARTED) {
1026         if (service_state == ServiceState::STARTING) {
1027             if (! can_interrupt_start()) {
1028                 // Well this is awkward: we're going to have to continue
1029                 // starting, but we don't want any dependents to think that
1030                 // they are still waiting to start.
1031                 // Make sure they remain stopped:
1032                 stopDependents();
1033                 return;
1034             }
1035
1036             // We must have had desired_state == STARTED.
1037             notifyListeners(ServiceEvent::STARTCANCELLED);
1038             
1039             // Reaching this point, we have can_interrupt_start() == true. So,
1040             // we can stop. Dependents might be starting, but they must be
1041             // waiting on us, so they should also be immediately stoppable.
1042             // Fall through to below,.
1043         }
1044         else {
1045             // If we're starting we need to wait for that to complete.
1046             // If we're already stopping/stopped there's nothing to do.
1047             return;
1048         }
1049     }
1050
1051     service_state = ServiceState::STOPPING;
1052     waiting_for_deps = true;
1053
1054     // If we get here, we are in STARTED state; stop all dependents.
1055     if (stopDependents()) {
1056         all_deps_stopped();
1057     }
1058 }
1059
1060 bool ServiceRecord::stopCheckDependents() noexcept
1061 {
1062     bool all_deps_stopped = true;
1063     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1064         if (! (*i)->is_stopped()) {
1065             all_deps_stopped = false;
1066             break;
1067         }
1068     }
1069     
1070     return all_deps_stopped;
1071 }
1072
1073 bool ServiceRecord::stopDependents() noexcept
1074 {
1075     bool all_deps_stopped = true;
1076     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1077         if (! (*i)->is_stopped()) {
1078             // Note we check *first* since if the dependent service is not stopped,
1079             // 1. We will issue a stop to it shortly and
1080             // 2. It will notify us when stopped, at which point the stopCheckDependents()
1081             //    check is run anyway.
1082             all_deps_stopped = false;
1083         }
1084
1085         (*i)->forceStop();
1086     }
1087
1088     return all_deps_stopped;
1089 }
1090
1091 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1092 void ServiceRecord::all_deps_stopped() noexcept
1093 {
1094     waiting_for_deps = false;
1095     stopped();
1096 }
1097
1098 void base_process_service::all_deps_stopped() noexcept
1099 {
1100     waiting_for_deps = false;
1101     if (pid != -1) {
1102         // The process is still kicking on - must actually kill it.
1103         if (! onstart_flags.no_sigterm) {
1104             kill(pid, SIGTERM);
1105         }
1106         if (term_signal != -1) {
1107             kill(pid, term_signal);
1108         }
1109
1110         // In most cases, the rest is done in process_child_callback.
1111         // If we are a BGPROCESS and the process is not our immediate child, however, that
1112         // won't work - check for this now:
1113         if (service_type == ServiceType::BGPROCESS) {
1114             int status;
1115             pid_t r = waitpid(pid, &status, WNOHANG);
1116             if (r == -1 && errno == ECHILD) {
1117                 // We can't track this child (or it's terminated already)
1118                 stopped();
1119             }
1120             else if (r == pid) {
1121                 // Process may have died due to signal since we explicitly requested it to
1122                 // stop by signalling it; no need to log any termination status.
1123                 stopped();
1124             }
1125         }
1126     }
1127     else {
1128         // The process is already dead.
1129         stopped();
1130     }
1131 }
1132
1133 void scripted_service::all_deps_stopped() noexcept
1134 {
1135     waiting_for_deps = false;
1136     if (stop_command.length() == 0) {
1137         stopped();
1138     }
1139     else if (! start_ps_process(stop_arg_parts, false)) {
1140         // Couldn't execute stop script, but there's not much we can do:
1141         stopped();
1142     }
1143 }
1144
1145 void ServiceRecord::unpin() noexcept
1146 {
1147     if (pinned_started) {
1148         pinned_started = false;
1149         if (desired_state == ServiceState::STOPPED) {
1150             do_stop();
1151             service_set->processQueues(false);
1152         }
1153     }
1154     if (pinned_stopped) {
1155         pinned_stopped = false;
1156         if (desired_state == ServiceState::STARTED) {
1157             do_start();
1158             service_set->processQueues(true);
1159         }
1160     }
1161 }
1162
1163 void ServiceRecord::queueForConsole() noexcept
1164 {
1165     service_set->append_console_queue(this);
1166 }
1167
1168 void ServiceRecord::releaseConsole() noexcept
1169 {
1170     service_set->pullConsoleQueue();
1171 }
1172
1173 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1174 {
1175     active_services++;
1176 }
1177
1178 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
1179 {
1180     active_services--;
1181 }
1182
1183 base_process_service::base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
1184         std::list<std::pair<unsigned,unsigned>> &command_offsets,
1185         sr_list * pdepends_on, sr_list * pdepends_soft)
1186      : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
1187          pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
1188 {
1189     restart_interval_count = 0;
1190     restart_interval_time = {0, 0};
1191     restart_timer.service = this;
1192     restart_timer.add_timer(eventLoop);
1193
1194     // By default, allow a maximum of 3 restarts within 10.0 seconds:
1195     restart_interval.tv_sec = 10;
1196     restart_interval.tv_nsec = 0;
1197     max_restart_interval_count = 3;
1198 }
1199
1200 void base_process_service::do_restart() noexcept
1201 {
1202     restarting = false;
1203     waiting_restart_timer = false;
1204
1205     // We may be STARTING (regular restart) or STARTED ("smooth recovery"). This affects whether
1206     // the process should be granted access to the console:
1207     bool on_console = service_state == ServiceState::STARTING
1208             ? onstart_flags.starts_on_console : onstart_flags.runs_on_console;
1209
1210     if (! start_ps_process(exec_arg_parts, on_console)) {
1211         if (service_state == ServiceState::STARTING) {
1212             failed_to_start();
1213         }
1214         else {
1215             desired_state = ServiceState::STOPPED;
1216             forceStop();
1217         }
1218         service_set->processQueues();
1219     }
1220 }
1221
1222 // Calculate different between two times (a more recent time, "now", and a previuos time "then").
1223 static timespec diff_time(timespec now, timespec then)
1224 {
1225     timespec r;
1226     r.tv_sec = now.tv_sec - then.tv_sec;
1227     if (now.tv_nsec >= then.tv_nsec) {
1228         r.tv_nsec = now.tv_nsec - then.tv_nsec;
1229     }
1230     else {
1231         r.tv_sec -= 1;
1232         r.tv_nsec = 1000000000 - (then.tv_nsec - now.tv_nsec);
1233     }
1234     return r;
1235 }
1236
1237 static bool operator<(const timespec &a, const timespec &b)
1238 {
1239     if (a.tv_sec < b.tv_sec) return true;
1240     if (a.tv_sec == b.tv_sec && a.tv_nsec < b.tv_nsec) return true;
1241     return false;
1242 }
1243
1244 bool base_process_service::restart_ps_process() noexcept
1245 {
1246     timespec current_time;
1247     eventLoop.get_time(current_time, clock_type::MONOTONIC);
1248
1249     if (max_restart_interval_count != 0) {
1250         // Check whether we're still in the most recent restart check interval:
1251         timespec int_diff = diff_time(current_time, restart_interval_time);
1252         if (int_diff < restart_interval) {
1253             if (++restart_interval_count >= max_restart_interval_count) {
1254                 log(LogLevel::ERROR, "Service ", service_name, " restarting too quickly; stopping.");
1255                 return false;
1256             }
1257         }
1258         else {
1259             restart_interval_time = current_time;
1260             restart_interval_count = 0;
1261         }
1262     }
1263
1264     // Check if enough time has lapsed since the prevous restart. If not, start a timer:
1265     timespec tdiff = diff_time(current_time, last_start_time);
1266     if (restart_delay < tdiff) {
1267         // > restart delay (normally 200ms)
1268         do_restart();
1269     }
1270     else {
1271         timespec timeout = diff_time(restart_delay, tdiff);
1272         restart_timer.arm_timer_rel(eventLoop, timeout);
1273         waiting_restart_timer = true;
1274     }
1275     return true;
1276 }
1277
1278 void base_process_service::interrupt_start() noexcept
1279 {
1280     // overridden in subclasses
1281     if (waiting_restart_timer) {
1282         restart_timer.stop_timer(eventLoop);
1283         waiting_restart_timer = false;
1284     }
1285 }
1286
1287 dasynq::rearm process_restart_timer::timer_expiry(EventLoop_t &, int expiry_count)
1288 {
1289     service->do_restart();
1290     return dasynq::rearm::DISARM;
1291 }