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