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