70b55afd995ee5561d277f154ddd48d3f77a1d1b
[oweals/dinit.git] / src / service.h
1 #ifndef SERVICE_H
2 #define SERVICE_H
3
4 #include <string>
5 #include <list>
6 #include <vector>
7 #include <csignal>
8 #include <unordered_set>
9
10 #include "dasynq.h"
11
12 #include "control.h"
13 #include "service-listener.h"
14 #include "service-constants.h"
15
16 /*
17  * This header defines ServiceRecord, a data record maintaining information about a service,
18  * and ServiceSet, a set of interdependent service records. It also defines some associated
19  * types and exceptions.
20  *
21  * Service states
22  * --------------
23  * Services have both a current state and a desired state. The desired state can be
24  * either STARTED or STOPPED. The current state can also be STARTING or STOPPING.
25  * A service can be "pinned" in either the STARTED or STOPPED states to prevent it
26  * from leaving that state until it is unpinned.
27  *
28  * The total state is a combination of the two, current and desired:
29  *      STOPPED/STOPPED  : stopped and will remain stopped
30  *      STOPPED/STARTED  : stopped (pinned), must be unpinned to start
31  *      STARTING/STARTED : starting, but not yet started. Dependencies may also be starting.
32  *      STARTING/STOPPED : as above, but the service will be stopped again as soon as it has
33  *                         completed startup.
34  *      STARTED/STARTED  : running and will continue running.
35  *      STARTED/STOPPED  : started (pinned), must be unpinned to stop
36  *      STOPPING/STOPPED : stopping and will stop. Dependents may be stopping.
37  *      STOPPING/STARTED : as above, but the service will be re-started again once it stops.
38  *
39  * A scripted service is in the STARTING/STOPPING states during the script execution.
40  * A process service is in the STOPPING state when it has been signalled to stop, and is
41  * in the STARTING state when waiting for dependencies to start or for the exec() call in
42  * the forked child to complete and return a status.
43  *
44  * Acquisition/release:
45  * ------------------
46  * Each service has a dependent-count ("required_by"). This starts at 0, adds 1 if the
47  * service has explicitly been started (i.e. "start_explicit" is true), and adds 1 for
48  * each dependent service which is not STOPPED (including dependents with a soft dependency).
49  * When required_by transitions to 0, the service is stopped (unless it is pinned). When
50  * require_by transitions from 0, the service is started (unless pinned).
51  *
52  * So, in general, the dependent-count determines the desired state (STARTED if the count
53  * is greater than 0, otherwise STOPPED). However, a service can be issued a stop-and-take
54  * down order (via `stop(true)'); this will first stop dependent services, which may restart
55  * and cancel the stop of the former service. Finally, a service can be force-stopped, which
56  * means that its stop process cannot be cancelled (though it may still be put in a desired
57  * state of STARTED, meaning it will start immediately upon stopping).
58  *
59  * Pinning
60  * -------
61  * A service may be "pinned" in either STARTED or STOPPED states (or even both). Once it
62  * reaches a pinned state, a service will not leave that state, though its desired state
63  * may still be set. (Note that pinning prevents, but never causes, state transition).
64  *
65  * The priority of the different state deciders is:
66  *  - pins
67  *  - force stop flag
68  *  - desired state (which is manipulated by require/release operations)
69  *
70  * So a forced stop cannot occur until the service is not pinned started, for instance.
71  *
72  * Two-phase transition
73  * --------------------
74  * Transition between states occurs in two phases: propagation and execution. In the
75  * propagation phase, acquisition/release messages are processed, and desired state may be
76  * altered accordingly. Desired state of dependencies/dependents should not be examined in
77  * this phase, since it may change during the phase (i.e. its current value at any point
78  * may not reflect the true final value).
79  *
80  * In the execution phase, actions are taken to achieve the desired state. Actual state may
81  * transition according to the current and desired states.
82  */
83
84 struct OnstartFlags {
85     bool rw_ready : 1;
86     bool log_ready : 1;
87     
88     // Not actually "onstart" commands:
89     bool no_sigterm : 1;  // do not send SIGTERM
90     bool runs_on_console : 1;  // run "in the foreground"
91     bool pass_cs_fd : 1;  // pass this service a control socket connection via fd
92     
93     OnstartFlags() noexcept : rw_ready(false), log_ready(false),
94             no_sigterm(false), runs_on_console(false), pass_cs_fd(false)
95     {
96     }
97 };
98
99 // Exception while loading a service
100 class ServiceLoadExc
101 {
102     public:
103     std::string serviceName;
104     const char *excDescription;
105     
106     protected:
107     ServiceLoadExc(std::string serviceName, const char *desc) noexcept
108         : serviceName(serviceName), excDescription(desc)
109     {
110     }
111 };
112
113 class ServiceNotFound : public ServiceLoadExc
114 {
115     public:
116     ServiceNotFound(std::string serviceName) noexcept
117         : ServiceLoadExc(serviceName, "Service description not found.")
118     {
119     }
120 };
121
122 class ServiceCyclicDependency : public ServiceLoadExc
123 {
124     public:
125     ServiceCyclicDependency(std::string serviceName) noexcept
126         : ServiceLoadExc(serviceName, "Has cyclic dependency.")
127     {
128     }
129 };
130
131 class ServiceDescriptionExc : public ServiceLoadExc
132 {
133     public:
134     ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
135         : ServiceLoadExc(serviceName, extraInfo.c_str())
136     {
137     }    
138 };
139
140 class ServiceRecord;
141 class ServiceSet;
142 class base_process_service;
143
144 /* Service dependency record */
145 class ServiceDep
146 {
147     ServiceRecord * from;
148     ServiceRecord * to;
149
150     public:
151     /* Whether the 'from' service is waiting for the 'to' service to start */
152     bool waiting_on;
153     /* Whether the 'from' service is holding an acquire on the 'to' service */
154     bool holding_acq;
155
156     ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false), holding_acq(false)
157     {  }
158
159     ServiceRecord * getFrom() noexcept
160     {
161         return from;
162     }
163
164     ServiceRecord * getTo() noexcept
165     {
166         return to;
167     }
168 };
169
170 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
171 // store a null terminator for the argument. Return a `char *` vector containing the beginning
172 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
173 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
174 {
175     std::vector<const char *> r;
176     r.reserve(arg_indices.size() + 1);
177
178     // First store nul terminator for each part:
179     for (auto index_pair : arg_indices) {
180         if (index_pair.second < s.length()) {
181             s[index_pair.second] = 0;
182         }
183     }
184
185     // Now we can get the C string (c_str) and store offsets into it:
186     const char * cstr = s.c_str();
187     for (auto index_pair : arg_indices) {
188         r.push_back(cstr + index_pair.first);
189     }
190     r.push_back(nullptr);
191     return r;
192 }
193
194 class ServiceChildWatcher : public EventLoop_t::child_proc_watcher_impl<ServiceChildWatcher>
195 {
196     public:
197     base_process_service * service;
198     rearm child_status(EventLoop_t &eloop, pid_t child, int status) noexcept;
199     
200     ServiceChildWatcher(base_process_service * sr) noexcept : service(sr) { }
201 };
202
203 class ServiceIoWatcher : public EventLoop_t::fd_watcher_impl<ServiceIoWatcher>
204 {
205     public:
206     base_process_service * service;
207     rearm fd_event(EventLoop_t &eloop, int fd, int flags) noexcept;
208     
209     ServiceIoWatcher(base_process_service * sr) noexcept : service(sr) { }
210 };
211
212 class ServiceRecord
213 {
214     protected:
215     typedef std::string string;
216     
217     string service_name;
218     ServiceType service_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
219     ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
220     ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
221
222     string program_name;          // storage for program/script and arguments
223     std::vector<const char *> exec_arg_parts; // pointer to each argument/part of the program_name, and nullptr
224     
225     string stop_command;          // storage for stop program/script and arguments
226     std::vector<const char *> stop_arg_parts; // pointer to each argument/part of the stop_command, and nullptr
227     
228     string pid_file;
229     
230     OnstartFlags onstart_flags;
231
232     string logfile;           // log file name, empty string specifies /dev/null
233     
234     bool auto_restart : 1;    // whether to restart this (process) if it dies unexpectedly
235     bool smooth_recovery : 1; // whether the service process can restart without bringing down service
236     
237     bool pinned_stopped : 1;
238     bool pinned_started : 1;
239     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
240     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
241     bool start_explicit : 1;    // whether we are are explictly required to be started
242
243     bool prop_require : 1;      // require must be propagated
244     bool prop_release : 1;      // release must be propagated
245     bool prop_failure : 1;      // failure to start must be propagated
246     
247     int required_by = 0;        // number of dependents wanting this service to be started
248
249     typedef std::list<ServiceRecord *> sr_list;
250     typedef sr_list::iterator sr_iter;
251     
252     // list of soft dependencies
253     typedef std::list<ServiceDep> softdep_list;
254     
255     // list of soft dependents
256     typedef std::list<ServiceDep *> softdpt_list;
257     
258     sr_list depends_on; // services this one depends on
259     sr_list dependents; // services depending on this one
260     softdep_list soft_deps;  // services this one depends on via a soft dependency
261     softdpt_list soft_dpts;  // services depending on this one via a soft dependency
262     
263     // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
264     //                         start/stop, this is how many we're waiting for */
265     
266     ServiceSet *service_set; // the set this service belongs to
267     
268     std::unordered_set<ServiceListener *> listeners;
269     
270     // Process services:
271     bool force_stop; // true if the service must actually stop. This is the
272                      // case if for example the process dies; the service,
273                      // and all its dependencies, MUST be stopped.
274     
275     int term_signal = -1;  // signal to use for process termination
276     
277     string socket_path; // path to the socket for socket-activation service
278     int socket_perms;   // socket permissions ("mode")
279     uid_t socket_uid = -1;  // socket user id or -1
280     gid_t socket_gid = -1;  // socket group id or -1
281
282     // Implementation details
283     
284     pid_t pid = -1;  // PID of the process. If state is STARTING or STOPPING,
285                      //   this is PID of the service script; otherwise it is the
286                      //   PID of the process itself (process service).
287     int exit_status; // Exit status, if the process has exited (pid == -1).
288     int socket_fd = -1;  // For socket-activation services, this is the file
289                          // descriptor for the socket.
290     
291     
292     // Data for use by ServiceSet
293     public:
294     
295     // Next service (after this one) in the queue for the console. Intended to only be used by ServiceSet class.
296     ServiceRecord *next_for_console;
297     
298     // Propagation and start/stop queues
299     ServiceRecord *next_in_prop_queue = nullptr;
300     ServiceRecord *next_in_stop_queue = nullptr;
301     
302     
303     protected:
304     
305     // All dependents have stopped.
306     virtual void all_deps_stopped() noexcept;
307     
308     // Service has actually stopped (includes having all dependents
309     // reaching STOPPED state).
310     void stopped() noexcept;
311     
312     // Service has successfully started
313     void started() noexcept;
314     
315     // Service failed to start (only called when in STARTING state).
316     //   dep_failed: whether failure is recorded due to a dependency failing
317     void failed_to_start(bool dep_failed = false) noexcept;
318
319     void run_child_proc(const char * const *args, const char *logfile, bool on_console, int wpipefd,
320             int csfd) noexcept;
321     
322     // Callback from libev when a child process dies
323     static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
324             int revents) noexcept;
325     
326     //virtual void handle_exit_status(int exit_status) noexcept;
327
328     // A dependency has reached STARTED state
329     void dependencyStarted() noexcept;
330     
331     void allDepsStarted(bool haveConsole = false) noexcept;
332
333     // Do any post-dependency startup; return false on failure
334     virtual bool start_ps_process() noexcept;
335
336     // Open the activation socket, return false on failure
337     bool open_socket() noexcept;
338
339     // Check whether dependencies have started, and optionally ask them to start
340     bool startCheckDependencies(bool do_start) noexcept;
341
342     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
343     // having to wait for it reach STARTED and then go through STOPPING).
344     bool can_interrupt_start() noexcept
345     {
346         return waiting_for_deps;
347     }
348     
349     // Whether a STOPPING service can immediately transition to STARTED.
350     bool can_interrupt_stop() noexcept
351     {
352         return waiting_for_deps && ! force_stop;
353     }
354
355     // A dependent has reached STOPPED state
356     void dependentStopped() noexcept;
357
358     // check if all dependents have stopped
359     bool stopCheckDependents() noexcept;
360     
361     // issue a stop to all dependents, return true if they are all already stopped
362     bool stopDependents() noexcept;
363     
364     void require() noexcept;
365     void release() noexcept;
366     void release_dependencies() noexcept;
367     
368     // Check if service is, fundamentally, stopped.
369     bool is_stopped() noexcept
370     {
371         return service_state == ServiceState::STOPPED
372             || (service_state == ServiceState::STARTING && waiting_for_deps);
373     }
374     
375     void notifyListeners(ServiceEvent event) noexcept
376     {
377         for (auto l : listeners) {
378             l->serviceEvent(this, event);
379         }
380     }
381     
382     // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
383     void queueForConsole() noexcept;
384     
385     // Release console (console must be currently held by this service)
386     void releaseConsole() noexcept;
387     
388     bool do_auto_restart() noexcept;
389
390     // Started state reached
391     bool process_started() noexcept;
392
393     public:
394
395     ServiceRecord(ServiceSet *set, string name)
396         : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
397             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
398             waiting_for_execstat(false), start_explicit(false),
399             prop_require(false), prop_release(false), prop_failure(false),
400             force_stop(false)
401     {
402         service_set = set;
403         service_name = name;
404         service_type = ServiceType::DUMMY;
405     }
406     
407     ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
408             sr_list * pdepends_on, sr_list * pdepends_soft)
409         : ServiceRecord(set, name)
410     {
411         service_set = set;
412         service_name = name;
413         this->service_type = service_type;
414         this->depends_on = std::move(*pdepends_on);
415
416         program_name = std::move(command);
417         exec_arg_parts = separate_args(program_name, command_offsets);
418
419         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
420             (*i)->dependents.push_back(this);
421         }
422
423         // Soft dependencies
424         auto b_iter = soft_deps.end();
425         for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
426             b_iter = soft_deps.emplace(b_iter, this, *i);
427             (*i)->soft_dpts.push_back(&(*b_iter));
428             ++b_iter;
429         }
430     }
431     
432     virtual ~ServiceRecord() noexcept
433     {
434     }
435     
436     // begin transition from stopped to started state or vice versa depending on current and desired state
437     void execute_transition() noexcept;
438     
439     void do_propagation() noexcept;
440     
441     // Called on transition of desired state from stopped to started (or unpinned stop)
442     void do_start() noexcept;
443
444     // Called on transition of desired state from started to stopped (or unpinned start)
445     void do_stop() noexcept;
446     
447     // Console is available.
448     void acquiredConsole() noexcept;
449     
450     // Set the stop command and arguments (may throw std::bad_alloc)
451     void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
452     {
453         stop_command = command;
454         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
455     }
456     
457     // Get the current service state.
458     ServiceState getState() noexcept
459     {
460         return service_state;
461     }
462     
463     // Get the target (aka desired) state.
464     ServiceState getTargetState() noexcept
465     {
466         return desired_state;
467     }
468
469     // Set logfile, should be done before service is started
470     void setLogfile(string logfile)
471     {
472         this->logfile = logfile;
473     }
474     
475     // Set whether this service should automatically restart when it dies
476     void setAutoRestart(bool auto_restart) noexcept
477     {
478         this->auto_restart = auto_restart;
479     }
480     
481     void setSmoothRecovery(bool smooth_recovery) noexcept
482     {
483         this->smooth_recovery = smooth_recovery;
484     }
485     
486     // Set "on start" flags (commands)
487     void setOnstartFlags(OnstartFlags flags) noexcept
488     {
489         this->onstart_flags = flags;
490     }
491     
492     // Set an additional signal (other than SIGTERM) to be used to terminate the process
493     void setExtraTerminationSignal(int signo) noexcept
494     {
495         this->term_signal = signo;
496     }
497     
498     void set_pid_file(string &&pid_file) noexcept
499     {
500         this->pid_file = std::move(pid_file);
501     }
502     
503     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
504     {
505         this->socket_path = std::move(socket_path);
506         this->socket_perms = socket_perms;
507         this->socket_uid = socket_uid;
508         this->socket_gid = socket_gid;
509     }
510
511     const std::string &getServiceName() const noexcept { return service_name; }
512     ServiceState getState() 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 forceStop() noexcept; // force-stop this service and all dependents
518     
519     // Pin the service in "started" state (when it reaches the state)
520     void pinStart() noexcept
521     {
522         pinned_started = true;
523     }
524     
525     // Pin the service in "stopped" state (when it reaches the state)
526     void pinStop() 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     bool isDummy() noexcept
537     {
538         return service_type == ServiceType::DUMMY;
539     }
540     
541     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
542     void addListener(ServiceListener * listener)
543     {
544         listeners.insert(listener);
545     }
546     
547     // Remove a listener.    
548     void removeListener(ServiceListener * listener) noexcept
549     {
550         listeners.erase(listener);
551     }
552 };
553
554 class base_process_service : public ServiceRecord
555 {
556     friend class ServiceChildWatcher;
557     friend class ServiceIoWatcher;
558
559     protected:
560     ServiceChildWatcher child_listener;
561     ServiceIoWatcher child_status_listener;
562
563     // start the process, return true on success
564     virtual bool start_ps_process() noexcept;
565     bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
566
567     virtual void all_deps_stopped() noexcept;
568     virtual void handle_exit_status(int exit_status) noexcept = 0;
569
570     public:
571     base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
572             std::list<std::pair<unsigned,unsigned>> &command_offsets,
573             sr_list * pdepends_on, sr_list * pdepends_soft)
574          : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
575              pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
576     {
577     }
578
579     ~base_process_service() noexcept
580     {
581     }
582 };
583
584 class process_service : public base_process_service
585 {
586     // called when the process exits. The exit_status is the status value yielded by
587     // the "wait" system call.
588     virtual void handle_exit_status(int exit_status) noexcept override;
589
590     public:
591     process_service(ServiceSet *sset, string name, string &&command,
592             std::list<std::pair<unsigned,unsigned>> &command_offsets,
593             sr_list * pdepends_on, sr_list * pdepends_soft)
594          : base_process_service(sset, name, ServiceType::PROCESS, std::move(command), command_offsets,
595              pdepends_on, pdepends_soft)
596     {
597     }
598
599     ~process_service() noexcept
600     {
601     }
602 };
603
604 class bgproc_service : public base_process_service
605 {
606     virtual void handle_exit_status(int exit_status) noexcept override;
607
608     bool doing_recovery : 1;    // if we are currently recovering a BGPROCESS (restarting process, while
609                                 //   holding STARTED service state)
610
611     // Read the pid-file, return false on failure
612     bool read_pid_file() noexcept;
613
614     public:
615     bgproc_service(ServiceSet *sset, string name, string &&command,
616             std::list<std::pair<unsigned,unsigned>> &command_offsets,
617             sr_list * pdepends_on, sr_list * pdepends_soft)
618          : base_process_service(sset, name, ServiceType::BGPROCESS, std::move(command), command_offsets,
619              pdepends_on, pdepends_soft)
620     {
621         doing_recovery = false;
622     }
623
624     ~bgproc_service() noexcept
625     {
626     }
627 };
628
629 class scripted_service : public base_process_service
630 {
631     virtual void all_deps_stopped() noexcept override;
632     virtual void handle_exit_status(int exit_status) noexcept override;
633
634     public:
635     scripted_service(ServiceSet *sset, string name, string &&command,
636             std::list<std::pair<unsigned,unsigned>> &command_offsets,
637             sr_list * pdepends_on, sr_list * pdepends_soft)
638          : base_process_service(sset, name, ServiceType::SCRIPTED, std::move(command), command_offsets,
639              pdepends_on, pdepends_soft)
640     {
641     }
642
643     ~scripted_service() noexcept
644     {
645     }
646 };
647
648
649 /*
650  * A ServiceSet, as the name suggests, manages a set of services.
651  *
652  * Other than the ability to find services by name, the service set manages various queues.
653  * One is the queue for processes wishing to acquire the console. There is also a set of
654  * processes that want to start, and another set of those that want to stop. These latter
655  * two "queues" (not really queues since their order is not important) are used to prevent too
656  * much recursion and to prevent service states from "bouncing" too rapidly.
657  * 
658  * A service that wishes to start or stop puts itself on the start/stop queue; a service that
659  * needs to propagate changes to dependent services or dependencies puts itself on the
660  * propagation queue. Any operation that potentially manipulates the queues must be followed
661  * by a "process queues" order (processQueues() method).
662  *
663  * Note that processQueues always repeatedly processes both queues until they are empty. The
664  * process is finite because starting a service can never cause services to stop, unless they
665  * fail to start, which should cause them to stop semi-permanently.
666  */
667 class ServiceSet
668 {
669     int active_services;
670     std::list<ServiceRecord *> records;
671     const char *service_dir;  // directory containing service descriptions
672     bool restart_enabled; // whether automatic restart is enabled (allowed)
673     
674     ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
675     
676     ServiceRecord * console_queue_head = nullptr; // first record in console queue
677     ServiceRecord * console_queue_tail = nullptr; // last record in console queue
678
679     // Propagation and start/stop "queues" - list of services waiting for processing
680     ServiceRecord * first_prop_queue = nullptr;
681     ServiceRecord * first_stop_queue = nullptr;
682     
683     // Private methods
684         
685     // Load a service description, and dependencies, if there is no existing
686     // record for the given name.
687     // Throws:
688     //   ServiceLoadException (or subclass) on problem with service description
689     //   std::bad_alloc on out-of-memory condition
690     ServiceRecord *loadServiceRecord(const char *name);
691
692     // Public
693     
694     public:
695     ServiceSet(const char *service_dir)
696     {
697         this->service_dir = service_dir;
698         active_services = 0;
699         restart_enabled = true;
700     }
701     
702     // Start the service with the given name. The named service will begin
703     // transition to the 'started' state.
704     //
705     // Throws a ServiceLoadException (or subclass) if the service description
706     // cannot be loaded or is invalid;
707     // Throws std::bad_alloc if out of memory.
708     void startService(const char *name);
709     
710     // Locate an existing service record.
711     ServiceRecord *find_service(const std::string &name) noexcept;
712     
713     // Find a loaded service record, or load it if it is not loaded.
714     // Throws:
715     //   ServiceLoadException (or subclass) on problem with service description
716     //   std::bad_alloc on out-of-memory condition 
717     ServiceRecord *loadService(const std::string &name)
718     {
719         ServiceRecord *record = find_service(name);
720         if (record == nullptr) {
721             record = loadServiceRecord(name.c_str());
722         }
723         return record;
724     }
725     
726     // Get the list of all loaded services.
727     const std::list<ServiceRecord *> &listServices()
728     {
729         return records;
730     }
731     
732     // Stop the service with the given name. The named service will begin
733     // transition to the 'stopped' state.
734     void stopService(const std::string &name) noexcept;
735     
736     // Add a service record to the state propogation queue
737     void addToPropQueue(ServiceRecord *service) noexcept
738     {
739         if (service->next_in_prop_queue == nullptr && first_prop_queue != service) {
740             service->next_in_prop_queue = first_prop_queue;
741             first_prop_queue = service;
742         }
743     }
744     
745     // Add a service record to the start queue; called by service record
746     void addToStartQueue(ServiceRecord *service) noexcept
747     {
748         // The start/stop queue is actually one queue:
749         addToStopQueue(service);
750     }
751     
752     // Add a service to the stop queue; called by service record
753     void addToStopQueue(ServiceRecord *service) noexcept
754     {
755         if (service->next_in_stop_queue == nullptr && first_stop_queue != service) {
756             service->next_in_stop_queue = first_stop_queue;
757             first_stop_queue = service;
758         }
759     }
760     
761     // Process state propagation and start/stop queues, until they are empty.
762     // TODO remove the pointless parameter
763     void processQueues(bool ignoredparam = false) noexcept
764     {
765         while (first_stop_queue != nullptr || first_prop_queue != nullptr) {
766             while (first_prop_queue != nullptr) {
767                 auto next = first_prop_queue;
768                 first_prop_queue = next->next_in_prop_queue;
769                 next->next_in_prop_queue = nullptr;
770                 next->do_propagation();
771             }
772             while (first_stop_queue != nullptr) {
773                 auto next = first_stop_queue;
774                 first_stop_queue = next->next_in_stop_queue;
775                 next->next_in_stop_queue = nullptr;
776                 next->execute_transition();
777             }
778         }
779     }
780     
781     // Set the console queue tail (returns previous tail)
782     ServiceRecord * append_console_queue(ServiceRecord * newTail) noexcept
783     {
784         auto prev_tail = console_queue_tail;
785         console_queue_tail = newTail;
786         newTail->next_for_console = nullptr;
787         if (! prev_tail) {
788             console_queue_head = newTail;
789             enable_console_log(false);
790         }
791         else {
792             prev_tail->next_for_console = newTail;
793         }
794         return prev_tail;
795     }
796     
797     // Retrieve the current console queue head and remove it from the queue
798     ServiceRecord * pullConsoleQueue() noexcept
799     {
800         auto prev_head = console_queue_head;
801         if (prev_head) {
802             prev_head->acquiredConsole();
803             console_queue_head = prev_head->next_for_console;
804             if (! console_queue_head) {
805                 console_queue_tail = nullptr;
806             }
807         }
808         else {
809             enable_console_log(true);
810         }
811         return prev_head;
812     }
813     
814     // Notification from service that it is active (state != STOPPED)
815     // Only to be called on the transition from inactive to active.
816     void service_active(ServiceRecord *) noexcept;
817     
818     // Notification from service that it is inactive (STOPPED)
819     // Only to be called on the transition from active to inactive.
820     void service_inactive(ServiceRecord *) noexcept;
821     
822     // Find out how many services are active (starting, running or stopping,
823     // but not stopped).
824     int count_active_services() noexcept
825     {
826         return active_services;
827     }
828     
829     void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
830     {
831         restart_enabled = false;
832         shutdown_type = type;
833         for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
834             (*i)->stop(false);
835             (*i)->unpin();
836         }
837         processQueues(false);
838     }
839     
840     void set_auto_restart(bool restart) noexcept
841     {
842         restart_enabled = restart;
843     }
844     
845     bool get_auto_restart() noexcept
846     {
847         return restart_enabled;
848     }
849     
850     ShutdownType getShutdownType() noexcept
851     {
852         return shutdown_type;
853     }
854 };
855
856 #endif