Properly handle scripted service start interrupt.
[oweals/dinit.git] / src / service.h
1 #ifndef SERVICE_H
2 #define SERVICE_H
3
4 #include <string>
5 #include <list>
6 #include <vector>
7 #include <csignal>
8 #include <unordered_set>
9 #include <algorithm>
10
11 #include "dasynq.h"
12
13 #include "control.h"
14 #include "service-listener.h"
15 #include "service-constants.h"
16 #include "dinit-ll.h"
17
18 /*
19  * This header defines service_record, a data record maintaining information about a service,
20  * and service_set, a set of interdependent service records. It also defines some associated
21  * types and exceptions.
22  *
23  * Service states
24  * --------------
25  * Services have both a current state and a desired state. The desired state can be
26  * either STARTED or STOPPED. The current state can also be STARTING or STOPPING.
27  * A service can be "pinned" in either the STARTED or STOPPED states to prevent it
28  * from leaving that state until it is unpinned.
29  *
30  * The total state is a combination of the two, current and desired:
31  *      STOPPED/STOPPED  : stopped and will remain stopped
32  *      STOPPED/STARTED  : stopped (pinned), must be unpinned to start
33  *      STARTING/STARTED : starting, but not yet started. Dependencies may also be starting.
34  *      STARTING/STOPPED : as above, but the service will be stopped again as soon as it has
35  *                         completed startup.
36  *      STARTED/STARTED  : running and will continue running.
37  *      STARTED/STOPPED  : started (pinned), must be unpinned to stop
38  *      STOPPING/STOPPED : stopping and will stop. Dependents may be stopping.
39  *      STOPPING/STARTED : as above, but the service will be re-started again once it stops.
40  *
41  * A scripted service is in the STARTING/STOPPING states during the script execution.
42  * A process service is in the STOPPING state when it has been signalled to stop, and is
43  * in the STARTING state when waiting for dependencies to start or for the exec() call in
44  * the forked child to complete and return a status.
45  *
46  * Acquisition/release:
47  * ------------------
48  * Each service has a dependent-count ("required_by"). This starts at 0, adds 1 if the
49  * service has explicitly been started (i.e. "start_explicit" is true), and adds 1 for
50  * each dependent service which is not STOPPED (including dependents with a soft dependency).
51  * When required_by transitions to 0, the service is stopped (unless it is pinned). When
52  * require_by transitions from 0, the service is started (unless pinned).
53  *
54  * So, in general, the dependent-count determines the desired state (STARTED if the count
55  * is greater than 0, otherwise STOPPED). However, a service can be issued a stop-and-take
56  * down order (via `stop(true)'); this will first stop dependent services, which may restart
57  * and cancel the stop of the former service. Finally, a service can be force-stopped, which
58  * means that its stop process cannot be cancelled (though it may still be put in a desired
59  * state of STARTED, meaning it will start immediately upon stopping).
60  *
61  * Pinning
62  * -------
63  * A service may be "pinned" in either STARTED or STOPPED states (or even both). Once it
64  * reaches a pinned state, a service will not leave that state, though its desired state
65  * may still be set. (Note that pinning prevents, but never causes, state transition).
66  *
67  * The priority of the different state deciders is:
68  *  - pins
69  *  - force stop flag
70  *  - desired state (which is manipulated by require/release operations)
71  *
72  * So a forced stop cannot occur until the service is not pinned started, for instance.
73  *
74  * Two-phase transition
75  * --------------------
76  * Transition between states occurs in two phases: propagation and execution. In both phases
77  * a linked-list queue is used to keep track of which services need processing; this avoids
78  * recursion (which would be of unknown depth and therefore liable to stack overflow).
79  *
80  * In the propagation phase, acquisition/release messages are processed, and desired state may be
81  * altered accordingly. Start and stop requests are also propagated in this phase. The state may
82  * be set to STARTING or STOPPING to reflect the desired state, but will never be set to STARTED
83  * or STOPPED (that happens in the execution phase).
84  *
85  * Propagation variables:
86  *   prop_acquire:  the service has transitioned to an acquired state and must issue an acquire
87  *                  on its dependencies
88  *   prop_release:  the service has transitioned to a released state and must issue a release on
89  *                  its dependencies.
90  *
91  *   prop_start:    the service should start
92  *   prop_stop:     the service should stop
93  *
94  * Note that "prop_acquire"/"prop_release" form a pair which cannot both be set at the same time
95  * which is enforced via explicit checks. For "prop_start"/"prop_stop" this occurs implicitly.
96  *
97  * In the execution phase, actions are taken to achieve the desired state. Actual state may
98  * transition according to the current and desired states. Processes can be sent signals, etc
99  * in order to stop them. A process can restart if it stops, but it does so by raising prop_start
100  * which needs to be processed in a second transition phase. Seeing as starting never causes
101  * another process to stop, the transition-execute-transition cycle always ends at the 2nd
102  * transition stage, at the latest.
103  */
104
105 struct onstart_flags_t {
106     bool rw_ready : 1;  // file system should be writable once this service starts
107     bool log_ready : 1; // syslog should be available once this service starts
108     
109     // Not actually "onstart" commands:
110     bool no_sigterm : 1;  // do not send SIGTERM
111     bool runs_on_console : 1;  // run "in the foreground"
112     bool starts_on_console : 1; // starts in the foreground
113     bool pass_cs_fd : 1;  // pass this service a control socket connection via fd
114     
115     onstart_flags_t() noexcept : rw_ready(false), log_ready(false),
116             no_sigterm(false), runs_on_console(false), starts_on_console(false), pass_cs_fd(false)
117     {
118     }
119 };
120
121 // Exception while loading a service
122 class service_load_exc
123 {
124     public:
125     std::string serviceName;
126     std::string excDescription;
127     
128     protected:
129     service_load_exc(std::string serviceName, std::string &&desc) noexcept
130         : serviceName(serviceName), excDescription(std::move(desc))
131     {
132     }
133 };
134
135 class service_not_found : public service_load_exc
136 {
137     public:
138     service_not_found(std::string serviceName) noexcept
139         : service_load_exc(serviceName, "Service description not found.")
140     {
141     }
142 };
143
144 class service_cyclic_dependency : public service_load_exc
145 {
146     public:
147     service_cyclic_dependency(std::string serviceName) noexcept
148         : service_load_exc(serviceName, "Has cyclic dependency.")
149     {
150     }
151 };
152
153 class service_description_exc : public service_load_exc
154 {
155     public:
156     service_description_exc(std::string serviceName, std::string &&extraInfo) noexcept
157         : service_load_exc(serviceName, std::move(extraInfo))
158     {
159     }    
160 };
161
162 class service_record;
163 class service_set;
164 class base_process_service;
165
166 enum class dependency_type
167 {
168     REGULAR,
169     SOFT,       // dependency starts in parallel, failure/stop does not affect dependent
170     WAITS_FOR,  // as for SOFT, but dependent waits until dependency starts/fails before starting
171     MILESTONE   // dependency must start successfully, but once started the dependency becomes soft
172 };
173
174 /* Service dependency record */
175 class service_dep
176 {
177     service_record * from;
178     service_record * to;
179
180     public:
181     /* Whether the 'from' service is waiting for the 'to' service to start */
182     bool waiting_on;
183     /* Whether the 'from' service is holding an acquire on the 'to' service */
184     bool holding_acq;
185
186     const dependency_type dep_type;
187
188     service_dep(service_record * from, service_record * to, dependency_type dep_type_p) noexcept
189             : from(from), to(to), waiting_on(false), holding_acq(false), dep_type(dep_type_p)
190     {  }
191
192     service_record * get_from() noexcept
193     {
194         return from;
195     }
196
197     service_record * get_to() noexcept
198     {
199         return to;
200     }
201 };
202
203 /* preliminary service dependency information */
204 class prelim_dep
205 {
206     public:
207     service_record * const to;
208     dependency_type const dep_type;
209
210     prelim_dep(service_record *to_p, dependency_type dep_type_p) : to(to_p), dep_type(dep_type_p)
211     {
212         //
213     }
214 };
215
216 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
217 // store a null terminator for the argument. Return a `char *` vector containing the beginning
218 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
219 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
220 {
221     std::vector<const char *> r;
222     r.reserve(arg_indices.size() + 1);
223
224     // First store nul terminator for each part:
225     for (auto index_pair : arg_indices) {
226         if (index_pair.second < s.length()) {
227             s[index_pair.second] = 0;
228         }
229     }
230
231     // Now we can get the C string (c_str) and store offsets into it:
232     const char * cstr = s.c_str();
233     for (auto index_pair : arg_indices) {
234         r.push_back(cstr + index_pair.first);
235     }
236     r.push_back(nullptr);
237     return r;
238 }
239
240 class service_child_watcher : public eventloop_t::child_proc_watcher_impl<service_child_watcher>
241 {
242     public:
243     base_process_service * service;
244     rearm status_change(eventloop_t &eloop, pid_t child, int status) noexcept;
245     
246     service_child_watcher(base_process_service * sr) noexcept : service(sr) { }
247 };
248
249 // Watcher for the pipe used to receive exec() failure status errno
250 class exec_status_pipe_watcher : public eventloop_t::fd_watcher_impl<exec_status_pipe_watcher>
251 {
252     public:
253     base_process_service * service;
254     rearm fd_event(eventloop_t &eloop, int fd, int flags) noexcept;
255     
256     exec_status_pipe_watcher(base_process_service * sr) noexcept : service(sr) { }
257 };
258
259 // service_record: base class for service record containing static information
260 // and current state of each service.
261 //
262 // This abstract base class defines the dependency behaviour of services. The actions to actually bring a
263 // service up or down are specified by subclasses in the virtual methods (see especially bring_up() and
264 // bring_down()).
265 //
266 class service_record
267 {
268     protected:
269     using string = std::string;
270     
271     private:
272     string service_name;
273     service_type_t record_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
274     service_state_t service_state = service_state_t::STOPPED; /* service_state_t::STOPPED, STARTING, STARTED, STOPPING */
275     service_state_t desired_state = service_state_t::STOPPED; /* service_state_t::STOPPED / STARTED */
276
277     protected:
278     string pid_file;
279     
280     onstart_flags_t onstart_flags;
281
282     string logfile;           // log file name, empty string specifies /dev/null
283     
284     bool auto_restart : 1;    // whether to restart this (process) if it dies unexpectedly
285     bool smooth_recovery : 1; // whether the service process can restart without bringing down service
286     
287     bool pinned_stopped : 1;
288     bool pinned_started : 1;
289     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
290                                 // if STOPPING, whether we are waiting for dependents to stop
291     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
292     bool start_explicit : 1;    // whether we are are explicitly required to be started
293
294     bool prop_require : 1;      // require must be propagated
295     bool prop_release : 1;      // release must be propagated
296     bool prop_failure : 1;      // failure to start must be propagated
297     bool prop_start   : 1;
298     bool prop_stop    : 1;
299
300     bool restarting   : 1;      // re-starting after unexpected termination
301     
302     int required_by = 0;        // number of dependents wanting this service to be started
303
304     // list of dependencies
305     typedef std::list<service_dep> dep_list;
306     
307     // list of dependents
308     typedef std::list<service_dep *> dpt_list;
309     
310     dep_list depends_on;  // services this one depends on
311     dpt_list dependents;  // services depending on this one
312     
313     service_set *services; // the set this service belongs to
314     
315     std::unordered_set<service_listener *> listeners;
316     
317     // Process services:
318     bool force_stop; // true if the service must actually stop. This is the
319                      // case if for example the process dies; the service,
320                      // and all its dependencies, MUST be stopped.
321     
322     int term_signal = -1;  // signal to use for process termination
323     
324     string socket_path; // path to the socket for socket-activation service
325     int socket_perms;   // socket permissions ("mode")
326     uid_t socket_uid = -1;  // socket user id or -1
327     gid_t socket_gid = -1;  // socket group id or -1
328
329     // Implementation details
330     
331     pid_t pid = -1;  // PID of the process. If state is STARTING or STOPPING,
332                      //   this is PID of the service script; otherwise it is the
333                      //   PID of the process itself (process service).
334     int exit_status; // Exit status, if the process has exited (pid == -1).
335     int socket_fd = -1;  // For socket-activation services, this is the file
336                          // descriptor for the socket.
337     
338     // Data for use by service_set
339     public:
340     
341     // Console queue.
342     lld_node<service_record> console_queue_node;
343     
344     // Propagation and start/stop queues
345     lls_node<service_record> prop_queue_node;
346     lls_node<service_record> stop_queue_node;
347     
348     protected:
349     
350     // stop immediately
351     void emergency_stop() noexcept;
352     
353     // Service has actually stopped (includes having all dependents
354     // reaching STOPPED state).
355     void stopped() noexcept;
356     
357     // Service has successfully started
358     void started() noexcept;
359     
360     // Service failed to start (only called when in STARTING state).
361     //   dep_failed: whether failure is recorded due to a dependency failing
362     void failed_to_start(bool dep_failed = false) noexcept;
363
364     void run_child_proc(const char * const *args, const char *logfile, bool on_console, int wpipefd,
365             int csfd) noexcept;
366     
367     // A dependency has reached STARTED state
368     void dependency_started() noexcept;
369     
370     void all_deps_started(bool haveConsole = false) noexcept;
371
372     // Open the activation socket, return false on failure
373     bool open_socket() noexcept;
374
375     // Start all dependencies, return true if all have started
376     bool start_check_dependencies() noexcept;
377
378     // Check whether all dependencies have started (i.e. whether we can start now)
379     bool check_deps_started() noexcept;
380
381     // Whether a STOPPING service can immediately transition to STARTED.
382     bool can_interrupt_stop() noexcept
383     {
384         return waiting_for_deps && ! force_stop;
385     }
386
387     // A dependent has reached STOPPED state
388     void dependent_stopped() noexcept;
389
390     // check if all dependents have stopped
391     bool stop_check_dependents() noexcept;
392     
393     // issue a stop to all dependents, return true if they are all already stopped
394     bool stop_dependents() noexcept;
395     
396     void require() noexcept;
397     void release() noexcept;
398     void release_dependencies() noexcept;
399     
400     // Check if service is, fundamentally, stopped.
401     bool is_stopped() noexcept
402     {
403         return service_state == service_state_t::STOPPED
404             || (service_state == service_state_t::STARTING && waiting_for_deps);
405     }
406     
407     void notify_listeners(service_event_t event) noexcept
408     {
409         for (auto l : listeners) {
410             l->service_event(this, event);
411         }
412     }
413     
414     // Queue to run on the console. 'acquired_console()' will be called when the console is available.
415     // Has no effect if the service has already queued for console.
416     void queue_for_console() noexcept;
417     
418     // Release console (console must be currently held by this service)
419     void release_console() noexcept;
420     
421     bool do_auto_restart() noexcept;
422
423     // Started state reached
424     bool process_started() noexcept;
425
426     // Called on transition of desired state from stopped to started (or unpinned stop)
427     void do_start() noexcept;
428
429     // Called on transition of desired state from started to stopped (or unpinned start)
430     void do_stop() noexcept;
431
432     // Set the service state
433     void set_state(service_state_t new_state) noexcept
434     {
435         service_state = new_state;
436     }
437
438     // Virtual functions, to be implemented by service implementations:
439
440     // Do any post-dependency startup; return false on failure
441     virtual bool bring_up() noexcept;
442
443     // All dependents have stopped, and this service should proceed to stop.
444     virtual void bring_down() noexcept;
445
446     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
447     // having to wait for it reach STARTED and then go through STOPPING).
448     virtual bool can_interrupt_start() noexcept
449     {
450         return waiting_for_deps;
451     }
452
453     // Whether a STARTING service can transition to its STARTED state, once all
454     // dependencies have started.
455     virtual bool can_proceed_to_start() noexcept
456     {
457         return true;
458     }
459
460     // Interrupt startup. Returns true if service start is fully cancelled; returns false if cancel order
461     // issued but service has not yet responded (state will be set to STOPPING).
462     virtual bool interrupt_start() noexcept;
463
464     public:
465
466     service_record(service_set *set, string name)
467         : service_state(service_state_t::STOPPED), desired_state(service_state_t::STOPPED),
468             auto_restart(false), smooth_recovery(false),
469             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
470             waiting_for_execstat(false), start_explicit(false),
471             prop_require(false), prop_release(false), prop_failure(false),
472             prop_start(false), prop_stop(false), restarting(false), force_stop(false)
473     {
474         services = set;
475         service_name = name;
476         record_type = service_type_t::DUMMY;
477         socket_perms = 0;
478         exit_status = 0;
479     }
480
481     service_record(service_set *set, string name, service_type_t record_type_p,
482             const std::list<prelim_dep> &deplist_p)
483         : service_record(set, name)
484     {
485         services = set;
486         service_name = name;
487         this->record_type = record_type_p;
488
489         for (auto & pdep : deplist_p) {
490             auto b = depends_on.emplace(depends_on.end(), this, pdep.to, pdep.dep_type);
491             pdep.to->dependents.push_back(&(*b));
492         }
493     }
494
495     virtual ~service_record() noexcept
496     {
497     }
498     
499     // Get the type of this service record
500     service_type_t get_type() noexcept
501     {
502         return record_type;
503     }
504
505     // begin transition from stopped to started state or vice versa depending on current and desired state
506     void execute_transition() noexcept;
507     
508     void do_propagation() noexcept;
509
510     // Console is available.
511     void acquired_console() noexcept;
512     
513     // Get the target (aka desired) state.
514     service_state_t get_target_state() noexcept
515     {
516         return desired_state;
517     }
518
519     // Set logfile, should be done before service is started
520     void set_log_file(string logfile)
521     {
522         this->logfile = logfile;
523     }
524     
525     // Set whether this service should automatically restart when it dies
526     void set_auto_restart(bool auto_restart) noexcept
527     {
528         this->auto_restart = auto_restart;
529     }
530     
531     void set_smooth_recovery(bool smooth_recovery) noexcept
532     {
533         this->smooth_recovery = smooth_recovery;
534     }
535     
536     // Set "on start" flags (commands)
537     void set_flags(onstart_flags_t flags) noexcept
538     {
539         this->onstart_flags = flags;
540     }
541     
542     // Set an additional signal (other than SIGTERM) to be used to terminate the process
543     void set_extra_termination_signal(int signo) noexcept
544     {
545         this->term_signal = signo;
546     }
547     
548     void set_pid_file(string &&pid_file) noexcept
549     {
550         this->pid_file = std::move(pid_file);
551     }
552     
553     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
554     {
555         this->socket_path = std::move(socket_path);
556         this->socket_perms = socket_perms;
557         this->socket_uid = socket_uid;
558         this->socket_gid = socket_gid;
559     }
560
561     const std::string &get_name() const noexcept { return service_name; }
562     service_state_t get_state() const noexcept { return service_state; }
563     
564     void start(bool activate = true) noexcept;  // start the service
565     void stop(bool bring_down = true) noexcept;   // stop the service
566     
567     void forced_stop() noexcept; // force-stop this service and all dependents
568     
569     // Pin the service in "started" state (when it reaches the state)
570     void pin_start() noexcept
571     {
572         pinned_started = true;
573     }
574     
575     // Pin the service in "stopped" state (when it reaches the state)
576     void pin_stop() noexcept
577     {
578         pinned_stopped = true;
579     }
580     
581     // Remove both "started" and "stopped" pins. If the service is currently pinned
582     // in either state but would naturally be in the opposite state, it will immediately
583     // commence starting/stopping.
584     void unpin() noexcept;
585     
586     bool isDummy() noexcept
587     {
588         return record_type == service_type_t::DUMMY;
589     }
590     
591     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
592     void addListener(service_listener * listener)
593     {
594         listeners.insert(listener);
595     }
596     
597     // Remove a listener.    
598     void removeListener(service_listener * listener) noexcept
599     {
600         listeners.erase(listener);
601     }
602 };
603
604 class base_process_service;
605
606 // A timer for process restarting. Used to ensure a minimum delay between process restarts (and
607 // also for timing service stop before the SIGKILL hammer is used).
608 class process_restart_timer : public eventloop_t::timer_impl<process_restart_timer>
609 {
610     public:
611     base_process_service * service;
612
613     process_restart_timer(base_process_service *service_p)
614         : service(service_p)
615     {
616     }
617
618     rearm timer_expiry(eventloop_t &, int expiry_count);
619 };
620
621 class base_process_service : public service_record
622 {
623     friend class service_child_watcher;
624     friend class exec_status_pipe_watcher;
625     friend class process_restart_timer;
626
627     private:
628     // Re-launch process
629     void do_restart() noexcept;
630
631     protected:
632     string program_name;          // storage for program/script and arguments
633     std::vector<const char *> exec_arg_parts; // pointer to each argument/part of the program_name, and nullptr
634
635     string stop_command;          // storage for stop program/script and arguments
636     std::vector<const char *> stop_arg_parts; // pointer to each argument/part of the stop_command, and nullptr
637
638     service_child_watcher child_listener;
639     exec_status_pipe_watcher child_status_listener;
640     process_restart_timer restart_timer;
641     time_val last_start_time;
642
643     // Restart interval time and restart count are used to track the number of automatic restarts
644     // over an interval. Too many restarts over an interval will inhibit further restarts.
645     time_val restart_interval_time;  // current restart interval
646     int restart_interval_count;      // count of restarts within current interval
647
648     time_val restart_interval;       // maximum restart interval
649     int max_restart_interval_count;  // number of restarts allowed over maximum interval
650     time_val restart_delay;          // delay between restarts
651
652     // Time allowed for service stop, after which SIGKILL is sent. 0 to disable.
653     time_val stop_timeout = {10, 0}; // default of 10 seconds
654
655     // Time allowed for service start, after which SIGINT is sent (and then SIGKILL after
656     // <stop_timeout>). 0 to disable.
657     time_val start_timeout = {60, 0}; // default of 1 minute
658
659     bool waiting_restart_timer : 1;
660     bool stop_timer_armed : 1;
661     bool reserved_child_watch : 1;
662     bool tracking_child : 1;  // whether we expect to see child process status
663     bool start_is_interruptible : 1;  // whether we can interrupt start
664
665     // Launch the process with the given arguments, return true on success
666     bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
667
668     // Restart the process (due to start failure or unexpected termination). Restarts will be
669     // rate-limited.
670     bool restart_ps_process() noexcept;
671
672     // Perform smooth recovery process
673     void do_smooth_recovery() noexcept;
674
675     // Start the process, return true on success
676     virtual bool bring_up() noexcept override;
677
678     virtual void bring_down() noexcept override;
679
680     // Called when the process exits. The exit_status is the status value yielded by
681     // the "wait" system call.
682     virtual void handle_exit_status(int exit_status) noexcept = 0;
683
684     // Called if an exec fails.
685     virtual void exec_failed(int errcode) noexcept = 0;
686
687     virtual bool can_interrupt_start() noexcept override
688     {
689         return waiting_restart_timer || start_is_interruptible || service_record::can_interrupt_start();
690     }
691
692     virtual bool can_proceed_to_start() noexcept override
693     {
694         return ! waiting_restart_timer;
695     }
696
697     virtual bool interrupt_start() noexcept override;
698
699     // Kill with SIGKILL
700     void kill_with_fire() noexcept;
701
702     // Signal the process group of the service process
703     void kill_pg(int signo) noexcept;
704
705     public:
706     base_process_service(service_set *sset, string name, service_type_t record_type_p, string &&command,
707             std::list<std::pair<unsigned,unsigned>> &command_offsets,
708             const std::list<prelim_dep> &deplist_p);
709
710     ~base_process_service() noexcept
711     {
712     }
713
714     // Set the stop command and arguments (may throw std::bad_alloc)
715     void set_stop_command(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
716     {
717         stop_command = command;
718         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
719     }
720
721     void set_restart_interval(timespec interval, int max_restarts) noexcept
722     {
723         restart_interval = interval;
724         max_restart_interval_count = max_restarts;
725     }
726
727     void set_restart_delay(timespec delay) noexcept
728     {
729         restart_delay = delay;
730     }
731
732     void set_stop_timeout(timespec timeout) noexcept
733     {
734         stop_timeout = timeout;
735     }
736
737     void set_start_timeout(timespec timeout) noexcept
738     {
739         start_timeout = timeout;
740     }
741
742     void set_start_interruptible(bool value) noexcept
743     {
744         start_is_interruptible = value;
745     }
746 };
747
748 class process_service : public base_process_service
749 {
750     virtual void handle_exit_status(int exit_status) noexcept override;
751     virtual void exec_failed(int errcode) noexcept override;
752     virtual void bring_down() noexcept override;
753
754     public:
755     process_service(service_set *sset, string name, string &&command,
756             std::list<std::pair<unsigned,unsigned>> &command_offsets,
757             std::list<prelim_dep> depends_p)
758          : base_process_service(sset, name, service_type_t::PROCESS, std::move(command), command_offsets,
759              depends_p)
760     {
761     }
762
763     ~process_service() noexcept
764     {
765     }
766 };
767
768 class bgproc_service : public base_process_service
769 {
770     virtual void handle_exit_status(int exit_status) noexcept override;
771     virtual void exec_failed(int errcode) noexcept override;
772
773     enum class pid_result_t {
774         OK,
775         FAILED,      // failed to read pid or read invalid pid
776         TERMINATED   // read pid successfully, but the process already terminated
777     };
778
779     // Read the pid-file, return false on failure
780     pid_result_t read_pid_file(int *exit_status) noexcept;
781
782     public:
783     bgproc_service(service_set *sset, string name, string &&command,
784             std::list<std::pair<unsigned,unsigned>> &command_offsets,
785             std::list<prelim_dep> depends_p)
786          : base_process_service(sset, name, service_type_t::BGPROCESS, std::move(command), command_offsets,
787              depends_p)
788     {
789     }
790
791     ~bgproc_service() noexcept
792     {
793     }
794 };
795
796 class scripted_service : public base_process_service
797 {
798     virtual void handle_exit_status(int exit_status) noexcept override;
799     virtual void exec_failed(int errcode) noexcept override;
800     virtual void bring_down() noexcept override;
801
802     virtual bool interrupt_start() noexcept override
803     {
804         // if base::interrupt_start() returns false, then start hasn't been fully interrupted, but an
805         // interrupt has been issued:
806         interrupting_start = ! base_process_service::interrupt_start();
807         return ! interrupting_start;
808     }
809
810     bool interrupting_start : 1;  // running start script (true) or stop script (false)
811
812     public:
813     scripted_service(service_set *sset, string name, string &&command,
814             std::list<std::pair<unsigned,unsigned>> &command_offsets,
815             std::list<prelim_dep> depends_p)
816          : base_process_service(sset, name, service_type_t::SCRIPTED, std::move(command), command_offsets,
817              depends_p), interrupting_start(false)
818     {
819     }
820
821     ~scripted_service() noexcept
822     {
823     }
824 };
825
826 inline auto extract_prop_queue(service_record *sr) -> decltype(sr->prop_queue_node) &
827 {
828     return sr->prop_queue_node;
829 }
830
831 inline auto extract_stop_queue(service_record *sr) -> decltype(sr->stop_queue_node) &
832 {
833     return sr->stop_queue_node;
834 }
835
836 inline auto extract_console_queue(service_record *sr) -> decltype(sr->console_queue_node) &
837 {
838     return sr->console_queue_node;
839 }
840
841 /*
842  * A service_set, as the name suggests, manages a set of services.
843  *
844  * Other than the ability to find services by name, the service set manages various queues.
845  * One is the queue for processes wishing to acquire the console. There is also a set of
846  * processes that want to start, and another set of those that want to stop. These latter
847  * two "queues" (not really queues since their order is not important) are used to prevent too
848  * much recursion and to prevent service states from "bouncing" too rapidly.
849  * 
850  * A service that wishes to start or stop puts itself on the start/stop queue; a service that
851  * needs to propagate changes to dependent services or dependencies puts itself on the
852  * propagation queue. Any operation that potentially manipulates the queues must be followed
853  * by a "process queues" order (processQueues() method).
854  *
855  * Note that processQueues always repeatedly processes both queues until they are empty. The
856  * process is finite because starting a service can never cause services to stop, unless they
857  * fail to start, which should cause them to stop semi-permanently.
858  */
859 class service_set
860 {
861     protected:
862     int active_services;
863     std::list<service_record *> records;
864     bool restart_enabled; // whether automatic restart is enabled (allowed)
865     
866     shutdown_type_t shutdown_type = shutdown_type_t::CONTINUE;  // Shutdown type, if stopping
867     
868     // Services waiting for exclusive access to the console
869     dlist<service_record, extract_console_queue> console_queue;
870
871     // Propagation and start/stop "queues" - list of services waiting for processing
872     slist<service_record, extract_prop_queue> prop_queue;
873     slist<service_record, extract_stop_queue> stop_queue;
874     
875     public:
876     service_set()
877     {
878         active_services = 0;
879         restart_enabled = true;
880     }
881     
882     virtual ~service_set()
883     {
884         for (auto * s : records) {
885             delete s;
886         }
887     }
888
889     // Start the specified service. The service will be marked active.
890     void start_service(service_record *svc)
891     {
892         svc->start();
893         process_queues();
894     }
895
896     // Stop the specified service. Its active mark will be cleared.
897     void stop_service(service_record *svc)
898     {
899         svc->stop(true);
900         process_queues();
901     }
902
903     // Locate an existing service record.
904     service_record *find_service(const std::string &name) noexcept;
905
906     // Load a service description, and dependencies, if there is no existing
907     // record for the given name.
908     // Throws:
909     //   ServiceLoadException (or subclass) on problem with service description
910     //   std::bad_alloc on out-of-memory condition
911     virtual service_record *load_service(const char *name)
912     {
913         auto r = find_service(name);
914         if (r == nullptr) {
915             throw service_not_found(name);
916         }
917         return r;
918     }
919
920     // Start the service with the given name. The named service will begin
921     // transition to the 'started' state.
922     //
923     // Throws a ServiceLoadException (or subclass) if the service description
924     // cannot be loaded or is invalid;
925     // Throws std::bad_alloc if out of memory.
926     void start_service(const char *name)
927     {
928         using namespace std;
929         service_record *record = load_service(name);
930         service_set::start_service(record);
931     }
932     
933     void add_service(service_record *svc)
934     {
935         records.push_back(svc);
936     }
937     
938     void remove_service(service_record *svc)
939     {
940         std::remove(records.begin(), records.end(), svc);
941     }
942
943     // Get the list of all loaded services.
944     const std::list<service_record *> &list_services() noexcept
945     {
946         return records;
947     }
948     
949     // Stop the service with the given name. The named service will begin
950     // transition to the 'stopped' state.
951     void stop_service(const std::string &name) noexcept;
952     
953     // Add a service record to the state propagation queue. The service record will have its
954     // do_propagation() method called when the queue is processed.
955     void add_prop_queue(service_record *service) noexcept
956     {
957         if (! prop_queue.is_queued(service)) {
958             prop_queue.insert(service);
959         }
960     }
961     
962     // Add a service record to the stop queue. The service record will have its
963     // execute_transition() method called when the queue is processed.
964     void add_transition_queue(service_record *service) noexcept
965     {
966         if (! stop_queue.is_queued(service)) {
967             stop_queue.insert(service);
968         }
969     }
970     
971     // Process state propagation and start/stop queues, until they are empty.
972     void process_queues() noexcept
973     {
974         while (! stop_queue.is_empty() || ! prop_queue.is_empty()) {
975             while (! prop_queue.is_empty()) {
976                 auto next = prop_queue.pop_front();
977                 next->do_propagation();
978             }
979             while (! stop_queue.is_empty()) {
980                 auto next = stop_queue.pop_front();
981                 next->execute_transition();
982             }
983         }
984     }
985     
986     // Set the console queue tail (returns previous tail)
987     void append_console_queue(service_record * newTail) noexcept
988     {
989         bool was_empty = console_queue.is_empty();
990         console_queue.append(newTail);
991         if (was_empty) {
992             enable_console_log(false);
993         }
994     }
995     
996     // Pull and dispatch a waiter from the console queue
997     void pull_console_queue() noexcept
998     {
999         if (console_queue.is_empty()) {
1000             enable_console_log(true);
1001         }
1002         else {
1003             service_record * front = console_queue.pop_front();
1004             front->acquired_console();
1005         }
1006     }
1007     
1008     void unqueue_console(service_record * service) noexcept
1009     {
1010         if (console_queue.is_queued(service)) {
1011             console_queue.unlink(service);
1012         }
1013     }
1014
1015     // Notification from service that it is active (state != STOPPED)
1016     // Only to be called on the transition from inactive to active.
1017     void service_active(service_record *) noexcept;
1018     
1019     // Notification from service that it is inactive (STOPPED)
1020     // Only to be called on the transition from active to inactive.
1021     void service_inactive(service_record *) noexcept;
1022     
1023     // Find out how many services are active (starting, running or stopping,
1024     // but not stopped).
1025     int count_active_services() noexcept
1026     {
1027         return active_services;
1028     }
1029     
1030     void stop_all_services(shutdown_type_t type = shutdown_type_t::HALT) noexcept
1031     {
1032         restart_enabled = false;
1033         shutdown_type = type;
1034         for (std::list<service_record *>::iterator i = records.begin(); i != records.end(); ++i) {
1035             (*i)->stop(false);
1036             (*i)->unpin();
1037         }
1038         process_queues();
1039     }
1040     
1041     void set_auto_restart(bool restart) noexcept
1042     {
1043         restart_enabled = restart;
1044     }
1045     
1046     bool get_auto_restart() noexcept
1047     {
1048         return restart_enabled;
1049     }
1050     
1051     shutdown_type_t getShutdownType() noexcept
1052     {
1053         return shutdown_type;
1054     }
1055 };
1056
1057 class dirload_service_set : public service_set
1058 {
1059     const char *service_dir;  // directory containing service descriptions
1060
1061     public:
1062     dirload_service_set(const char *service_dir_p) : service_set(), service_dir(service_dir_p)
1063     {
1064     }
1065
1066     service_record *load_service(const char *name) override;
1067 };
1068
1069 #endif