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