d907b09ee2c88bc33e9cd9648884ed66d27b1d89
[oweals/dinit.git] / src / includes / 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 "dinit.h"
14 #include "control.h"
15 #include "service-listener.h"
16 #include "service-constants.h"
17 #include "dinit-ll.h"
18 #include "dinit-log.h"
19
20 /*
21  * This header defines service_record, a data record maintaining information about a service,
22  * and service_set, a set of interdependent service records. It also defines some associated
23  * types and exceptions.
24  *
25  * Service states
26  * --------------
27  * Services have both a current state and a desired state. The desired state can be
28  * either STARTED or STOPPED. The current state can also be STARTING or STOPPING.
29  * A service can be "pinned" in either the STARTED or STOPPED states to prevent it
30  * from leaving that state until it is unpinned.
31  *
32  * The total state is a combination of the two, current and desired:
33  *      STOPPED/STOPPED  : stopped and will remain stopped
34  *      STOPPED/STARTED  : stopped (pinned), must be unpinned to start
35  *      STARTING/STARTED : starting, but not yet started. Dependencies may also be starting.
36  *      STARTING/STOPPED : as above, but the service will be stopped again as soon as it has
37  *                         completed startup.
38  *      STARTED/STARTED  : running and will continue running.
39  *      STARTED/STOPPED  : started (pinned), must be unpinned to stop
40  *      STOPPING/STOPPED : stopping and will stop. Dependents may be stopping.
41  *      STOPPING/STARTED : as above, but the service will be re-started again once it stops.
42  *
43  * A scripted service is in the STARTING/STOPPING states during the script execution.
44  * A process service is in the STOPPING state when it has been signalled to stop, and is
45  * in the STARTING state when waiting for dependencies to start or for the exec() call in
46  * the forked child to complete and return a status.
47  *
48  * Acquisition/release:
49  * ------------------
50  * Each service has a dependent-count ("required_by"). This starts at 0, adds 1 if the
51  * service has explicitly been started (i.e. "start_explicit" is true), and adds 1 for
52  * each dependent service which is not STOPPED (including dependents with a soft dependency).
53  * When required_by transitions to 0, the service is stopped (unless it is pinned). When
54  * require_by transitions from 0, the service is started (unless pinned).
55  *
56  * So, in general, the dependent-count determines the desired state (STARTED if the count
57  * is greater than 0, otherwise STOPPED). However, a service can be issued a stop-and-take
58  * down order (via `stop(true)'); this will first stop dependent services, which may restart
59  * and cancel the stop of the former service. Finally, a service can be force-stopped, which
60  * means that its stop process cannot be cancelled (though it may still be put in a desired
61  * state of STARTED, meaning it will start immediately upon stopping).
62  *
63  * Pinning
64  * -------
65  * A service may be "pinned" in either STARTED or STOPPED states (or even both). Once it
66  * reaches a pinned state, a service will not leave that state, though its desired state
67  * may still be set. (Note that pinning prevents, but never causes, state transition).
68  *
69  * The priority of the different state deciders is:
70  *  - pins
71  *  - force stop flag
72  *  - desired state (which is manipulated by require/release operations)
73  *
74  * So a forced stop cannot occur until the service is not pinned started, for instance.
75  *
76  * Two-phase transition
77  * --------------------
78  * Transition between states occurs in two phases: propagation and execution. In both phases
79  * a linked-list queue is used to keep track of which services need processing; this avoids
80  * recursion (which would be of unknown depth and therefore liable to stack overflow).
81  *
82  * In the propagation phase, acquisition/release messages are processed, and desired state may be
83  * altered accordingly. Start and stop requests are also propagated in this phase. The state may
84  * be set to STARTING or STOPPING to reflect the desired state, but will never be set to STARTED
85  * or STOPPED (that happens in the execution phase).
86  *
87  * The two-phase transition is needed to avoid problem where a service that becomes STOPPED has
88  * an incorrect acquisition count, which may cause it to restart when it should not. The
89  * propagation phase allows the acquisition count to settle before the transition to the STOPPED
90  * state occurs, and the decision whether to restart can then be made based on the (correct)
91  * acquisition count.
92  *
93  * Propagation variables:
94  *   prop_acquire:  the service has transitioned to an acquired state and must issue an acquire
95  *                  on its dependencies
96  *   prop_release:  the service has transitioned to a released state and must issue a release on
97  *                  its dependencies.
98  *
99  *   prop_start:    the service should start
100  *   prop_stop:     the service should stop
101  *
102  * Note that "prop_acquire"/"prop_release" form a pair which cannot both be set at the same time
103  * which is enforced via explicit checks. For "prop_start"/"prop_stop" this occurs implicitly.
104  *
105  * In the execution phase, actions are taken to achieve the desired state. Actual state may
106  * transition according to the current and desired states. Processes can be sent signals, etc
107  * in order to stop them. A process can restart if it stops, but it does so by raising prop_start
108  * which needs to be processed in a second transition phase. Seeing as starting never causes
109  * another process to stop, the transition-execute-transition cycle always ends at the 2nd
110  * transition stage, at the latest.
111  */
112
113 struct onstart_flags_t {
114     bool rw_ready : 1;  // file system should be writable once this service starts
115     bool log_ready : 1; // syslog should be available once this service starts
116     
117     // Not actually "onstart" commands:
118     bool no_sigterm : 1;  // do not send SIGTERM
119     bool runs_on_console : 1;  // run "in the foreground"
120     bool starts_on_console : 1; // starts in the foreground
121     bool pass_cs_fd : 1;  // pass this service a control socket connection via fd
122     
123     onstart_flags_t() noexcept : rw_ready(false), log_ready(false),
124             no_sigterm(false), runs_on_console(false), starts_on_console(false), pass_cs_fd(false)
125     {
126     }
127 };
128
129 // Exception while loading a service
130 class service_load_exc
131 {
132     public:
133     std::string serviceName;
134     std::string excDescription;
135     
136     protected:
137     service_load_exc(std::string serviceName, std::string &&desc) noexcept
138         : serviceName(serviceName), excDescription(std::move(desc))
139     {
140     }
141 };
142
143 class service_not_found : public service_load_exc
144 {
145     public:
146     service_not_found(std::string serviceName) noexcept
147         : service_load_exc(serviceName, "Service description not found.")
148     {
149     }
150 };
151
152 class service_cyclic_dependency : public service_load_exc
153 {
154     public:
155     service_cyclic_dependency(std::string serviceName) noexcept
156         : service_load_exc(serviceName, "Has cyclic dependency.")
157     {
158     }
159 };
160
161 class service_description_exc : public service_load_exc
162 {
163     public:
164     service_description_exc(std::string serviceName, std::string &&extraInfo) noexcept
165         : service_load_exc(serviceName, std::move(extraInfo))
166     {
167     }    
168 };
169
170 class service_record;
171 class service_set;
172 class base_process_service;
173
174 enum class dependency_type
175 {
176     REGULAR,
177     SOFT,       // dependency starts in parallel, failure/stop does not affect dependent
178     WAITS_FOR,  // as for SOFT, but dependent waits until dependency starts/fails before starting
179     MILESTONE   // dependency must start successfully, but once started the dependency becomes soft
180 };
181
182 /* Service dependency record */
183 class service_dep
184 {
185     service_record * from;
186     service_record * to;
187
188     public:
189     /* Whether the 'from' service is waiting for the 'to' service to start */
190     bool waiting_on;
191     /* Whether the 'from' service is holding an acquire on the 'to' service */
192     bool holding_acq;
193
194     const dependency_type dep_type;
195
196     service_dep(service_record * from, service_record * to, dependency_type dep_type_p) noexcept
197             : from(from), to(to), waiting_on(false), holding_acq(false), dep_type(dep_type_p)
198     {  }
199
200     service_record * get_from() noexcept
201     {
202         return from;
203     }
204
205     service_record * get_to() noexcept
206     {
207         return to;
208     }
209 };
210
211 /* preliminary service dependency information */
212 class prelim_dep
213 {
214     public:
215     service_record * const to;
216     dependency_type const dep_type;
217
218     prelim_dep(service_record *to_p, dependency_type dep_type_p) : to(to_p), dep_type(dep_type_p)
219     {
220         //
221     }
222 };
223
224 class service_child_watcher : public eventloop_t::child_proc_watcher_impl<service_child_watcher>
225 {
226     public:
227     base_process_service * service;
228     dasynq::rearm status_change(eventloop_t &eloop, pid_t child, int status) noexcept;
229     
230     service_child_watcher(base_process_service * sr) noexcept : service(sr) { }
231 };
232
233 // Watcher for the pipe used to receive exec() failure status errno
234 class exec_status_pipe_watcher : public eventloop_t::fd_watcher_impl<exec_status_pipe_watcher>
235 {
236     public:
237     base_process_service * service;
238     dasynq::rearm fd_event(eventloop_t &eloop, int fd, int flags) noexcept;
239     
240     exec_status_pipe_watcher(base_process_service * sr) noexcept : service(sr) { }
241 };
242
243 // service_record: base class for service record containing static information
244 // and current state of each service.
245 //
246 // This abstract base class defines the dependency behaviour of services. The actions to actually bring a
247 // service up or down are specified by subclasses in the virtual methods (see especially bring_up() and
248 // bring_down()).
249 //
250 class service_record
251 {
252     protected:
253     using string = std::string;
254     using time_val = dasynq::time_val;
255     
256     private:
257     string service_name;
258     service_type_t record_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
259     service_state_t service_state = service_state_t::STOPPED; /* service_state_t::STOPPED, STARTING, STARTED, STOPPING */
260     service_state_t desired_state = service_state_t::STOPPED; /* service_state_t::STOPPED / STARTED */
261
262     protected:
263     string pid_file;
264     
265     onstart_flags_t onstart_flags;
266
267     string logfile;           // log file name, empty string specifies /dev/null
268     
269     bool auto_restart : 1;    // whether to restart this (process) if it dies unexpectedly
270     bool smooth_recovery : 1; // whether the service process can restart without bringing down service
271     
272     bool pinned_stopped : 1;
273     bool pinned_started : 1;
274     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
275                                 // if STOPPING, whether we are waiting for dependents to stop
276     bool waiting_for_console : 1;   // waiting for exclusive console access (while STARTING)
277     bool have_console : 1;      // whether we have exclusive console access (STARTING/STARTED)
278     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
279     bool start_explicit : 1;    // whether we are are explicitly required to be started
280
281     bool prop_require : 1;      // require must be propagated
282     bool prop_release : 1;      // release must be propagated
283     bool prop_failure : 1;      // failure to start must be propagated
284     bool prop_start   : 1;
285     bool prop_stop    : 1;
286
287     bool restarting   : 1;      // re-starting after unexpected termination
288     
289     int required_by = 0;        // number of dependents wanting this service to be started
290
291     // list of dependencies
292     typedef std::list<service_dep> dep_list;
293     
294     // list of dependents
295     typedef std::list<service_dep *> dpt_list;
296     
297     dep_list depends_on;  // services this one depends on
298     dpt_list dependents;  // services depending on this one
299     
300     service_set *services; // the set this service belongs to
301     
302     std::unordered_set<service_listener *> listeners;
303     
304     // Process services:
305     bool force_stop; // true if the service must actually stop. This is the
306                      // case if for example the process dies; the service,
307                      // and all its dependencies, MUST be stopped.
308     
309     int term_signal = -1;  // signal to use for process termination
310     
311     string socket_path; // path to the socket for socket-activation service
312     int socket_perms;   // socket permissions ("mode")
313     uid_t socket_uid = -1;  // socket user id or -1
314     gid_t socket_gid = -1;  // socket group id or -1
315
316     // Data for use by service_set
317     public:
318     
319     // Console queue.
320     lld_node<service_record> console_queue_node;
321     
322     // Propagation and start/stop queues
323     lls_node<service_record> prop_queue_node;
324     lls_node<service_record> stop_queue_node;
325     
326     protected:
327
328     // Service has actually stopped (includes having all dependents
329     // reaching STOPPED state).
330     void stopped() noexcept;
331     
332     // Service has successfully started
333     void started() noexcept;
334     
335     // Service failed to start (only called when in STARTING state).
336     //   dep_failed: whether failure is recorded due to a dependency failing
337     //   immediate_stop: whether to set state as STOPPED and handle complete stop.
338     void failed_to_start(bool dep_failed = false, bool immediate_stop = true) noexcept;
339
340     // Run a child process (call after forking).
341     // - args specifies the program arguments including the executable (argv[0])
342     // - working_dir specifies the working directory; may be null
343     // - logfile specifies the logfile
344     // - on_console: if true, process is run with access to console
345     // - wpipefd: if the exec is unsuccessful, or another error occurs beforehand, the
346     //   error number (errno) is written to this file descriptor
347     // - csfd: the control socket fd; may be -1 to inhibit passing of control socket
348     // - socket_fd: the pre-opened socket file descriptor (may be -1)
349     // - uid/gid: the identity to run the process as (may be both -1, otherwise both must be valid)
350     void run_child_proc(const char * const *args, const char *working_dir, const char *logfile,
351             bool on_console, int wpipefd, int csfd, int socket_fd, uid_t uid, gid_t gid) noexcept;
352     
353     // A dependency has reached STARTED state
354     void dependency_started() noexcept;
355     
356     void all_deps_started() noexcept;
357
358     // Start all dependencies, return true if all have started
359     bool start_check_dependencies() noexcept;
360
361     // Check whether all dependencies have started (i.e. whether we can start now)
362     bool check_deps_started() noexcept;
363
364     // Whether a STOPPING service can immediately transition to STARTED.
365     bool can_interrupt_stop() noexcept
366     {
367         return waiting_for_deps && ! force_stop;
368     }
369
370     // A dependent has reached STOPPED state
371     void dependent_stopped() noexcept;
372
373     // check if all dependents have stopped
374     bool stop_check_dependents() noexcept;
375     
376     // issue a stop to all dependents, return true if they are all already stopped
377     bool stop_dependents() noexcept;
378     
379     void require() noexcept;
380     void release(bool issue_stop = true) noexcept;
381     void release_dependencies() noexcept;
382     
383     // Check if service is, fundamentally, stopped.
384     bool is_stopped() noexcept
385     {
386         return service_state == service_state_t::STOPPED
387             || (service_state == service_state_t::STARTING && waiting_for_deps);
388     }
389     
390     void notify_listeners(service_event_t event) noexcept
391     {
392         for (auto l : listeners) {
393             l->service_event(this, event);
394         }
395     }
396     
397     // Queue to run on the console. 'acquired_console()' will be called when the console is available.
398     // Has no effect if the service has already queued for console.
399     void queue_for_console() noexcept;
400     
401     // Release console (console must be currently held by this service)
402     void release_console() noexcept;
403     
404     bool do_auto_restart() noexcept;
405
406     // Started state reached
407     bool process_started() noexcept;
408
409     // Called on transition of desired state from stopped to started (or unpinned stop)
410     void do_start() noexcept;
411
412     // Begin stopping, release activation.
413     void do_stop() noexcept;
414
415     // Set the service state
416     void set_state(service_state_t new_state) noexcept
417     {
418         service_state = new_state;
419     }
420
421     // Virtual functions, to be implemented by service implementations:
422
423     // Do any post-dependency startup; return false on failure
424     virtual bool bring_up() noexcept;
425
426     // All dependents have stopped, and this service should proceed to stop.
427     virtual void bring_down() noexcept;
428
429     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
430     // having to wait for it reach STARTED and then go through STOPPING).
431     virtual bool can_interrupt_start() noexcept
432     {
433         return waiting_for_deps;
434     }
435
436     // Whether a STARTING service can transition to its STARTED state, once all
437     // dependencies have started.
438     virtual bool can_proceed_to_start() noexcept
439     {
440         return true;
441     }
442
443     // Interrupt startup. Returns true if service start is fully cancelled; returns false if cancel order
444     // issued but service has not yet responded (state will be set to STOPPING).
445     virtual bool interrupt_start() noexcept;
446
447     // The service is becoming inactive - i.e. it has stopped and will not be immediately restarted. Perform
448     // any appropriate cleanup.
449     virtual void becoming_inactive() noexcept { }
450
451     public:
452
453     service_record(service_set *set, string name)
454         : service_state(service_state_t::STOPPED), desired_state(service_state_t::STOPPED),
455             auto_restart(false), smooth_recovery(false),
456             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
457             waiting_for_console(false), have_console(false), waiting_for_execstat(false),
458             start_explicit(false), prop_require(false), prop_release(false), prop_failure(false),
459             prop_start(false), prop_stop(false), restarting(false), force_stop(false)
460     {
461         services = set;
462         service_name = name;
463         record_type = service_type_t::DUMMY;
464         socket_perms = 0;
465     }
466
467     service_record(service_set *set, string name, service_type_t record_type_p,
468             const std::list<prelim_dep> &deplist_p)
469         : service_record(set, name)
470     {
471         services = set;
472         service_name = name;
473         this->record_type = record_type_p;
474
475         for (auto & pdep : deplist_p) {
476             auto b = depends_on.emplace(depends_on.end(), this, pdep.to, pdep.dep_type);
477             pdep.to->dependents.push_back(&(*b));
478         }
479     }
480
481     virtual ~service_record() noexcept
482     {
483     }
484     
485     // Get the type of this service record
486     service_type_t get_type() noexcept
487     {
488         return record_type;
489     }
490
491     // begin transition from stopped to started state or vice versa depending on current and desired state
492     void execute_transition() noexcept;
493     
494     void do_propagation() noexcept;
495
496     // Console is available.
497     void acquired_console() noexcept;
498     
499     // Get the target (aka desired) state.
500     service_state_t get_target_state() noexcept
501     {
502         return desired_state;
503     }
504
505     // Set logfile, should be done before service is started
506     void set_log_file(string logfile)
507     {
508         this->logfile = logfile;
509     }
510     
511     // Set whether this service should automatically restart when it dies
512     void set_auto_restart(bool auto_restart) noexcept
513     {
514         this->auto_restart = auto_restart;
515     }
516     
517     void set_smooth_recovery(bool smooth_recovery) noexcept
518     {
519         this->smooth_recovery = smooth_recovery;
520     }
521     
522     // Set "on start" flags (commands)
523     void set_flags(onstart_flags_t flags) noexcept
524     {
525         this->onstart_flags = flags;
526     }
527
528     void set_pid_file(string &&pid_file) noexcept
529     {
530         this->pid_file = std::move(pid_file);
531     }
532     
533     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
534     {
535         this->socket_path = std::move(socket_path);
536         this->socket_perms = socket_perms;
537         this->socket_uid = socket_uid;
538         this->socket_gid = socket_gid;
539     }
540
541     const std::string &get_name() const noexcept { return service_name; }
542     service_state_t get_state() const noexcept { return service_state; }
543     
544     void start(bool activate = true) noexcept;  // start the service
545     void stop(bool bring_down = true) noexcept;   // stop the service
546     
547     void forced_stop() noexcept; // force-stop this service and all dependents
548     
549     // Pin the service in "started" state (when it reaches the state)
550     void pin_start() noexcept
551     {
552         pinned_started = true;
553     }
554     
555     // Pin the service in "stopped" state (when it reaches the state)
556     void pin_stop() noexcept
557     {
558         pinned_stopped = true;
559     }
560     
561     // Remove both "started" and "stopped" pins. If the service is currently pinned
562     // in either state but would naturally be in the opposite state, it will immediately
563     // commence starting/stopping.
564     void unpin() noexcept;
565     
566     bool is_dummy() noexcept
567     {
568         return record_type == service_type_t::DUMMY;
569     }
570     
571     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
572     void add_listener(service_listener * listener)
573     {
574         listeners.insert(listener);
575     }
576     
577     // Remove a listener.    
578     void remove_listener(service_listener * listener) noexcept
579     {
580         listeners.erase(listener);
581     }
582     
583     // Assuming there is one reference (from a control link), return true if this is the only reference,
584     // or false if there are others (including dependents).
585     bool has_lone_ref() noexcept
586     {
587         if (! dependents.empty()) return false;
588         auto i = listeners.begin();
589         return (++i == listeners.end());
590     }
591
592     // Prepare this service to be unloaded.
593     void prepare_for_unload() noexcept
594     {
595         // Remove all dependencies:
596         for (auto &dep : depends_on) {
597             auto &dep_dpts = dep.get_to()->dependents;
598             dep_dpts.erase(std::find(dep_dpts.begin(), dep_dpts.end(), &dep));
599         }
600         depends_on.clear();
601     }
602 };
603
604 inline auto extract_prop_queue(service_record *sr) -> decltype(sr->prop_queue_node) &
605 {
606     return sr->prop_queue_node;
607 }
608
609 inline auto extract_stop_queue(service_record *sr) -> decltype(sr->stop_queue_node) &
610 {
611     return sr->stop_queue_node;
612 }
613
614 inline auto extract_console_queue(service_record *sr) -> decltype(sr->console_queue_node) &
615 {
616     return sr->console_queue_node;
617 }
618
619 /*
620  * A service_set, as the name suggests, manages a set of services.
621  *
622  * Other than the ability to find services by name, the service set manages various queues.
623  * One is the queue for processes wishing to acquire the console. There is also a set of
624  * processes that want to start, and another set of those that want to stop. These latter
625  * two "queues" (not really queues since their order is not important) are used to prevent too
626  * much recursion and to prevent service states from "bouncing" too rapidly.
627  * 
628  * A service that wishes to start or stop puts itself on the start/stop queue; a service that
629  * needs to propagate changes to dependent services or dependencies puts itself on the
630  * propagation queue. Any operation that potentially manipulates the queues must be followed
631  * by a "process queues" order (processQueues() method).
632  *
633  * Note that processQueues always repeatedly processes both queues until they are empty. The
634  * process is finite because starting a service can never cause services to stop, unless they
635  * fail to start, which should cause them to stop semi-permanently.
636  */
637 class service_set
638 {
639     protected:
640     int active_services;
641     std::list<service_record *> records;
642     bool restart_enabled; // whether automatic restart is enabled (allowed)
643     
644     shutdown_type_t shutdown_type = shutdown_type_t::CONTINUE;  // Shutdown type, if stopping
645     
646     // Services waiting for exclusive access to the console
647     dlist<service_record, extract_console_queue> console_queue;
648
649     // Propagation and start/stop "queues" - list of services waiting for processing
650     slist<service_record, extract_prop_queue> prop_queue;
651     slist<service_record, extract_stop_queue> stop_queue;
652     
653     public:
654     service_set()
655     {
656         active_services = 0;
657         restart_enabled = true;
658     }
659     
660     virtual ~service_set()
661     {
662         for (auto * s : records) {
663             delete s;
664         }
665     }
666
667     // Start the specified service. The service will be marked active.
668     void start_service(service_record *svc)
669     {
670         svc->start();
671         process_queues();
672     }
673
674     // Stop the specified service. Its active mark will be cleared.
675     void stop_service(service_record *svc)
676     {
677         svc->stop(true);
678         process_queues();
679     }
680
681     // Locate an existing service record.
682     service_record *find_service(const std::string &name) noexcept;
683
684     // Load a service description, and dependencies, if there is no existing
685     // record for the given name.
686     // Throws:
687     //   ServiceLoadException (or subclass) on problem with service description
688     //   std::bad_alloc on out-of-memory condition
689     virtual service_record *load_service(const char *name)
690     {
691         auto r = find_service(name);
692         if (r == nullptr) {
693             throw service_not_found(name);
694         }
695         return r;
696     }
697
698     // Start the service with the given name. The named service will begin
699     // transition to the 'started' state.
700     //
701     // Throws a ServiceLoadException (or subclass) if the service description
702     // cannot be loaded or is invalid;
703     // Throws std::bad_alloc if out of memory.
704     void start_service(const char *name)
705     {
706         using namespace std;
707         service_record *record = load_service(name);
708         service_set::start_service(record);
709     }
710     
711     void add_service(service_record *svc)
712     {
713         records.push_back(svc);
714     }
715     
716     void remove_service(service_record *svc)
717     {
718         records.erase(std::find(records.begin(), records.end(), svc));
719     }
720
721     // Get the list of all loaded services.
722     const std::list<service_record *> &list_services() noexcept
723     {
724         return records;
725     }
726     
727     // Stop the service with the given name. The named service will begin
728     // transition to the 'stopped' state.
729     void stop_service(const std::string &name) noexcept;
730     
731     // Add a service record to the state propagation queue. The service record will have its
732     // do_propagation() method called when the queue is processed.
733     void add_prop_queue(service_record *service) noexcept
734     {
735         if (! prop_queue.is_queued(service)) {
736             prop_queue.insert(service);
737         }
738     }
739     
740     // Add a service record to the stop queue. The service record will have its
741     // execute_transition() method called when the queue is processed.
742     void add_transition_queue(service_record *service) noexcept
743     {
744         if (! stop_queue.is_queued(service)) {
745             stop_queue.insert(service);
746         }
747     }
748     
749     // Process state propagation and start/stop queues, until they are empty.
750     void process_queues() noexcept
751     {
752         while (! stop_queue.is_empty() || ! prop_queue.is_empty()) {
753             while (! prop_queue.is_empty()) {
754                 auto next = prop_queue.pop_front();
755                 next->do_propagation();
756             }
757             while (! stop_queue.is_empty()) {
758                 auto next = stop_queue.pop_front();
759                 next->execute_transition();
760             }
761         }
762     }
763     
764     // Set the console queue tail (returns previous tail)
765     void append_console_queue(service_record * newTail) noexcept
766     {
767         bool was_empty = console_queue.is_empty();
768         console_queue.append(newTail);
769         if (was_empty) {
770             enable_console_log(false);
771         }
772     }
773     
774     // Pull and dispatch a waiter from the console queue
775     void pull_console_queue() noexcept
776     {
777         if (console_queue.is_empty()) {
778             enable_console_log(true);
779         }
780         else {
781             service_record * front = console_queue.pop_front();
782             front->acquired_console();
783         }
784     }
785     
786     void unqueue_console(service_record * service) noexcept
787     {
788         if (console_queue.is_queued(service)) {
789             console_queue.unlink(service);
790         }
791     }
792
793     // Check if console queue is empty (possibly due to console already having
794     // been assigned to the only queueing service)
795     bool is_console_queue_empty() noexcept
796     {
797         return console_queue.is_empty();
798     }
799
800     // Check whether a service is queued for the console
801     bool is_queued_for_console(service_record * service) noexcept
802     {
803         return console_queue.is_queued(service);
804     }
805
806     // Notification from service that it is active (state != STOPPED)
807     // Only to be called on the transition from inactive to active.
808     void service_active(service_record *) noexcept;
809     
810     // Notification from service that it is inactive (STOPPED)
811     // Only to be called on the transition from active to inactive.
812     void service_inactive(service_record *) noexcept;
813     
814     // Find out how many services are active (starting, running or stopping,
815     // but not stopped).
816     int count_active_services() noexcept
817     {
818         return active_services;
819     }
820     
821     void stop_all_services(shutdown_type_t type = shutdown_type_t::HALT) noexcept
822     {
823         restart_enabled = false;
824         shutdown_type = type;
825         for (std::list<service_record *>::iterator i = records.begin(); i != records.end(); ++i) {
826             (*i)->stop(false);
827             (*i)->unpin();
828         }
829         process_queues();
830     }
831     
832     void set_auto_restart(bool restart) noexcept
833     {
834         restart_enabled = restart;
835     }
836     
837     bool get_auto_restart() noexcept
838     {
839         return restart_enabled;
840     }
841     
842     shutdown_type_t get_shutdown_type() noexcept
843     {
844         return shutdown_type;
845     }
846 };
847
848 // A service directory entry, tracking the directory as a nul-terminated string, which may either
849 // be static or dynamically allocated (via new char[...]).
850 class service_dir_entry
851 {
852     const char *dir;
853     bool dir_dyn_allocd;  // dynamically allocated?
854
855     public:
856     service_dir_entry(const char *dir_p, bool dir_dyn_allocd_p) :
857         dir(dir_p), dir_dyn_allocd(dir_dyn_allocd_p)
858     { }
859
860     ~service_dir_entry()
861     {
862         if (dir_dyn_allocd) {
863             delete[] dir;
864         }
865     }
866
867     const char *get_dir() const
868     {
869         return dir;
870     }
871 };
872
873 // A service set which loads services from one of several service directories.
874 class dirload_service_set : public service_set
875 {
876     std::vector<service_dir_entry> service_dirs; // directories containing service descriptions
877
878     public:
879     dirload_service_set() : service_set()
880     {
881         // nothing to do.
882     }
883
884     dirload_service_set(const dirload_service_set &) = delete;
885
886     // Construct a dirload_service_set which loads services from the specified directory. The
887     // directory specified can be dynamically allocated via "new char[...]" (dyn_allocd == true)
888     // or statically allocated.
889     dirload_service_set(const char *service_dir_p, bool dyn_allocd = false) : service_set()
890     {
891         service_dirs.emplace_back(service_dir_p, false);
892     }
893
894     // Append a directory to the list of service directories, so that it is searched last for
895     // service description files.
896     void add_service_dir(const char *service_dir_p, bool dyn_allocd = true)
897     {
898         service_dirs.emplace_back(service_dir_p, dyn_allocd);
899     }
900
901     service_record *load_service(const char *name) override;
902 };
903
904 #endif