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