91c0bb8db7de1a839ad6a7f28bd7425236915f74
[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  * Aquisition/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
73 struct OnstartFlags {
74     bool rw_ready : 1;
75     bool log_ready : 1;
76     
77     // Not actually "onstart" commands:
78     bool no_sigterm : 1;  // do not send SIGTERM
79     bool runs_on_console : 1;  // run "in the foreground"
80     bool pass_cs_fd : 1;  // pass this service a control socket connection via fd
81     
82     OnstartFlags() noexcept : rw_ready(false), log_ready(false),
83             no_sigterm(false), runs_on_console(false), pass_cs_fd(false)
84     {
85     }
86 };
87
88 // Exception while loading a service
89 class ServiceLoadExc
90 {
91     public:
92     std::string serviceName;
93     const char *excDescription;
94     
95     protected:
96     ServiceLoadExc(std::string serviceName) noexcept
97         : serviceName(serviceName)
98     {
99     }
100 };
101
102 class ServiceNotFound : public ServiceLoadExc
103 {
104     public:
105     ServiceNotFound(std::string serviceName) noexcept
106         : ServiceLoadExc(serviceName)
107     {
108         excDescription = "Service description not found.";
109     }
110 };
111
112 class ServiceCyclicDependency : public ServiceLoadExc
113 {
114     public:
115     ServiceCyclicDependency(std::string serviceName) noexcept
116         : ServiceLoadExc(serviceName)
117     {
118         excDescription = "Has cyclic dependency.";
119     }
120 };
121
122 class ServiceDescriptionExc : public ServiceLoadExc
123 {
124     public:
125     std::string extraInfo;
126     
127     ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
128         : ServiceLoadExc(serviceName), extraInfo(extraInfo)
129     {
130         excDescription = extraInfo.c_str();
131     }    
132 };
133
134 class ServiceRecord; // forward declaration
135 class ServiceSet; // forward declaration
136
137 /* Service dependency record */
138 class ServiceDep
139 {
140     ServiceRecord * from;
141     ServiceRecord * to;
142
143     public:
144     /* Whether the 'from' service is waiting for the 'to' service to start */
145     bool waiting_on;
146     /* Whether the 'from' service is holding an acquire on the 'to' service */
147     bool holding_acq;
148
149     ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false), holding_acq(false)
150     {  }
151
152     ServiceRecord * getFrom() noexcept
153     {
154         return from;
155     }
156
157     ServiceRecord * getTo() noexcept
158     {
159         return to;
160     }
161 };
162
163 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
164 // store a null terminator for the argument. Return a `char *` vector containing the beginning
165 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
166 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
167 {
168     std::vector<const char *> r;
169     r.reserve(arg_indices.size() + 1);
170
171     // First store nul terminator for each part:
172     for (auto index_pair : arg_indices) {
173         if (index_pair.second < s.length()) {
174             s[index_pair.second] = 0;
175         }
176     }
177
178     // Now we can get the C string (c_str) and store offsets into it:
179     const char * cstr = s.c_str();
180     for (auto index_pair : arg_indices) {
181         r.push_back(cstr + index_pair.first);
182     }
183     r.push_back(nullptr);
184     return r;
185 }
186
187 class ServiceChildWatcher : public EventLoop_t::child_proc_watcher_impl<ServiceChildWatcher>
188 {
189     public:
190     ServiceRecord * service;
191     rearm child_status(EventLoop_t &eloop, pid_t child, int status) noexcept;
192     
193     ServiceChildWatcher(ServiceRecord * sr) noexcept : service(sr) { }
194 };
195
196 class ServiceIoWatcher : public EventLoop_t::fd_watcher_impl<ServiceIoWatcher>
197 {
198     public:
199     ServiceRecord * service;
200     rearm fd_event(EventLoop_t &eloop, int fd, int flags) noexcept;
201     
202     ServiceIoWatcher(ServiceRecord * sr) noexcept : service(sr) { }
203 };
204
205 class ServiceRecord
206 {
207     friend class ServiceChildWatcher;
208     friend class ServiceIoWatcher;
209     
210     typedef std::string string;
211     
212     string service_name;
213     ServiceType service_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
214     ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
215     ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
216
217     string program_name;          // storage for program/script and arguments
218     std::vector<const char *> exec_arg_parts; // pointer to each argument/part of the program_name, and nullptr
219     
220     string stop_command;          // storage for stop program/script and arguments
221     std::vector<const char *> stop_arg_parts; // pointer to each argument/part of the stop_command, and nullptr
222     
223     string pid_file;
224     
225     OnstartFlags onstart_flags;
226
227     string logfile;           // log file name, empty string specifies /dev/null
228     
229     bool auto_restart : 1;    // whether to restart this (process) if it dies unexpectedly
230     bool smooth_recovery : 1; // whether the service process can restart without bringing down service
231     
232     bool pinned_stopped : 1;
233     bool pinned_started : 1;
234     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
235     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
236     bool doing_recovery : 1;    // if we are currently recovering a BGPROCESS (restarting process, while
237                                 //   holding STARTED service state)
238     bool start_explicit : 1;    // whether we are are explictly required to be started
239
240     bool prop_require : 1;      // require must be propagated
241     bool prop_release : 1;      // release must be propagated
242     bool prop_failure : 1;      // failure to start must be propagated
243     
244     int required_by = 0;        // number of dependents wanting this service to be started
245
246     typedef std::list<ServiceRecord *> sr_list;
247     typedef sr_list::iterator sr_iter;
248     
249     // list of soft dependencies
250     typedef std::list<ServiceDep> softdep_list;
251     
252     // list of soft dependents
253     typedef std::list<ServiceDep *> softdpt_list;
254     
255     sr_list depends_on; // services this one depends on
256     sr_list dependents; // services depending on this one
257     softdep_list soft_deps;  // services this one depends on via a soft dependency
258     softdpt_list soft_dpts;  // services depending on this one via a soft dependency
259     
260     // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
261     //                         start/stop, this is how many we're waiting for */
262     
263     ServiceSet *service_set; // the set this service belongs to
264     
265     std::unordered_set<ServiceListener *> listeners;
266     
267     // Process services:
268     bool force_stop; // true if the service must actually stop. This is the
269                      // case if for example the process dies; the service,
270                      // and all its dependencies, MUST be stopped.
271     
272     int term_signal = -1;  // signal to use for process termination
273     
274     string socket_path; // path to the socket for socket-activation service
275     int socket_perms;   // socket permissions ("mode")
276     uid_t socket_uid = -1;  // socket user id or -1
277     gid_t socket_gid = -1;  // sockget group id or -1
278
279     // Implementation details
280     
281     pid_t pid = -1;  // PID of the process. If state is STARTING or STOPPING,
282                      //   this is PID of the service script; otherwise it is the
283                      //   PID of the process itself (process service).
284     int exit_status; // Exit status, if the process has exited (pid == -1).
285     int socket_fd = -1;  // For socket-activation services, this is the file
286                          // descriptor for the socket.
287     
288     ServiceChildWatcher child_listener;
289     ServiceIoWatcher child_status_listener;
290     
291     // Data for use by ServiceSet
292     public:
293     
294     // Next service (after this one) in the queue for the console. Intended to only be used by ServiceSet class.
295     ServiceRecord *next_for_console;
296     
297     // Propagation and start/stop queues
298     ServiceRecord *next_in_prop_queue = nullptr;
299     ServiceRecord *next_in_stop_queue = nullptr;
300     
301     
302     private:
303     
304     // All dependents have stopped.
305     void allDepsStopped();
306     
307     // Service has actually stopped (includes having all dependents
308     // reaching STOPPED state).
309     void stopped() noexcept;
310     
311     // Service has successfully started
312     void started() noexcept;
313     
314     // Service failed to start (only called when in STARTING state).
315     //   dep_failed: whether failure is recorded due to a dependency failing
316     void failed_to_start(bool dep_failed = false) noexcept;
317
318     // For process services, start the process, return true on success
319     bool start_ps_process() noexcept;
320     bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
321     
322     void run_child_proc(const char * const *args, const char *logfile, bool on_console, int wpipefd,
323             int csfd) noexcept;
324     
325     // Callback from libev when a child process dies
326     static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
327             int revents) noexcept;
328     
329     void handle_exit_status() noexcept;
330
331     // A dependency has reached STARTED state
332     void dependencyStarted() noexcept;
333     
334     void allDepsStarted(bool haveConsole = false) noexcept;
335     
336     // Read the pid-file, return false on failure
337     bool read_pid_file() noexcept;
338     
339     // Open the activation socket, return false on failure
340     bool open_socket() noexcept;
341     
342     // Check whether dependencies have started, and optionally ask them to start
343     bool startCheckDependencies(bool do_start) noexcept;
344     
345     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
346     // having to wait for it reach STARTED and then go through STOPPING).
347     bool can_interrupt_start() noexcept
348     {
349         return waiting_for_deps;
350     }
351     
352     // Whether a STOPPING service can immediately transition to STARTED.
353     bool can_interrupt_stop() noexcept
354     {
355         return waiting_for_deps && ! force_stop;
356     }
357
358     // Notify dependencies that we no longer need them,
359     // (if this is actually the case).
360     void notify_dependencies_stopped() noexcept;
361
362     // A dependent has reached STOPPED state
363     void dependentStopped() noexcept;
364
365     // check if all dependents have stopped
366     bool stopCheckDependents() noexcept;
367     
368     // issue a stop to all dependents, return true if they are all already stopped
369     bool stopDependents() noexcept;
370     
371     void require() noexcept;
372     void release() noexcept;
373     void release_dependencies() noexcept;
374     
375     // Check if service is, fundamentally, stopped.
376     bool is_stopped() noexcept
377     {
378         return service_state == ServiceState::STOPPED
379             || (service_state == ServiceState::STARTING && waiting_for_deps);
380     }
381     
382     void notifyListeners(ServiceEvent event) noexcept
383     {
384         for (auto l : listeners) {
385             l->serviceEvent(this, event);
386         }
387     }
388     
389     // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
390     void queueForConsole() noexcept;
391     
392     // Release console (console must be currently held by this service)
393     void releaseConsole() noexcept;
394     
395     bool do_auto_restart() noexcept;
396     
397     public:
398
399     ServiceRecord(ServiceSet *set, string name)
400         : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
401             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
402             waiting_for_execstat(false), doing_recovery(false),
403             start_explicit(false), prop_require(false), prop_release(false), prop_failure(false),
404             force_stop(false), child_listener(this), child_status_listener(this)
405     {
406         service_set = set;
407         service_name = name;
408         service_type = ServiceType::DUMMY;
409     }
410     
411     ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
412             sr_list * pdepends_on, sr_list * pdepends_soft)
413         : ServiceRecord(set, name)
414     {
415         service_set = set;
416         service_name = name;
417         this->service_type = service_type;
418         this->depends_on = std::move(*pdepends_on);
419
420         program_name = command;
421         exec_arg_parts = separate_args(program_name, command_offsets);
422
423         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
424             (*i)->dependents.push_back(this);
425         }
426
427         // Soft dependencies
428         auto b_iter = soft_deps.end();
429         for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
430             b_iter = soft_deps.emplace(b_iter, this, *i);
431             (*i)->soft_dpts.push_back(&(*b_iter));
432             ++b_iter;
433         }
434     }
435     
436     // TODO write a destructor
437     
438     // begin transition from stopped to started state or vice versa depending on current and desired state
439     void execute_transition() noexcept;
440     
441     void do_propagation() noexcept;
442     
443     // Called on transition of desired state from stopped to started (or unpinned stop)
444     void do_start() noexcept;
445
446     // Called on transition of desired state from started to stopped (or unpinned start)
447     void do_stop() noexcept;
448     
449     // Console is available.
450     void acquiredConsole() noexcept;
451     
452     // Set the stop command and arguments (may throw std::bad_alloc)
453     void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
454     {
455         stop_command = command;
456         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
457     }
458     
459     // Get the current service state.
460     ServiceState getState() noexcept
461     {
462         return service_state;
463     }
464     
465     // Get the target (aka desired) state.
466     ServiceState getTargetState() noexcept
467     {
468         return desired_state;
469     }
470
471     // Set logfile, should be done before service is started
472     void setLogfile(string logfile)
473     {
474         this->logfile = logfile;
475     }
476     
477     // Set whether this service should automatically restart when it dies
478     void setAutoRestart(bool auto_restart) noexcept
479     {
480         this->auto_restart = auto_restart;
481     }
482     
483     void setSmoothRecovery(bool smooth_recovery) noexcept
484     {
485         this->smooth_recovery = smooth_recovery;
486     }
487     
488     // Set "on start" flags (commands)
489     void setOnstartFlags(OnstartFlags flags) noexcept
490     {
491         this->onstart_flags = flags;
492     }
493     
494     // Set an additional signal (other than SIGTERM) to be used to terminate the process
495     void setExtraTerminationSignal(int signo) noexcept
496     {
497         this->term_signal = signo;
498     }
499     
500     void set_pid_file(string &&pid_file) noexcept
501     {
502         this->pid_file = pid_file;
503     }
504     
505     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
506     {
507         this->socket_path = socket_path;
508         this->socket_perms = socket_perms;
509         this->socket_uid = socket_uid;
510         this->socket_gid = socket_gid;
511     }
512
513     const std::string &getServiceName() const noexcept { return service_name; }
514     ServiceState getState() const noexcept { return service_state; }
515     
516     void start(bool activate = true) noexcept;  // start the service
517     void stop(bool bring_down = true) noexcept;   // stop the service
518     
519     void forceStop() noexcept; // force-stop this service and all dependents
520     
521     // Pin the service in "started" state (when it reaches the state)
522     void pinStart() noexcept
523     {
524         pinned_started = true;
525     }
526     
527     // Pin the service in "stopped" state (when it reaches the state)
528     void pinStop() noexcept
529     {
530         pinned_stopped = true;
531     }
532     
533     // Remove both "started" and "stopped" pins. If the service is currently pinned
534     // in either state but would naturally be in the opposite state, it will immediately
535     // commence starting/stopping.
536     void unpin() noexcept;
537     
538     bool isDummy() noexcept
539     {
540         return service_type == ServiceType::DUMMY;
541     }
542     
543     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
544     void addListener(ServiceListener * listener)
545     {
546         listeners.insert(listener);
547     }
548     
549     // Remove a listener.    
550     void removeListener(ServiceListener * listener) noexcept
551     {
552         listeners.erase(listener);
553     }
554 };
555
556 /*
557  * A ServiceSet, as the name suggests, manages a set of services.
558  *
559  * Other than the ability to find services by name, the service set manages various queues.
560  * One is the queue for processes wishing to acquire the console. There is also a set of
561  * processes that want to start, and another set of those that want to stop. These latter
562  * two "queues" (not really queues since their order is not important) are used to prevent too
563  * much recursion and to prevent service states from "bouncing" too rapidly.
564  * 
565  * A service that wishes to start or stop puts itself on the start/stop queue; a service that
566  * needs to propagate changes to dependent services or dependencies puts itself on the
567  * propagation queue. Any operation that potentially manipulates the queues must be followed
568  * by a "process queues" order (processQueues() method).
569  *
570  * Note that processQueues always repeatedly processes both queues until they are empty. The
571  * process is finite because starting a service can never cause services to stop, unless they
572  * fail to start, which should cause them to stop semi-permanently.
573  */
574 class ServiceSet
575 {
576     int active_services;
577     std::list<ServiceRecord *> records;
578     const char *service_dir;  // directory containing service descriptions
579     bool restart_enabled; // whether automatic restart is enabled (allowed)
580     
581     ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
582     
583     ServiceRecord * console_queue_head = nullptr; // first record in console queue
584     ServiceRecord * console_queue_tail = nullptr; // last record in console queue
585
586     // Propagation and start/stop "queues" - list of services waiting for processing
587     ServiceRecord * first_prop_queue = nullptr;
588     ServiceRecord * first_stop_queue = nullptr;
589     
590     // Private methods
591         
592     // Load a service description, and dependencies, if there is no existing
593     // record for the given name.
594     // Throws:
595     //   ServiceLoadException (or subclass) on problem with service description
596     //   std::bad_alloc on out-of-memory condition
597     ServiceRecord *loadServiceRecord(const char *name);
598
599     // Public
600     
601     public:
602     ServiceSet(const char *service_dir)
603     {
604         this->service_dir = service_dir;
605         active_services = 0;
606         restart_enabled = true;
607     }
608     
609     // Start the service with the given name. The named service will begin
610     // transition to the 'started' state.
611     //
612     // Throws a ServiceLoadException (or subclass) if the service description
613     // cannot be loaded or is invalid;
614     // Throws std::bad_alloc if out of memory.
615     void startService(const char *name);
616     
617     // Locate an existing service record.
618     ServiceRecord *findService(const std::string &name) noexcept;
619     
620     // Find a loaded service record, or load it if it is not loaded.
621     // Throws:
622     //   ServiceLoadException (or subclass) on problem with service description
623     //   std::bad_alloc on out-of-memory condition 
624     ServiceRecord *loadService(const std::string &name)
625     {
626         ServiceRecord *record = findService(name);
627         if (record == nullptr) {
628             record = loadServiceRecord(name.c_str());
629         }
630         return record;
631     }
632     
633     // Get the list of all loaded services.
634     const std::list<ServiceRecord *> &listServices()
635     {
636         return records;
637     }
638     
639     // Stop the service with the given name. The named service will begin
640     // transition to the 'stopped' state.
641     void stopService(const std::string &name) noexcept;
642     
643     // Add a service record to the state propogation queue
644     void addToPropQueue(ServiceRecord *service) noexcept
645     {
646         if (service->next_in_prop_queue == nullptr && first_prop_queue != service) {
647             service->next_in_prop_queue = first_prop_queue;
648             first_prop_queue = service;
649         }
650     }
651     
652     // Add a service record to the start queue; called by service record
653     void addToStartQueue(ServiceRecord *service) noexcept
654     {
655         // The start/stop queue is actually one queue:
656         addToStopQueue(service);
657     }
658     
659     // Add a service to the stop queue; called by service record
660     void addToStopQueue(ServiceRecord *service) noexcept
661     {
662         if (service->next_in_stop_queue == nullptr && first_stop_queue != service) {
663             service->next_in_stop_queue = first_stop_queue;
664             first_stop_queue = service;
665         }
666     }
667     
668     // Process state propagation and start/stop queues, until they are empty.
669     // TODO remove the pointless parameter
670     void processQueues(bool ignoredparam = false) noexcept
671     {
672         while (first_stop_queue != nullptr || first_prop_queue != nullptr) {
673             while (first_prop_queue != nullptr) {
674                 auto next = first_prop_queue;
675                 first_prop_queue = next->next_in_prop_queue;
676                 next->next_in_prop_queue = nullptr;
677                 next->do_propagation();
678             }
679             while (first_stop_queue != nullptr) {
680                 auto next = first_stop_queue;
681                 first_stop_queue = next->next_in_stop_queue;
682                 next->next_in_stop_queue = nullptr;
683                 next->execute_transition();
684             }
685         }
686     }
687     
688     // Set the console queue tail (returns previous tail)
689     ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
690     {
691         auto prev_tail = console_queue_tail;
692         console_queue_tail = newTail;
693         newTail->next_for_console = nullptr;
694         if (! prev_tail) {
695             console_queue_head = newTail;
696             enable_console_log(false);
697         }
698         else {
699             prev_tail->next_for_console = newTail;
700         }
701         return prev_tail;
702     }
703     
704     // Retrieve the current console queue head and remove it from the queue
705     ServiceRecord * pullConsoleQueue() noexcept
706     {
707         auto prev_head = console_queue_head;
708         if (prev_head) {
709             prev_head->acquiredConsole();
710             console_queue_head = prev_head->next_for_console;
711             if (! console_queue_head) {
712                 console_queue_tail = nullptr;
713             }
714         }
715         else {
716             enable_console_log(true);
717         }
718         return prev_head;
719     }
720     
721     // Notification from service that it is active (state != STOPPED)
722     // Only to be called on the transition from inactive to active.
723     void service_active(ServiceRecord *) noexcept;
724     
725     // Notification from service that it is inactive (STOPPED)
726     // Only to be called on the transition from active to inactive.
727     void service_inactive(ServiceRecord *) noexcept;
728     
729     // Find out how many services are active (starting, running or stopping,
730     // but not stopped).
731     int count_active_services() noexcept
732     {
733         return active_services;
734     }
735     
736     void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
737     {
738         restart_enabled = false;
739         shutdown_type = type;
740         for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
741             (*i)->stop(false);
742             (*i)->unpin();
743         }
744         processQueues(false);
745     }
746     
747     void set_auto_restart(bool restart) noexcept
748     {
749         restart_enabled = restart;
750     }
751     
752     bool get_auto_restart() noexcept
753     {
754         return restart_enabled;
755     }
756     
757     ShutdownType getShutdownType() noexcept
758     {
759         return shutdown_type;
760     }
761 };
762
763 #endif