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