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