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