service: only force stop dependents if necessary.
[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 starts_on_console : 1; // starts in the foreground
92     bool pass_cs_fd : 1;  // pass this service a control socket connection via fd
93     
94     OnstartFlags() noexcept : rw_ready(false), log_ready(false),
95             no_sigterm(false), runs_on_console(false), starts_on_console(false), pass_cs_fd(false)
96     {
97     }
98 };
99
100 // Exception while loading a service
101 class ServiceLoadExc
102 {
103     public:
104     std::string serviceName;
105     std::string excDescription;
106     
107     protected:
108     ServiceLoadExc(std::string serviceName, std::string &&desc) noexcept
109         : serviceName(serviceName), excDescription(std::move(desc))
110     {
111     }
112 };
113
114 class ServiceNotFound : public ServiceLoadExc
115 {
116     public:
117     ServiceNotFound(std::string serviceName) noexcept
118         : ServiceLoadExc(serviceName, "Service description not found.")
119     {
120     }
121 };
122
123 class ServiceCyclicDependency : public ServiceLoadExc
124 {
125     public:
126     ServiceCyclicDependency(std::string serviceName) noexcept
127         : ServiceLoadExc(serviceName, "Has cyclic dependency.")
128     {
129     }
130 };
131
132 class ServiceDescriptionExc : public ServiceLoadExc
133 {
134     public:
135     ServiceDescriptionExc(std::string serviceName, std::string &&extraInfo) noexcept
136         : ServiceLoadExc(serviceName, std::move(extraInfo))
137     {
138     }    
139 };
140
141 class ServiceRecord;
142 class ServiceSet;
143 class base_process_service;
144
145 /* Service dependency record */
146 class ServiceDep
147 {
148     ServiceRecord * from;
149     ServiceRecord * to;
150
151     public:
152     /* Whether the 'from' service is waiting for the 'to' service to start */
153     bool waiting_on;
154     /* Whether the 'from' service is holding an acquire on the 'to' service */
155     bool holding_acq;
156
157     ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false), holding_acq(false)
158     {  }
159
160     ServiceRecord * getFrom() noexcept
161     {
162         return from;
163     }
164
165     ServiceRecord * getTo() noexcept
166     {
167         return to;
168     }
169 };
170
171 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
172 // store a null terminator for the argument. Return a `char *` vector containing the beginning
173 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
174 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
175 {
176     std::vector<const char *> r;
177     r.reserve(arg_indices.size() + 1);
178
179     // First store nul terminator for each part:
180     for (auto index_pair : arg_indices) {
181         if (index_pair.second < s.length()) {
182             s[index_pair.second] = 0;
183         }
184     }
185
186     // Now we can get the C string (c_str) and store offsets into it:
187     const char * cstr = s.c_str();
188     for (auto index_pair : arg_indices) {
189         r.push_back(cstr + index_pair.first);
190     }
191     r.push_back(nullptr);
192     return r;
193 }
194
195 class ServiceChildWatcher : public EventLoop_t::child_proc_watcher_impl<ServiceChildWatcher>
196 {
197     public:
198     base_process_service * service;
199     rearm status_change(EventLoop_t &eloop, pid_t child, int status) noexcept;
200     
201     ServiceChildWatcher(base_process_service * sr) noexcept : service(sr) { }
202 };
203
204 class ServiceIoWatcher : public EventLoop_t::fd_watcher_impl<ServiceIoWatcher>
205 {
206     public:
207     base_process_service * service;
208     rearm fd_event(EventLoop_t &eloop, int fd, int flags) noexcept;
209     
210     ServiceIoWatcher(base_process_service * sr) noexcept : service(sr) { }
211 };
212
213 class ServiceRecord
214 {
215     protected:
216     typedef std::string string;
217     
218     string service_name;
219     ServiceType service_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
220     ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
221     ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
222
223     string program_name;          // storage for program/script and arguments
224     std::vector<const char *> exec_arg_parts; // pointer to each argument/part of the program_name, and nullptr
225     
226     string stop_command;          // storage for stop program/script and arguments
227     std::vector<const char *> stop_arg_parts; // pointer to each argument/part of the stop_command, and nullptr
228     
229     string pid_file;
230     
231     OnstartFlags onstart_flags;
232
233     string logfile;           // log file name, empty string specifies /dev/null
234     
235     bool auto_restart : 1;    // whether to restart this (process) if it dies unexpectedly
236     bool smooth_recovery : 1; // whether the service process can restart without bringing down service
237     
238     bool pinned_stopped : 1;
239     bool pinned_started : 1;
240     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
241     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
242     bool start_explicit : 1;    // whether we are are explictly required to be started
243
244     bool prop_require : 1;      // require must be propagated
245     bool prop_release : 1;      // release must be propagated
246     bool prop_failure : 1;      // failure to start must be propagated
247     bool restarting : 1;        // re-starting after unexpected termination
248     
249     int required_by = 0;        // number of dependents wanting this service to be started
250
251     typedef std::list<ServiceRecord *> sr_list;
252     typedef sr_list::iterator sr_iter;
253     
254     // list of soft dependencies
255     typedef std::list<ServiceDep> softdep_list;
256     
257     // list of soft dependents
258     typedef std::list<ServiceDep *> softdpt_list;
259     
260     sr_list depends_on; // services this one depends on
261     sr_list dependents; // services depending on this one
262     softdep_list soft_deps;  // services this one depends on via a soft dependency
263     softdpt_list soft_dpts;  // services depending on this one via a soft dependency
264     
265     // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
266     //                         start/stop, this is how many we're waiting for */
267     
268     ServiceSet *service_set; // the set this service belongs to
269     
270     std::unordered_set<ServiceListener *> listeners;
271     
272     // Process services:
273     bool force_stop; // true if the service must actually stop. This is the
274                      // case if for example the process dies; the service,
275                      // and all its dependencies, MUST be stopped.
276     
277     int term_signal = -1;  // signal to use for process termination
278     
279     string socket_path; // path to the socket for socket-activation service
280     int socket_perms;   // socket permissions ("mode")
281     uid_t socket_uid = -1;  // socket user id or -1
282     gid_t socket_gid = -1;  // socket group id or -1
283
284     // Implementation details
285     
286     pid_t pid = -1;  // PID of the process. If state is STARTING or STOPPING,
287                      //   this is PID of the service script; otherwise it is the
288                      //   PID of the process itself (process service).
289     int exit_status; // Exit status, if the process has exited (pid == -1).
290     int socket_fd = -1;  // For socket-activation services, this is the file
291                          // descriptor for the socket.
292     
293     
294     // Data for use by ServiceSet
295     public:
296     
297     // Next service (after this one) in the queue for the console. Intended to only be used by ServiceSet class.
298     ServiceRecord *next_for_console;
299     
300     // Propagation and start/stop queues
301     ServiceRecord *next_in_prop_queue = nullptr;
302     ServiceRecord *next_in_stop_queue = nullptr;
303     
304     
305     protected:
306     
307     // All dependents have stopped.
308     virtual void all_deps_stopped() noexcept;
309     
310     // Service has actually stopped (includes having all dependents
311     // reaching STOPPED state).
312     void stopped() noexcept;
313     
314     // Service has successfully started
315     void started() noexcept;
316     
317     // Service failed to start (only called when in STARTING state).
318     //   dep_failed: whether failure is recorded due to a dependency failing
319     void failed_to_start(bool dep_failed = false) noexcept;
320
321     void run_child_proc(const char * const *args, const char *logfile, bool on_console, int wpipefd,
322             int csfd) noexcept;
323     
324     // Callback from libev when a child process dies
325     static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
326             int revents) noexcept;
327     
328     //virtual void handle_exit_status(int exit_status) noexcept;
329
330     // A dependency has reached STARTED state
331     void dependencyStarted() noexcept;
332     
333     void allDepsStarted(bool haveConsole = false) noexcept;
334
335     // Do any post-dependency startup; return false on failure
336     virtual bool start_ps_process() noexcept;
337
338     // Open the activation socket, return false on failure
339     bool open_socket() noexcept;
340
341     // Check whether dependencies have started, and optionally ask them to start
342     bool startCheckDependencies(bool do_start) noexcept;
343
344     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
345     // having to wait for it reach STARTED and then go through STOPPING).
346     virtual bool can_interrupt_start() noexcept
347     {
348         return waiting_for_deps;
349     }
350     
351     virtual void interrupt_start() noexcept
352     {
353         // overridden in subclasses
354     }
355
356     // Whether a STOPPING service can immediately transition to STARTED.
357     bool can_interrupt_stop() noexcept
358     {
359         return waiting_for_deps && ! force_stop;
360     }
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     // Started state reached
398     bool process_started() noexcept;
399
400     public:
401
402     ServiceRecord(ServiceSet *set, string name)
403         : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
404             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
405             waiting_for_execstat(false), start_explicit(false),
406             prop_require(false), prop_release(false), prop_failure(false),
407             restarting(false), force_stop(false)
408     {
409         service_set = set;
410         service_name = name;
411         service_type = ServiceType::DUMMY;
412     }
413     
414     ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
415             sr_list * pdepends_on, sr_list * pdepends_soft)
416         : ServiceRecord(set, name)
417     {
418         service_set = set;
419         service_name = name;
420         this->service_type = service_type;
421         this->depends_on = std::move(*pdepends_on);
422
423         program_name = std::move(command);
424         exec_arg_parts = separate_args(program_name, command_offsets);
425
426         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
427             (*i)->dependents.push_back(this);
428         }
429
430         // Soft dependencies
431         auto b_iter = soft_deps.end();
432         for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
433             b_iter = soft_deps.emplace(b_iter, this, *i);
434             (*i)->soft_dpts.push_back(&(*b_iter));
435             ++b_iter;
436         }
437     }
438     
439     virtual ~ServiceRecord() noexcept
440     {
441     }
442     
443     // begin transition from stopped to started state or vice versa depending on current and desired state
444     void execute_transition() noexcept;
445     
446     void do_propagation() noexcept;
447     
448     // Called on transition of desired state from stopped to started (or unpinned stop)
449     void do_start() noexcept;
450
451     // Called on transition of desired state from started to stopped (or unpinned start)
452     void do_stop() noexcept;
453     
454     // Console is available.
455     void acquiredConsole() noexcept;
456     
457     // Set the stop command and arguments (may throw std::bad_alloc)
458     void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
459     {
460         stop_command = command;
461         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
462     }
463     
464     // Get the current service state.
465     ServiceState getState() noexcept
466     {
467         return service_state;
468     }
469     
470     // Get the target (aka desired) state.
471     ServiceState getTargetState() noexcept
472     {
473         return desired_state;
474     }
475
476     // Set logfile, should be done before service is started
477     void setLogfile(string logfile)
478     {
479         this->logfile = logfile;
480     }
481     
482     // Set whether this service should automatically restart when it dies
483     void setAutoRestart(bool auto_restart) noexcept
484     {
485         this->auto_restart = auto_restart;
486     }
487     
488     void setSmoothRecovery(bool smooth_recovery) noexcept
489     {
490         this->smooth_recovery = smooth_recovery;
491     }
492     
493     // Set "on start" flags (commands)
494     void setOnstartFlags(OnstartFlags flags) noexcept
495     {
496         this->onstart_flags = flags;
497     }
498     
499     // Set an additional signal (other than SIGTERM) to be used to terminate the process
500     void setExtraTerminationSignal(int signo) noexcept
501     {
502         this->term_signal = signo;
503     }
504     
505     void set_pid_file(string &&pid_file) noexcept
506     {
507         this->pid_file = std::move(pid_file);
508     }
509     
510     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
511     {
512         this->socket_path = std::move(socket_path);
513         this->socket_perms = socket_perms;
514         this->socket_uid = socket_uid;
515         this->socket_gid = socket_gid;
516     }
517
518     const std::string &getServiceName() const noexcept { return service_name; }
519     ServiceState getState() const noexcept { return service_state; }
520     
521     void start(bool activate = true) noexcept;  // start the service
522     void stop(bool bring_down = true) noexcept;   // stop the service
523     
524     void forceStop() noexcept; // force-stop this service and all dependents
525     
526     // Pin the service in "started" state (when it reaches the state)
527     void pinStart() noexcept
528     {
529         pinned_started = true;
530     }
531     
532     // Pin the service in "stopped" state (when it reaches the state)
533     void pinStop() noexcept
534     {
535         pinned_stopped = true;
536     }
537     
538     // Remove both "started" and "stopped" pins. If the service is currently pinned
539     // in either state but would naturally be in the opposite state, it will immediately
540     // commence starting/stopping.
541     void unpin() noexcept;
542     
543     bool isDummy() noexcept
544     {
545         return service_type == ServiceType::DUMMY;
546     }
547     
548     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
549     void addListener(ServiceListener * listener)
550     {
551         listeners.insert(listener);
552     }
553     
554     // Remove a listener.    
555     void removeListener(ServiceListener * listener) noexcept
556     {
557         listeners.erase(listener);
558     }
559 };
560
561 class base_process_service;
562
563 // A timer for process restarting. Used to ensure a minimum delay between
564 // process restarts.
565 class process_restart_timer : public EventLoop_t::timer_impl<process_restart_timer>
566 {
567     public:
568     base_process_service * service;
569
570     process_restart_timer()
571     {
572     }
573
574     rearm timer_expiry(EventLoop_t &, int expiry_count);
575 };
576
577 class base_process_service : public ServiceRecord
578 {
579     friend class ServiceChildWatcher;
580     friend class ServiceIoWatcher;
581     friend class process_restart_timer;
582
583     private:
584     // Re-launch process
585     void do_restart() noexcept;
586
587     protected:
588     ServiceChildWatcher child_listener;
589     ServiceIoWatcher child_status_listener;
590     process_restart_timer restart_timer;
591     timespec last_start_time;
592
593     // Restart interval time and restart count are used to track the number of automatic restarts
594     // over an interval. Too many restarts over an interval will inhibit further restarts.
595     timespec restart_interval_time;
596     int restart_interval_count;
597
598     timespec restart_interval;
599     int max_restart_interval_count;
600     timespec restart_delay;
601
602     bool waiting_restart_timer = false;
603
604     // Start the process, return true on success
605     virtual bool start_ps_process() noexcept override;
606     bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
607
608     // Restart the process (due to start failure or unexpected termination). Restarts will be
609     // rate-limited.
610     bool restart_ps_process() noexcept;
611
612     virtual void all_deps_stopped() noexcept override;
613     virtual void handle_exit_status(int exit_status) noexcept = 0;
614
615     virtual bool can_interrupt_start() noexcept override
616     {
617         return waiting_restart_timer || ServiceRecord::can_interrupt_start();
618     }
619
620     virtual void interrupt_start() noexcept override;
621
622     public:
623     base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
624             std::list<std::pair<unsigned,unsigned>> &command_offsets,
625             sr_list * pdepends_on, sr_list * pdepends_soft);
626
627     ~base_process_service() noexcept
628     {
629     }
630
631     void set_restart_interval(timespec interval, int max_restarts) noexcept
632     {
633         restart_interval = interval;
634         max_restart_interval_count = max_restarts;
635     }
636
637     void set_restart_delay(timespec delay) noexcept
638     {
639         restart_delay = delay;
640     }
641 };
642
643 class process_service : public base_process_service
644 {
645     // called when the process exits. The exit_status is the status value yielded by
646     // the "wait" system call.
647     virtual void handle_exit_status(int exit_status) noexcept override;
648
649     public:
650     process_service(ServiceSet *sset, string name, string &&command,
651             std::list<std::pair<unsigned,unsigned>> &command_offsets,
652             sr_list * pdepends_on, sr_list * pdepends_soft)
653          : base_process_service(sset, name, ServiceType::PROCESS, std::move(command), command_offsets,
654              pdepends_on, pdepends_soft)
655     {
656     }
657
658     ~process_service() noexcept
659     {
660     }
661 };
662
663 class bgproc_service : public base_process_service
664 {
665     virtual void handle_exit_status(int exit_status) noexcept override;
666
667     bool doing_recovery : 1;    // if we are currently recovering a BGPROCESS (restarting process, while
668                                 //   holding STARTED service state)
669
670     // Read the pid-file, return false on failure
671     bool read_pid_file() noexcept;
672
673     public:
674     bgproc_service(ServiceSet *sset, string name, string &&command,
675             std::list<std::pair<unsigned,unsigned>> &command_offsets,
676             sr_list * pdepends_on, sr_list * pdepends_soft)
677          : base_process_service(sset, name, ServiceType::BGPROCESS, std::move(command), command_offsets,
678              pdepends_on, pdepends_soft)
679     {
680         doing_recovery = false;
681     }
682
683     ~bgproc_service() noexcept
684     {
685     }
686 };
687
688 class scripted_service : public base_process_service
689 {
690     virtual void all_deps_stopped() noexcept override;
691     virtual void handle_exit_status(int exit_status) noexcept override;
692
693     public:
694     scripted_service(ServiceSet *sset, string name, string &&command,
695             std::list<std::pair<unsigned,unsigned>> &command_offsets,
696             sr_list * pdepends_on, sr_list * pdepends_soft)
697          : base_process_service(sset, name, ServiceType::SCRIPTED, std::move(command), command_offsets,
698              pdepends_on, pdepends_soft)
699     {
700     }
701
702     ~scripted_service() noexcept
703     {
704     }
705 };
706
707
708 /*
709  * A ServiceSet, as the name suggests, manages a set of services.
710  *
711  * Other than the ability to find services by name, the service set manages various queues.
712  * One is the queue for processes wishing to acquire the console. There is also a set of
713  * processes that want to start, and another set of those that want to stop. These latter
714  * two "queues" (not really queues since their order is not important) are used to prevent too
715  * much recursion and to prevent service states from "bouncing" too rapidly.
716  * 
717  * A service that wishes to start or stop puts itself on the start/stop queue; a service that
718  * needs to propagate changes to dependent services or dependencies puts itself on the
719  * propagation queue. Any operation that potentially manipulates the queues must be followed
720  * by a "process queues" order (processQueues() method).
721  *
722  * Note that processQueues always repeatedly processes both queues until they are empty. The
723  * process is finite because starting a service can never cause services to stop, unless they
724  * fail to start, which should cause them to stop semi-permanently.
725  */
726 class ServiceSet
727 {
728     int active_services;
729     std::list<ServiceRecord *> records;
730     const char *service_dir;  // directory containing service descriptions
731     bool restart_enabled; // whether automatic restart is enabled (allowed)
732     
733     ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
734     
735     ServiceRecord * console_queue_head = nullptr; // first record in console queue
736     ServiceRecord * console_queue_tail = nullptr; // last record in console queue
737
738     // Propagation and start/stop "queues" - list of services waiting for processing
739     ServiceRecord * first_prop_queue = nullptr;
740     ServiceRecord * first_stop_queue = nullptr;
741     
742     // Private methods
743         
744     // Load a service description, and dependencies, if there is no existing
745     // record for the given name.
746     // Throws:
747     //   ServiceLoadException (or subclass) on problem with service description
748     //   std::bad_alloc on out-of-memory condition
749     ServiceRecord *loadServiceRecord(const char *name);
750
751     // Public
752     
753     public:
754     ServiceSet(const char *service_dir)
755     {
756         this->service_dir = service_dir;
757         active_services = 0;
758         restart_enabled = true;
759     }
760     
761     // Start the service with the given name. The named service will begin
762     // transition to the 'started' state.
763     //
764     // Throws a ServiceLoadException (or subclass) if the service description
765     // cannot be loaded or is invalid;
766     // Throws std::bad_alloc if out of memory.
767     void startService(const char *name);
768     
769     // Locate an existing service record.
770     ServiceRecord *find_service(const std::string &name) noexcept;
771     
772     // Find a loaded service record, or load it if it is not loaded.
773     // Throws:
774     //   ServiceLoadException (or subclass) on problem with service description
775     //   std::bad_alloc on out-of-memory condition 
776     ServiceRecord *loadService(const std::string &name)
777     {
778         ServiceRecord *record = find_service(name);
779         if (record == nullptr) {
780             record = loadServiceRecord(name.c_str());
781         }
782         return record;
783     }
784     
785     // Get the list of all loaded services.
786     const std::list<ServiceRecord *> &listServices()
787     {
788         return records;
789     }
790     
791     // Stop the service with the given name. The named service will begin
792     // transition to the 'stopped' state.
793     void stopService(const std::string &name) noexcept;
794     
795     // Add a service record to the state propagation queue. The service record will have its
796     // do_propagation() method called when the queue is processed.
797     void addToPropQueue(ServiceRecord *service) noexcept
798     {
799         if (service->next_in_prop_queue == nullptr && first_prop_queue != service) {
800             service->next_in_prop_queue = first_prop_queue;
801             first_prop_queue = service;
802         }
803     }
804     
805     // Add a service record to the start queue. The service record will have its
806     // execute_transition() method called when the queue is processed.
807     void addToStartQueue(ServiceRecord *service) noexcept
808     {
809         // The start/stop queue is actually one queue:
810         addToStopQueue(service);
811     }
812     
813     // Add a service record to the stop queue. The service record will have its
814     // execute_transition() method called when the queue is processed.
815     void addToStopQueue(ServiceRecord *service) noexcept
816     {
817         if (service->next_in_stop_queue == nullptr && first_stop_queue != service) {
818             service->next_in_stop_queue = first_stop_queue;
819             first_stop_queue = service;
820         }
821     }
822     
823     // Process state propagation and start/stop queues, until they are empty.
824     // TODO remove the pointless parameter
825     void processQueues(bool ignoredparam = false) noexcept
826     {
827         while (first_stop_queue != nullptr || first_prop_queue != nullptr) {
828             while (first_prop_queue != nullptr) {
829                 auto next = first_prop_queue;
830                 first_prop_queue = next->next_in_prop_queue;
831                 next->next_in_prop_queue = nullptr;
832                 next->do_propagation();
833             }
834             while (first_stop_queue != nullptr) {
835                 auto next = first_stop_queue;
836                 first_stop_queue = next->next_in_stop_queue;
837                 next->next_in_stop_queue = nullptr;
838                 next->execute_transition();
839             }
840         }
841     }
842     
843     // Set the console queue tail (returns previous tail)
844     ServiceRecord * append_console_queue(ServiceRecord * newTail) noexcept
845     {
846         auto prev_tail = console_queue_tail;
847         console_queue_tail = newTail;
848         newTail->next_for_console = nullptr;
849         if (! prev_tail) {
850             console_queue_head = newTail;
851             enable_console_log(false);
852         }
853         else {
854             prev_tail->next_for_console = newTail;
855         }
856         return prev_tail;
857     }
858     
859     // Retrieve the current console queue head and remove it from the queue
860     ServiceRecord * pullConsoleQueue() noexcept
861     {
862         auto prev_head = console_queue_head;
863         if (prev_head) {
864             prev_head->acquiredConsole();
865             console_queue_head = prev_head->next_for_console;
866             if (! console_queue_head) {
867                 console_queue_tail = nullptr;
868             }
869         }
870         else {
871             enable_console_log(true);
872         }
873         return prev_head;
874     }
875     
876     // Notification from service that it is active (state != STOPPED)
877     // Only to be called on the transition from inactive to active.
878     void service_active(ServiceRecord *) noexcept;
879     
880     // Notification from service that it is inactive (STOPPED)
881     // Only to be called on the transition from active to inactive.
882     void service_inactive(ServiceRecord *) noexcept;
883     
884     // Find out how many services are active (starting, running or stopping,
885     // but not stopped).
886     int count_active_services() noexcept
887     {
888         return active_services;
889     }
890     
891     void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
892     {
893         restart_enabled = false;
894         shutdown_type = type;
895         for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
896             (*i)->stop(false);
897             (*i)->unpin();
898         }
899         processQueues(false);
900     }
901     
902     void set_auto_restart(bool restart) noexcept
903     {
904         restart_enabled = restart;
905     }
906     
907     bool get_auto_restart() noexcept
908     {
909         return restart_enabled;
910     }
911     
912     ShutdownType getShutdownType() noexcept
913     {
914         return shutdown_type;
915     }
916 };
917
918 #endif