Rename 'all_deps_stopped' function to 'bring_down'.
[oweals/dinit.git] / src / service.h
index 8b052d857eadc14fec8aecac026b20b2d623d67c..5fa51bcffb40cd9a0b84fc08e3875b00b3f4c41b 100644 (file)
@@ -6,6 +6,7 @@
 #include <vector>
 #include <csignal>
 #include <unordered_set>
+#include <algorithm>
 
 #include "dasynq.h"
 
@@ -15,8 +16,8 @@
 #include "dinit-ll.h"
 
 /*
- * This header defines ServiceRecord, a data record maintaining information about a service,
- * and ServiceSet, a set of interdependent service records. It also defines some associated
+ * This header defines service_record, a data record maintaining information about a service,
+ * and service_set, a set of interdependent service records. It also defines some associated
  * types and exceptions.
  *
  * Service states
  * transition stage, at the latest.
  */
 
-struct OnstartFlags {
-    bool rw_ready : 1;
-    bool log_ready : 1;
+struct onstart_flags_t {
+    bool rw_ready : 1;  // file system should be writable once this service starts
+    bool log_ready : 1; // syslog should be available once this service starts
     
     // Not actually "onstart" commands:
     bool no_sigterm : 1;  // do not send SIGTERM
@@ -111,62 +112,70 @@ struct OnstartFlags {
     bool starts_on_console : 1; // starts in the foreground
     bool pass_cs_fd : 1;  // pass this service a control socket connection via fd
     
-    OnstartFlags() noexcept : rw_ready(false), log_ready(false),
+    onstart_flags_t() noexcept : rw_ready(false), log_ready(false),
             no_sigterm(false), runs_on_console(false), starts_on_console(false), pass_cs_fd(false)
     {
     }
 };
 
 // Exception while loading a service
-class ServiceLoadExc
+class service_load_exc
 {
     public:
     std::string serviceName;
     std::string excDescription;
     
     protected:
-    ServiceLoadExc(std::string serviceName, std::string &&desc) noexcept
+    service_load_exc(std::string serviceName, std::string &&desc) noexcept
         : serviceName(serviceName), excDescription(std::move(desc))
     {
     }
 };
 
-class ServiceNotFound : public ServiceLoadExc
+class service_not_found : public service_load_exc
 {
     public:
-    ServiceNotFound(std::string serviceName) noexcept
-        : ServiceLoadExc(serviceName, "Service description not found.")
+    service_not_found(std::string serviceName) noexcept
+        : service_load_exc(serviceName, "Service description not found.")
     {
     }
 };
 
-class ServiceCyclicDependency : public ServiceLoadExc
+class service_cyclic_dependency : public service_load_exc
 {
     public:
-    ServiceCyclicDependency(std::string serviceName) noexcept
-        : ServiceLoadExc(serviceName, "Has cyclic dependency.")
+    service_cyclic_dependency(std::string serviceName) noexcept
+        : service_load_exc(serviceName, "Has cyclic dependency.")
     {
     }
 };
 
-class ServiceDescriptionExc : public ServiceLoadExc
+class service_description_exc : public service_load_exc
 {
     public:
-    ServiceDescriptionExc(std::string serviceName, std::string &&extraInfo) noexcept
-        : ServiceLoadExc(serviceName, std::move(extraInfo))
+    service_description_exc(std::string serviceName, std::string &&extraInfo) noexcept
+        : service_load_exc(serviceName, std::move(extraInfo))
     {
     }    
 };
 
-class ServiceRecord;
-class ServiceSet;
+class service_record;
+class service_set;
 class base_process_service;
 
+enum class dependency_type
+{
+    REGULAR,
+    SOFT,       // dependency starts in parallel, failure/stop does not affect dependent
+    WAITS_FOR,  // as for SOFT, but dependent waits until dependency starts/fails before starting
+    MILESTONE   // dependency must start successfully, but once started the dependency becomes soft
+};
+
 /* Service dependency record */
-class ServiceDep
+class service_dep
 {
-    ServiceRecord * from;
-    ServiceRecord * to;
+    service_record * from;
+    service_record * to;
 
     public:
     /* Whether the 'from' service is waiting for the 'to' service to start */
@@ -174,20 +183,36 @@ class ServiceDep
     /* Whether the 'from' service is holding an acquire on the 'to' service */
     bool holding_acq;
 
-    ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false), holding_acq(false)
+    const dependency_type dep_type;
+
+    service_dep(service_record * from, service_record * to, dependency_type dep_type_p) noexcept
+            : from(from), to(to), waiting_on(false), holding_acq(false), dep_type(dep_type_p)
     {  }
 
-    ServiceRecord * getFrom() noexcept
+    service_record * get_from() noexcept
     {
         return from;
     }
 
-    ServiceRecord * getTo() noexcept
+    service_record * get_to() noexcept
     {
         return to;
     }
 };
 
+/* preliminary service dependency information */
+class prelim_dep
+{
+    public:
+    service_record * const to;
+    dependency_type const dep_type;
+
+    prelim_dep(service_record *to_p, dependency_type dep_type_p) : to(to_p), dep_type(dep_type_p)
+    {
+        //
+    }
+};
+
 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
 // store a null terminator for the argument. Return a `char *` vector containing the beginning
 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
@@ -212,33 +237,36 @@ static std::vector<const char *> separate_args(std::string &s, std::list<std::pa
     return r;
 }
 
-class ServiceChildWatcher : public EventLoop_t::child_proc_watcher_impl<ServiceChildWatcher>
+class service_child_watcher : public eventloop_t::child_proc_watcher_impl<service_child_watcher>
 {
     public:
     base_process_service * service;
-    rearm status_change(EventLoop_t &eloop, pid_t child, int status) noexcept;
+    rearm status_change(eventloop_t &eloop, pid_t child, int status) noexcept;
     
-    ServiceChildWatcher(base_process_service * sr) noexcept : service(sr) { }
+    service_child_watcher(base_process_service * sr) noexcept : service(sr) { }
 };
 
-class ServiceIoWatcher : public EventLoop_t::fd_watcher_impl<ServiceIoWatcher>
+// Watcher for the pipe used to receive exec() failure status errno
+class exec_status_pipe_watcher : public eventloop_t::fd_watcher_impl<exec_status_pipe_watcher>
 {
     public:
     base_process_service * service;
-    rearm fd_event(EventLoop_t &eloop, int fd, int flags) noexcept;
+    rearm fd_event(eventloop_t &eloop, int fd, int flags) noexcept;
     
-    ServiceIoWatcher(base_process_service * sr) noexcept : service(sr) { }
+    exec_status_pipe_watcher(base_process_service * sr) noexcept : service(sr) { }
 };
 
-class ServiceRecord
+// service_record: base class for service record containing static information
+// and current state of each service.
+class service_record
 {
     protected:
     typedef std::string string;
     
     string service_name;
-    ServiceType service_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
-    ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
-    ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
+    service_type record_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
+    service_state_t service_state = service_state_t::STOPPED; /* service_state_t::STOPPED, STARTING, STARTED, STOPPING */
+    service_state_t desired_state = service_state_t::STOPPED; /* service_state_t::STOPPED / STARTED */
 
     string program_name;          // storage for program/script and arguments
     std::vector<const char *> exec_arg_parts; // pointer to each argument/part of the program_name, and nullptr
@@ -248,7 +276,7 @@ class ServiceRecord
     
     string pid_file;
     
-    OnstartFlags onstart_flags;
+    onstart_flags_t onstart_flags;
 
     string logfile;           // log file name, empty string specifies /dev/null
     
@@ -258,38 +286,32 @@ class ServiceRecord
     bool pinned_stopped : 1;
     bool pinned_started : 1;
     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
+                                // if STOPPING, whether we are waiting for dependents to stop
     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
-    bool start_explicit : 1;    // whether we are are explictly required to be started
+    bool start_explicit : 1;    // whether we are are explicitly required to be started
 
     bool prop_require : 1;      // require must be propagated
     bool prop_release : 1;      // release must be propagated
     bool prop_failure : 1;      // failure to start must be propagated
     bool prop_start   : 1;
     bool prop_stop    : 1;
-    bool restarting : 1;        // re-starting after unexpected termination
+
+    bool restarting   : 1;      // re-starting after unexpected termination
     
     int required_by = 0;        // number of dependents wanting this service to be started
 
-    typedef std::list<ServiceRecord *> sr_list;
-    typedef sr_list::iterator sr_iter;
+    // list of dependencies
+    typedef std::list<service_dep> dep_list;
     
-    // list of soft dependencies
-    typedef std::list<ServiceDep> softdep_list;
+    // list of dependents
+    typedef std::list<service_dep *> dpt_list;
     
-    // list of soft dependents
-    typedef std::list<ServiceDep *> softdpt_list;
+    dep_list depends_on;  // services this one depends on
+    dpt_list dependents;  // services depending on this one
     
-    sr_list depends_on; // services this one depends on
-    sr_list dependents; // services depending on this one
-    softdep_list soft_deps;  // services this one depends on via a soft dependency
-    softdpt_list soft_dpts;  // services depending on this one via a soft dependency
+    service_set *services; // the set this service belongs to
     
-    // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
-    //                         start/stop, this is how many we're waiting for */
-    
-    ServiceSet *service_set; // the set this service belongs to
-    
-    std::unordered_set<ServiceListener *> listeners;
+    std::unordered_set<service_listener *> listeners;
     
     // Process services:
     bool force_stop; // true if the service must actually stop. This is the
@@ -312,21 +334,23 @@ class ServiceRecord
     int socket_fd = -1;  // For socket-activation services, this is the file
                          // descriptor for the socket.
     
-    
-    // Data for use by ServiceSet
+    // Data for use by service_set
     public:
     
     // Console queue.
-    lld_node<ServiceRecord> console_queue_node;
+    lld_node<service_record> console_queue_node;
     
     // Propagation and start/stop queues
-    lls_node<ServiceRecord> prop_queue_node;
-    lls_node<ServiceRecord> stop_queue_node;
+    lls_node<service_record> prop_queue_node;
+    lls_node<service_record> stop_queue_node;
     
     protected:
     
-    // All dependents have stopped.
-    virtual void all_deps_stopped() noexcept;
+    // stop immediately
+    void emergency_stop() noexcept;
+
+    // All dependents have stopped, and this service should proceed to stop.
+    virtual void bring_down() noexcept;
     
     // Service has actually stopped (includes having all dependents
     // reaching STOPPED state).
@@ -342,16 +366,10 @@ class ServiceRecord
     void run_child_proc(const char * const *args, const char *logfile, bool on_console, int wpipefd,
             int csfd) noexcept;
     
-    // Callback from libev when a child process dies
-    static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
-            int revents) noexcept;
-    
-    //virtual void handle_exit_status(int exit_status) noexcept;
-
     // A dependency has reached STARTED state
-    void dependencyStarted() noexcept;
+    void dependency_started() noexcept;
     
-    void allDepsStarted(bool haveConsole = false) noexcept;
+    void all_deps_started(bool haveConsole = false) noexcept;
 
     // Do any post-dependency startup; return false on failure
     virtual bool start_ps_process() noexcept;
@@ -359,8 +377,11 @@ class ServiceRecord
     // Open the activation socket, return false on failure
     bool open_socket() noexcept;
 
-    // Check whether dependencies have started, and optionally ask them to start
-    bool startCheckDependencies(bool do_start) noexcept;
+    // Start all dependencies, return true if all have started
+    bool start_check_dependencies() noexcept;
+
+    // Check whether all dependencies have started (i.e. whether we can start now)
+    bool check_deps_started() noexcept;
 
     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
     // having to wait for it reach STARTED and then go through STOPPING).
@@ -369,6 +390,13 @@ class ServiceRecord
         return waiting_for_deps;
     }
     
+    // Whether a STARTING service can transition to its STARTED state, once all
+    // dependencies have started.
+    virtual bool can_proceed_to_start() noexcept
+    {
+        return true;
+    }
+
     virtual void interrupt_start() noexcept;
 
     // Whether a STOPPING service can immediately transition to STARTED.
@@ -378,13 +406,13 @@ class ServiceRecord
     }
 
     // A dependent has reached STOPPED state
-    void dependentStopped() noexcept;
+    void dependent_stopped() noexcept;
 
     // check if all dependents have stopped
-    bool stopCheckDependents() noexcept;
+    bool stop_check_dependents() noexcept;
     
     // issue a stop to all dependents, return true if they are all already stopped
-    bool stopDependents() noexcept;
+    bool stop_dependents() noexcept;
     
     void require() noexcept;
     void release() noexcept;
@@ -393,18 +421,18 @@ class ServiceRecord
     // Check if service is, fundamentally, stopped.
     bool is_stopped() noexcept
     {
-        return service_state == ServiceState::STOPPED
-            || (service_state == ServiceState::STARTING && waiting_for_deps);
+        return service_state == service_state_t::STOPPED
+            || (service_state == service_state_t::STARTING && waiting_for_deps);
     }
     
-    void notifyListeners(ServiceEvent event) noexcept
+    void notify_listeners(service_event_t event) noexcept
     {
         for (auto l : listeners) {
-            l->serviceEvent(this, event);
+            l->service_event(this, event);
         }
     }
     
-    // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
+    // Queue to run on the console. 'acquired_console()' will be called when the console is available.
     // Has no effect if the service has already queued for console.
     void queue_for_console() noexcept;
     
@@ -416,47 +444,53 @@ class ServiceRecord
     // Started state reached
     bool process_started() noexcept;
 
+    // Called on transition of desired state from stopped to started (or unpinned stop)
+    void do_start() noexcept;
+
+    // Called on transition of desired state from started to stopped (or unpinned start)
+    void do_stop() noexcept;
+
     public:
 
-    ServiceRecord(ServiceSet *set, string name)
-        : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED),
+    service_record(service_set *set, string name)
+        : service_state(service_state_t::STOPPED), desired_state(service_state_t::STOPPED),
             auto_restart(false), smooth_recovery(false),
             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
             waiting_for_execstat(false), start_explicit(false),
             prop_require(false), prop_release(false), prop_failure(false),
             prop_start(false), prop_stop(false), restarting(false), force_stop(false)
     {
-        service_set = set;
+        services = set;
         service_name = name;
-        service_type = ServiceType::DUMMY;
+        record_type = service_type::DUMMY;
+        socket_perms = 0;
+        exit_status = 0;
     }
-    
-    ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
-            sr_list * pdepends_on, sr_list * pdepends_soft)
-        : ServiceRecord(set, name)
+
+    service_record(service_set *set, string name, service_type record_type_p,
+            const std::list<prelim_dep> &deplist_p)
+        : service_record(set, name)
     {
-        service_set = set;
+        services = set;
         service_name = name;
-        this->service_type = service_type;
-        this->depends_on = std::move(*pdepends_on);
+        this->record_type = record_type_p;
 
+        for (auto & pdep : deplist_p) {
+            auto b = depends_on.emplace(depends_on.end(), this, pdep.to, pdep.dep_type);
+            pdep.to->dependents.push_back(&(*b));
+        }
+    }
+    
+    service_record(service_set *set, string name, service_type record_type_p, string &&command,
+            std::list<std::pair<unsigned,unsigned>> &command_offsets,
+            const std::list<prelim_dep> &deplist_p)
+        : service_record(set, name, record_type_p, deplist_p)
+    {
         program_name = std::move(command);
         exec_arg_parts = separate_args(program_name, command_offsets);
-
-        for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
-            (*i)->dependents.push_back(this);
-        }
-
-        // Soft dependencies
-        auto b_iter = soft_deps.end();
-        for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
-            b_iter = soft_deps.emplace(b_iter, this, *i);
-            (*i)->soft_dpts.push_back(&(*b_iter));
-            ++b_iter;
-        }
     }
     
-    virtual ~ServiceRecord() noexcept
+    virtual ~service_record() noexcept
     {
     }
     
@@ -464,60 +498,48 @@ class ServiceRecord
     void execute_transition() noexcept;
     
     void do_propagation() noexcept;
-    
-    // Called on transition of desired state from stopped to started (or unpinned stop)
-    void do_start() noexcept;
 
-    // Called on transition of desired state from started to stopped (or unpinned start)
-    void do_stop() noexcept;
-    
     // Console is available.
-    void acquiredConsole() noexcept;
+    void acquired_console() noexcept;
     
     // Set the stop command and arguments (may throw std::bad_alloc)
-    void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
+    void set_stop_command(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
     {
         stop_command = command;
         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
     }
     
-    // Get the current service state.
-    ServiceState getState() noexcept
-    {
-        return service_state;
-    }
-    
     // Get the target (aka desired) state.
-    ServiceState getTargetState() noexcept
+    service_state_t get_target_state() noexcept
     {
         return desired_state;
     }
 
     // Set logfile, should be done before service is started
-    void setLogfile(string logfile)
+    void set_log_file(string logfile)
     {
         this->logfile = logfile;
     }
     
     // Set whether this service should automatically restart when it dies
-    void setAutoRestart(bool auto_restart) noexcept
+    void set_auto_restart(bool auto_restart) noexcept
     {
         this->auto_restart = auto_restart;
     }
     
-    void setSmoothRecovery(bool smooth_recovery) noexcept
+    void set_smooth_recovery(bool smooth_recovery) noexcept
     {
         this->smooth_recovery = smooth_recovery;
     }
     
     // Set "on start" flags (commands)
-    void setOnstartFlags(OnstartFlags flags) noexcept
+    void set_flags(onstart_flags_t flags) noexcept
     {
         this->onstart_flags = flags;
     }
     
     // Set an additional signal (other than SIGTERM) to be used to terminate the process
-    void setExtraTerminationSignal(int signo) noexcept
+    void set_extra_termination_signal(int signo) noexcept
     {
         this->term_signal = signo;
     }
@@ -535,22 +557,22 @@ class ServiceRecord
         this->socket_gid = socket_gid;
     }
 
-    const std::string &getServiceName() const noexcept { return service_name; }
-    ServiceState getState() const noexcept { return service_state; }
+    const std::string &get_service_name() const noexcept { return service_name; }
+    service_state_t get_state() const noexcept { return service_state; }
     
     void start(bool activate = true) noexcept;  // start the service
     void stop(bool bring_down = true) noexcept;   // stop the service
     
-    void forceStop() noexcept; // force-stop this service and all dependents
+    void forced_stop() noexcept; // force-stop this service and all dependents
     
     // Pin the service in "started" state (when it reaches the state)
-    void pinStart() noexcept
+    void pin_start() noexcept
     {
         pinned_started = true;
     }
     
     // Pin the service in "stopped" state (when it reaches the state)
-    void pinStop() noexcept
+    void pin_stop() noexcept
     {
         pinned_stopped = true;
     }
@@ -562,17 +584,17 @@ class ServiceRecord
     
     bool isDummy() noexcept
     {
-        return service_type == ServiceType::DUMMY;
+        return record_type == service_type::DUMMY;
     }
     
     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
-    void addListener(ServiceListener * listener)
+    void addListener(service_listener * listener)
     {
         listeners.insert(listener);
     }
     
     // Remove a listener.    
-    void removeListener(ServiceListener * listener) noexcept
+    void removeListener(service_listener * listener) noexcept
     {
         listeners.erase(listener);
     }
@@ -580,9 +602,9 @@ class ServiceRecord
 
 class base_process_service;
 
-// A timer for process restarting. Used to ensure a minimum delay between
-// process restarts.
-class process_restart_timer : public EventLoop_t::timer_impl<process_restart_timer>
+// A timer for process restarting. Used to ensure a minimum delay between process restarts (and
+// also for timing service stop before the SIGKILL hammer is used).
+class process_restart_timer : public eventloop_t::timer_impl<process_restart_timer>
 {
     public:
     base_process_service * service;
@@ -591,13 +613,13 @@ class process_restart_timer : public EventLoop_t::timer_impl<process_restart_tim
     {
     }
 
-    rearm timer_expiry(EventLoop_t &, int expiry_count);
+    rearm timer_expiry(eventloop_t &, int expiry_count);
 };
 
-class base_process_service : public ServiceRecord
+class base_process_service : public service_record
 {
-    friend class ServiceChildWatcher;
-    friend class ServiceIoWatcher;
+    friend class service_child_watcher;
+    friend class exec_status_pipe_watcher;
     friend class process_restart_timer;
 
     private:
@@ -605,21 +627,28 @@ class base_process_service : public ServiceRecord
     void do_restart() noexcept;
 
     protected:
-    ServiceChildWatcher child_listener;
-    ServiceIoWatcher child_status_listener;
+    service_child_watcher child_listener;
+    exec_status_pipe_watcher child_status_listener;
     process_restart_timer restart_timer;
-    timespec last_start_time;
+    time_val last_start_time;
 
     // Restart interval time and restart count are used to track the number of automatic restarts
     // over an interval. Too many restarts over an interval will inhibit further restarts.
-    timespec restart_interval_time;
+    time_val restart_interval_time;
     int restart_interval_count;
 
-    timespec restart_interval;
+    time_val restart_interval;
     int max_restart_interval_count;
-    timespec restart_delay;
+    time_val restart_delay;
+
+    // Time allowed for service stop, after which SIGKILL is sent. 0 to disable.
+    time_val stop_timeout = {10, 0}; // default of 10 seconds
 
-    bool waiting_restart_timer = false;
+    bool waiting_restart_timer : 1;
+    bool stop_timer_armed : 1;
+    bool reserved_child_watch : 1;
+    bool tracking_child : 1;  // whether we expect to see child process status
+    bool start_is_interruptible : 1;  // whether we can interrupt start
 
     // Start the process, return true on success
     virtual bool start_ps_process() noexcept override;
@@ -629,20 +658,38 @@ class base_process_service : public ServiceRecord
     // rate-limited.
     bool restart_ps_process() noexcept;
 
-    virtual void all_deps_stopped() noexcept override;
+    // Perform smooth recovery process
+    void do_smooth_recovery() noexcept;
+
+    virtual void bring_down() noexcept override;
+
+    // Called when the process exits. The exit_status is the status value yielded by
+    // the "wait" system call.
     virtual void handle_exit_status(int exit_status) noexcept = 0;
+    virtual void exec_failed(int errcode) noexcept = 0;
 
     virtual bool can_interrupt_start() noexcept override
     {
-        return waiting_restart_timer || ServiceRecord::can_interrupt_start();
+        return waiting_restart_timer || service_record::can_interrupt_start();
+    }
+
+    virtual bool can_proceed_to_start() noexcept override
+    {
+        return ! waiting_restart_timer;
     }
 
     virtual void interrupt_start() noexcept override;
 
+    // Kill with SIGKILL
+    void kill_with_fire() noexcept;
+
+    // Signal the process group of the service process
+    void kill_pg(int signo) noexcept;
+
     public:
-    base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
+    base_process_service(service_set *sset, string name, service_type record_type_p, string &&command,
             std::list<std::pair<unsigned,unsigned>> &command_offsets,
-            sr_list * pdepends_on, sr_list * pdepends_soft);
+            const std::list<prelim_dep> &deplist_p);
 
     ~base_process_service() noexcept
     {
@@ -658,20 +705,25 @@ class base_process_service : public ServiceRecord
     {
         restart_delay = delay;
     }
+
+    void set_stop_timeout(timespec timeout) noexcept
+    {
+        stop_timeout = timeout;
+    }
 };
 
 class process_service : public base_process_service
 {
-    // called when the process exits. The exit_status is the status value yielded by
-    // the "wait" system call.
     virtual void handle_exit_status(int exit_status) noexcept override;
+    virtual void exec_failed(int errcode) noexcept override;
+    virtual void bring_down() noexcept override;
 
     public:
-    process_service(ServiceSet *sset, string name, string &&command,
+    process_service(service_set *sset, string name, string &&command,
             std::list<std::pair<unsigned,unsigned>> &command_offsets,
-            sr_list * pdepends_on, sr_list * pdepends_soft)
-         : base_process_service(sset, name, ServiceType::PROCESS, std::move(command), command_offsets,
-             pdepends_on, pdepends_soft)
+            std::list<prelim_dep> depends_p)
+         : base_process_service(sset, name, service_type::PROCESS, std::move(command), command_offsets,
+             depends_p)
     {
     }
 
@@ -683,21 +735,24 @@ class process_service : public base_process_service
 class bgproc_service : public base_process_service
 {
     virtual void handle_exit_status(int exit_status) noexcept override;
+    virtual void exec_failed(int errcode) noexcept override;
 
-    bool doing_recovery : 1;    // if we are currently recovering a BGPROCESS (restarting process, while
-                                //   holding STARTED service state)
+    enum class pid_result_t {
+        OK,
+        FAILED,      // failed to read pid or read invalid pid
+        TERMINATED   // read pid successfully, but the process already terminated
+    };
 
     // Read the pid-file, return false on failure
-    bool read_pid_file() noexcept;
+    pid_result_t read_pid_file(int *exit_status) noexcept;
 
     public:
-    bgproc_service(ServiceSet *sset, string name, string &&command,
+    bgproc_service(service_set *sset, string name, string &&command,
             std::list<std::pair<unsigned,unsigned>> &command_offsets,
-            sr_list * pdepends_on, sr_list * pdepends_soft)
-         : base_process_service(sset, name, ServiceType::BGPROCESS, std::move(command), command_offsets,
-             pdepends_on, pdepends_soft)
+            std::list<prelim_dep> depends_p)
+         : base_process_service(sset, name, service_type::BGPROCESS, std::move(command), command_offsets,
+             depends_p)
     {
-        doing_recovery = false;
     }
 
     ~bgproc_service() noexcept
@@ -707,15 +762,16 @@ class bgproc_service : public base_process_service
 
 class scripted_service : public base_process_service
 {
-    virtual void all_deps_stopped() noexcept override;
     virtual void handle_exit_status(int exit_status) noexcept override;
+    virtual void exec_failed(int errcode) noexcept override;
+    virtual void bring_down() noexcept override;
 
     public:
-    scripted_service(ServiceSet *sset, string name, string &&command,
+    scripted_service(service_set *sset, string name, string &&command,
             std::list<std::pair<unsigned,unsigned>> &command_offsets,
-            sr_list * pdepends_on, sr_list * pdepends_soft)
-         : base_process_service(sset, name, ServiceType::SCRIPTED, std::move(command), command_offsets,
-             pdepends_on, pdepends_soft)
+            std::list<prelim_dep> depends_p)
+         : base_process_service(sset, name, service_type::SCRIPTED, std::move(command), command_offsets,
+             depends_p)
     {
     }
 
@@ -724,23 +780,23 @@ class scripted_service : public base_process_service
     }
 };
 
-inline auto extract_prop_queue(ServiceRecord *sr) -> decltype(sr->prop_queue_node) &
+inline auto extract_prop_queue(service_record *sr) -> decltype(sr->prop_queue_node) &
 {
     return sr->prop_queue_node;
 }
 
-inline auto extract_stop_queue(ServiceRecord *sr) -> decltype(sr->stop_queue_node) &
+inline auto extract_stop_queue(service_record *sr) -> decltype(sr->stop_queue_node) &
 {
     return sr->stop_queue_node;
 }
 
-inline auto extract_console_queue(ServiceRecord *sr) -> decltype(sr->console_queue_node) &
+inline auto extract_console_queue(service_record *sr) -> decltype(sr->console_queue_node) &
 {
     return sr->console_queue_node;
 }
 
 /*
- * A ServiceSet, as the name suggests, manages a set of services.
+ * A service_set, as the name suggests, manages a set of services.
  *
  * Other than the ability to find services by name, the service set manages various queues.
  * One is the queue for processes wishing to acquire the console. There is also a set of
@@ -757,95 +813,112 @@ inline auto extract_console_queue(ServiceRecord *sr) -> decltype(sr->console_que
  * process is finite because starting a service can never cause services to stop, unless they
  * fail to start, which should cause them to stop semi-permanently.
  */
-class ServiceSet
+class service_set
 {
+    protected:
     int active_services;
-    std::list<ServiceRecord *> records;
-    const char *service_dir;  // directory containing service descriptions
+    std::list<service_record *> records;
     bool restart_enabled; // whether automatic restart is enabled (allowed)
     
-    ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
+    shutdown_type_t shutdown_type = shutdown_type_t::CONTINUE;  // Shutdown type, if stopping
     
     // Services waiting for exclusive access to the console
-    dlist<ServiceRecord, extract_console_queue> console_queue;
+    dlist<service_record, extract_console_queue> console_queue;
 
     // Propagation and start/stop "queues" - list of services waiting for processing
-    slist<ServiceRecord, extract_prop_queue> prop_queue;
-    slist<ServiceRecord, extract_stop_queue> stop_queue;
+    slist<service_record, extract_prop_queue> prop_queue;
+    slist<service_record, extract_stop_queue> stop_queue;
     
-    // Private methods
-        
+    public:
+    service_set()
+    {
+        active_services = 0;
+        restart_enabled = true;
+    }
+    
+    virtual ~service_set()
+    {
+        for (auto * s : records) {
+            delete s;
+        }
+    }
+
+    // Start the specified service. The service will be marked active.
+    void start_service(service_record *svc)
+    {
+        svc->start();
+        process_queues();
+    }
+
+    // Stop the specified service. Its active mark will be cleared.
+    void stop_service(service_record *svc)
+    {
+        svc->stop(true);
+        process_queues();
+    }
+
+    // Locate an existing service record.
+    service_record *find_service(const std::string &name) noexcept;
+
     // Load a service description, and dependencies, if there is no existing
     // record for the given name.
     // Throws:
     //   ServiceLoadException (or subclass) on problem with service description
     //   std::bad_alloc on out-of-memory condition
-    ServiceRecord *loadServiceRecord(const char *name);
-
-    // Public
-    
-    public:
-    ServiceSet(const char *service_dir)
+    virtual service_record *load_service(const char *name)
     {
-        this->service_dir = service_dir;
-        active_services = 0;
-        restart_enabled = true;
+        auto r = find_service(name);
+        if (r == nullptr) {
+            throw service_not_found(name);
+        }
+        return r;
     }
-    
+
     // Start the service with the given name. The named service will begin
     // transition to the 'started' state.
     //
     // Throws a ServiceLoadException (or subclass) if the service description
     // cannot be loaded or is invalid;
     // Throws std::bad_alloc if out of memory.
-    void startService(const char *name);
-    
-    // Locate an existing service record.
-    ServiceRecord *find_service(const std::string &name) noexcept;
+    void start_service(const char *name)
+    {
+        using namespace std;
+        service_record *record = load_service(name);
+        service_set::start_service(record);
+    }
     
-    // Find a loaded service record, or load it if it is not loaded.
-    // Throws:
-    //   ServiceLoadException (or subclass) on problem with service description
-    //   std::bad_alloc on out-of-memory condition 
-    ServiceRecord *loadService(const std::string &name)
+    void add_service(service_record *svc)
     {
-        ServiceRecord *record = find_service(name);
-        if (record == nullptr) {
-            record = loadServiceRecord(name.c_str());
-        }
-        return record;
+        records.push_back(svc);
     }
     
+    void remove_service(service_record *svc)
+    {
+        std::remove(records.begin(), records.end(), svc);
+    }
+
     // Get the list of all loaded services.
-    const std::list<ServiceRecord *> &listServices()
+    const std::list<service_record *> &list_services() noexcept
     {
         return records;
     }
     
     // Stop the service with the given name. The named service will begin
     // transition to the 'stopped' state.
-    void stopService(const std::string &name) noexcept;
+    void stop_service(const std::string &name) noexcept;
     
     // Add a service record to the state propagation queue. The service record will have its
     // do_propagation() method called when the queue is processed.
-    void addToPropQueue(ServiceRecord *service) noexcept
+    void add_prop_queue(service_record *service) noexcept
     {
         if (! prop_queue.is_queued(service)) {
             prop_queue.insert(service);
         }
     }
     
-    // Add a service record to the start queue. The service record will have its
-    // execute_transition() method called when the queue is processed.
-    void addToStartQueue(ServiceRecord *service) noexcept
-    {
-        // The start/stop queue is actually one queue:
-        addToStopQueue(service);
-    }
-    
     // Add a service record to the stop queue. The service record will have its
     // execute_transition() method called when the queue is processed.
-    void addToStopQueue(ServiceRecord *service) noexcept
+    void add_transition_queue(service_record *service) noexcept
     {
         if (! stop_queue.is_queued(service)) {
             stop_queue.insert(service);
@@ -853,8 +926,7 @@ class ServiceSet
     }
     
     // Process state propagation and start/stop queues, until they are empty.
-    // TODO remove the pointless parameter
-    void processQueues(bool ignoredparam = false) noexcept
+    void process_queues() noexcept
     {
         while (! stop_queue.is_empty() || ! prop_queue.is_empty()) {
             while (! prop_queue.is_empty()) {
@@ -869,20 +941,28 @@ class ServiceSet
     }
     
     // Set the console queue tail (returns previous tail)
-    void append_console_queue(ServiceRecord * newTail) noexcept
+    void append_console_queue(service_record * newTail) noexcept
     {
-        if (! console_queue.is_queued(newTail)) {
-            console_queue.append(newTail);
+        bool was_empty = console_queue.is_empty();
+        console_queue.append(newTail);
+        if (was_empty) {
+            enable_console_log(false);
         }
     }
     
-    // Retrieve the current console queue head and remove it from the queue
-    ServiceRecord * pull_console_queue() noexcept
+    // Pull and dispatch a waiter from the console queue
+    void pull_console_queue() noexcept
     {
-        return console_queue.pop_front();
+        if (console_queue.is_empty()) {
+            enable_console_log(true);
+        }
+        else {
+            service_record * front = console_queue.pop_front();
+            front->acquired_console();
+        }
     }
     
-    void unqueue_console(ServiceRecord * service) noexcept
+    void unqueue_console(service_record * service) noexcept
     {
         if (console_queue.is_queued(service)) {
             console_queue.unlink(service);
@@ -891,11 +971,11 @@ class ServiceSet
 
     // Notification from service that it is active (state != STOPPED)
     // Only to be called on the transition from inactive to active.
-    void service_active(ServiceRecord *) noexcept;
+    void service_active(service_record *) noexcept;
     
     // Notification from service that it is inactive (STOPPED)
     // Only to be called on the transition from active to inactive.
-    void service_inactive(ServiceRecord *) noexcept;
+    void service_inactive(service_record *) noexcept;
     
     // Find out how many services are active (starting, running or stopping,
     // but not stopped).
@@ -904,15 +984,15 @@ class ServiceSet
         return active_services;
     }
     
-    void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
+    void stop_all_services(shutdown_type_t type = shutdown_type_t::HALT) noexcept
     {
         restart_enabled = false;
         shutdown_type = type;
-        for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
+        for (std::list<service_record *>::iterator i = records.begin(); i != records.end(); ++i) {
             (*i)->stop(false);
             (*i)->unpin();
         }
-        processQueues(false);
+        process_queues();
     }
     
     void set_auto_restart(bool restart) noexcept
@@ -925,10 +1005,22 @@ class ServiceSet
         return restart_enabled;
     }
     
-    ShutdownType getShutdownType() noexcept
+    shutdown_type_t getShutdownType() noexcept
     {
         return shutdown_type;
     }
 };
 
+class dirload_service_set : public service_set
+{
+    const char *service_dir;  // directory containing service descriptions
+
+    public:
+    dirload_service_set(const char *service_dir_p) : service_set(), service_dir(service_dir_p)
+    {
+    }
+
+    service_record *load_service(const char *name) override;
+};
+
 #endif