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