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