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