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