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