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