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