8 #include <unordered_set>
13 #include "service-listener.h"
14 #include "service-constants.h"
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.
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.
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
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.
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.
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 depdendents 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).
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).
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).
65 * The priority of the different state deciders is:
68 * - desired state (which is manipulated by require/release operations)
70 * So a forced stop cannot occur until the service is not pinned started, for instance.
76 // Not actually "onstart" commands:
77 bool no_sigterm : 1; // do not send SIGTERM
78 bool runs_on_console : 1; // run "in the foreground"
80 OnstartFlags() noexcept : rw_ready(false),
81 no_sigterm(false), runs_on_console(false)
86 // Exception while loading a service
90 std::string serviceName;
91 const char *excDescription;
94 ServiceLoadExc(std::string serviceName) noexcept
95 : serviceName(serviceName)
100 class ServiceNotFound : public ServiceLoadExc
103 ServiceNotFound(std::string serviceName) noexcept
104 : ServiceLoadExc(serviceName)
106 excDescription = "Service description not found.";
110 class ServiceCyclicDependency : public ServiceLoadExc
113 ServiceCyclicDependency(std::string serviceName) noexcept
114 : ServiceLoadExc(serviceName)
116 excDescription = "Has cyclic dependency.";
120 class ServiceDescriptionExc : public ServiceLoadExc
123 std::string extraInfo;
125 ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
126 : ServiceLoadExc(serviceName), extraInfo(extraInfo)
128 excDescription = extraInfo.c_str();
132 class ServiceRecord; // forward declaration
133 class ServiceSet; // forward declaration
135 /* Service dependency record */
138 ServiceRecord * from;
142 /* Whether the 'from' service is waiting for the 'to' service to start */
145 ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false)
148 ServiceRecord * getFrom() noexcept
153 ServiceRecord * getTo() noexcept
159 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
160 // store a null terminator for the argument. Return a `char *` vector containing the beginning
161 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
162 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
164 std::vector<const char *> r;
165 r.reserve(arg_indices.size() + 1);
167 // First store nul terminator for each part:
168 for (auto index_pair : arg_indices) {
169 if (index_pair.second < s.length()) {
170 s[index_pair.second] = 0;
174 // Now we can get the C string (c_str) and store offsets into it:
175 const char * cstr = s.c_str();
176 for (auto index_pair : arg_indices) {
177 r.push_back(cstr + index_pair.first);
179 r.push_back(nullptr);
183 class ServiceChildWatcher : public EventLoop_t::ChildProcWatcher
186 // TODO resolve clunkiness of storing this field
187 ServiceRecord * service;
188 void gotTermStat(EventLoop_t * eloop, pid_t child, int status) noexcept;
190 ServiceChildWatcher(ServiceRecord * sr) noexcept : service(sr) { }
193 class ServiceIoWatcher : public EventLoop_t::FdWatcher
196 // TODO resolve clunkiness of storing these fields
198 ServiceRecord * service;
199 Rearm gotEvent(EventLoop_t * eloop, int fd, int flags) noexcept;
201 ServiceIoWatcher(ServiceRecord * sr) noexcept : service(sr) { }
203 void registerWith(EventLoop_t *loop, int fd, int flags)
206 EventLoop_t::FdWatcher::registerWith(loop, fd, flags);
212 friend class ServiceChildWatcher;
213 friend class ServiceIoWatcher;
215 typedef std::string string;
218 ServiceType service_type; /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
219 ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
220 ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
222 string program_name; /* storage for program/script and arguments */
223 std::vector<const char *> exec_arg_parts; /* pointer to each argument/part of the program_name */
225 string stop_command; /* storage for stop program/script and arguments */
226 std::vector<const char *> stop_arg_parts; /* pointer to each argument/part of the stop_command */
230 OnstartFlags onstart_flags;
232 string logfile; // log file name, empty string specifies /dev/null
234 bool auto_restart : 1; // whether to restart this (process) if it dies unexpectedly
235 bool smooth_recovery : 1; // whether the service process can restart without bringing down service
237 bool pinned_stopped : 1;
238 bool pinned_started : 1;
239 bool waiting_for_deps : 1; // if STARTING, whether we are waiting for dependencies (inc console) to start
240 bool waiting_for_execstat : 1; // if we are waiting for exec status after fork()
241 bool doing_recovery : 1; // if we are currently recovering a BGPROCESS (restarting process, while
242 // holding STARTED service state)
243 bool start_explicit : 1; // whether we are are explictly required to be started
244 int required_by = 0; // number of dependents wanting this service to be started
246 typedef std::list<ServiceRecord *> sr_list;
247 typedef sr_list::iterator sr_iter;
249 // list of soft dependencies
250 typedef std::list<ServiceDep> softdep_list;
252 // list of soft dependents
253 typedef std::list<ServiceDep *> softdpt_list;
255 sr_list depends_on; // services this one depends on
256 sr_list dependents; // services depending on this one
257 softdep_list soft_deps; // services this one depends on via a soft dependency
258 softdpt_list soft_dpts; // services depending on this one via a soft dependency
260 // unsigned wait_count; /* if we are waiting for dependents/dependencies to
261 // start/stop, this is how many we're waiting for */
263 ServiceSet *service_set; // the set this service belongs to
265 std::unordered_set<ServiceListener *> listeners;
268 bool force_stop; // true if the service must actually stop. This is the
269 // case if for example the process dies; the service,
270 // and all its dependencies, MUST be stopped.
272 int term_signal = -1; // signal to use for process termination
274 string socket_path; // path to the socket for socket-activation service
275 int socket_perms; // socket permissions ("mode")
276 uid_t socket_uid = -1; // socket user id or -1
277 gid_t socket_gid = -1; // sockget group id or -1
279 // Implementation details
281 pid_t pid = -1; // PID of the process. If state is STARTING or STOPPING,
282 // this is PID of the service script; otherwise it is the
283 // PID of the process itself (process service).
284 int exit_status; // Exit status, if the process has exited (pid == -1).
285 int socket_fd = -1; // For socket-activation services, this is the file
286 // descriptor for the socket.
288 ServiceChildWatcher child_listener;
289 ServiceIoWatcher child_status_listener;
291 // Data for use by ServiceSet
294 // Next service (after this one) in the queue for the console. Intended to only be used by ServiceSet class.
295 ServiceRecord *next_for_console;
298 ServiceRecord *next_in_start_queue = nullptr;
299 ServiceRecord *next_in_stop_queue = nullptr;
304 // All dependents have stopped.
305 void allDepsStopped();
307 // Service has actually stopped (includes having all dependents
308 // reaching STOPPED state).
309 void stopped() noexcept;
311 // Service has successfully started
312 void started() noexcept;
314 // Service failed to start (only called when in STARTING state).
315 // dep_failed: whether failure is recorded due to a dependency failing
316 void failed_to_start(bool dep_failed = false) noexcept;
318 // For process services, start the process, return true on success
319 bool start_ps_process() noexcept;
320 bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
322 // Callback from libev when a child process dies
323 static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
324 int revents) noexcept;
326 static void process_child_status(EventLoop_t *loop, ServiceIoWatcher * stat_io,
327 int revents) noexcept;
329 void handle_exit_status() noexcept;
331 // A dependency has reached STARTED state
332 void dependencyStarted() noexcept;
334 void allDepsStarted(bool haveConsole = false) noexcept;
336 // Read the pid-file, return false on failure
337 bool read_pid_file() noexcept;
339 // Open the activation socket, return false on failure
340 bool open_socket() noexcept;
342 // Check whether dependencies have started, and optionally ask them to start
343 bool startCheckDependencies(bool do_start) noexcept;
345 // Whether a STARTING service can immediately transition to STOPPED (as opposed to
346 // having to wait for it reach STARTED and then go through STOPPING).
347 bool can_interrupt_start() noexcept
349 return waiting_for_deps;
352 // Whether a STOPPING service can immediately transition to STARTED.
353 bool can_interrupt_stop() noexcept
355 return waiting_for_deps && ! force_stop;
358 // Notify dependencies that we no longer need them,
359 // (if this is actually the case).
360 void notify_dependencies_stopped() noexcept;
362 // A dependent has reached STOPPED state
363 void dependentStopped() noexcept;
365 // check if all dependents have stopped
366 bool stopCheckDependents() noexcept;
368 // issue a stop to all dependents, return true if they are all already stopped
369 bool stopDependents() noexcept;
371 void require() noexcept;
372 void release() noexcept;
373 void release_dependencies() noexcept;
375 // Check if service is, fundamentally, stopped.
376 bool is_stopped() noexcept
378 return service_state == ServiceState::STOPPED
379 || (service_state == ServiceState::STARTING && waiting_for_deps);
382 void notifyListeners(ServiceEvent event) noexcept
384 for (auto l : listeners) {
385 l->serviceEvent(this, event);
389 // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
390 void queueForConsole() noexcept;
392 // Release console (console must be currently held by this service)
393 void releaseConsole() noexcept;
395 bool do_auto_restart() noexcept;
399 ServiceRecord(ServiceSet *set, string name)
400 : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
401 pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
402 waiting_for_execstat(false), doing_recovery(false),
403 start_explicit(false), force_stop(false), child_listener(this), child_status_listener(this)
407 service_type = ServiceType::DUMMY;
410 ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
411 sr_list * pdepends_on, sr_list * pdepends_soft)
412 : ServiceRecord(set, name)
416 this->service_type = service_type;
417 this->depends_on = std::move(*pdepends_on);
419 program_name = command;
420 exec_arg_parts = separate_args(program_name, command_offsets);
422 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
423 (*i)->dependents.push_back(this);
427 auto b_iter = soft_deps.end();
428 for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
429 b_iter = soft_deps.emplace(b_iter, this, *i);
430 (*i)->soft_dpts.push_back(&(*b_iter));
435 // TODO write a destructor
437 // Called on transition of desired state from stopped to started (or unpinned stop)
438 void do_start() noexcept;
440 // Called on transition of desired state from started to stopped (or unpinned start)
441 void do_stop() noexcept;
443 // Console is available.
444 void acquiredConsole() noexcept;
446 // Set the stop command and arguments (may throw std::bad_alloc)
447 void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
449 stop_command = command;
450 stop_arg_parts = separate_args(stop_command, stop_command_offsets);
453 // Get the current service state.
454 ServiceState getState() noexcept
456 return service_state;
459 // Get the target (aka desired) state.
460 ServiceState getTargetState() noexcept
462 return desired_state;
465 // Set logfile, should be done before service is started
466 void setLogfile(string logfile)
468 this->logfile = logfile;
471 // Set whether this service should automatically restart when it dies
472 void setAutoRestart(bool auto_restart) noexcept
474 this->auto_restart = auto_restart;
477 void setSmoothRecovery(bool smooth_recovery) noexcept
479 this->smooth_recovery = smooth_recovery;
482 // Set "on start" flags (commands)
483 void setOnstartFlags(OnstartFlags flags) noexcept
485 this->onstart_flags = flags;
488 // Set an additional signal (other than SIGTERM) to be used to terminate the process
489 void setExtraTerminationSignal(int signo) noexcept
491 this->term_signal = signo;
494 void set_pid_file(string &&pid_file) noexcept
496 this->pid_file = pid_file;
499 void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
501 this->socket_path = socket_path;
502 this->socket_perms = socket_perms;
503 this->socket_uid = socket_uid;
504 this->socket_gid = socket_gid;
507 const char *getServiceName() const noexcept { return service_name.c_str(); }
508 ServiceState getState() const noexcept { return service_state; }
510 void start(bool activate = true) noexcept; // start the service
511 void stop(bool bring_down = true) noexcept; // stop the service
513 void forceStop() noexcept; // force-stop this service and all dependents
515 // Pin the service in "started" state (when it reaches the state)
516 void pinStart() noexcept
518 pinned_started = true;
521 // Pin the service in "stopped" state (when it reaches the state)
522 void pinStop() noexcept
524 pinned_stopped = true;
527 // Remove both "started" and "stopped" pins. If the service is currently pinned
528 // in either state but would naturally be in the opposite state, it will immediately
529 // commence starting/stopping.
530 void unpin() noexcept;
532 bool isDummy() noexcept
534 return service_type == ServiceType::DUMMY;
537 // Add a listener. A listener must only be added once. May throw std::bad_alloc.
538 void addListener(ServiceListener * listener)
540 listeners.insert(listener);
543 // Remove a listener.
544 void removeListener(ServiceListener * listener) noexcept
546 listeners.erase(listener);
551 * A ServiceSet, as the name suggests, manages a set of services.
553 * Other than the ability to find services by name, the service set manages various queues.
554 * One is the queue for processes wishing to acquire the console. There is also a set of
555 * processes that want to start, and another set of those that want to stop. These latter
556 * two "queues" (not really queues since their order is not important) are used to prevent too
557 * much recursion and to prevent service states from "bouncing" too rapidly.
559 * A service that wishes to stop puts itself on the stop queue; a service that wishes to start
560 * puts itself on the start queue. Any operation that potentially manipulates the queues must
561 * be folloed by a "process queues" order (processQueues method, which can be instructed to
562 * process either the start queue or the stop queue first).
564 * Note that which queue it does process first, processQueues always repeatedly processes both
565 * queues until they are empty. The process is finite because starting a service can never
566 * cause services to be added to the stop queue, unless they fail to start, which should cause
567 * them to stop semi-permanently.
572 std::list<ServiceRecord *> records;
573 const char *service_dir; // directory containing service descriptions
574 bool restart_enabled; // whether automatic restart is enabled (allowed)
576 ShutdownType shutdown_type = ShutdownType::CONTINUE; // Shutdown type, if stopping
578 ServiceRecord * console_queue_head = nullptr; // first record in console queue
579 ServiceRecord * console_queue_tail = nullptr; // last record in console queue
581 // start/stop "queue" - list of services waiting to stop/start
582 ServiceRecord * first_start_queue = nullptr;
583 ServiceRecord * first_stop_queue = nullptr;
587 // Load a service description, and dependencies, if there is no existing
588 // record for the given name.
590 // ServiceLoadException (or subclass) on problem with service description
591 // std::bad_alloc on out-of-memory condition
592 ServiceRecord *loadServiceRecord(const char *name);
597 ServiceSet(const char *service_dir)
599 this->service_dir = service_dir;
601 restart_enabled = true;
604 // Start the service with the given name. The named service will begin
605 // transition to the 'started' state.
607 // Throws a ServiceLoadException (or subclass) if the service description
608 // cannot be loaded or is invalid;
609 // Throws std::bad_alloc if out of memory.
610 void startService(const char *name);
612 // Locate an existing service record.
613 ServiceRecord *findService(const std::string &name) noexcept;
615 // Find a loaded service record, or load it if it is not loaded.
617 // ServiceLoadException (or subclass) on problem with service description
618 // std::bad_alloc on out-of-memory condition
619 ServiceRecord *loadService(const std::string &name)
621 ServiceRecord *record = findService(name);
622 if (record == nullptr) {
623 record = loadServiceRecord(name.c_str());
628 // Stop the service with the given name. The named service will begin
629 // transition to the 'stopped' state.
630 void stopService(const std::string &name) noexcept;
632 // Add a service record to the start queue
633 void addToStartQueue(ServiceRecord *service) noexcept
635 if (service->next_in_start_queue == nullptr && first_start_queue != service) {
636 service->next_in_start_queue = first_start_queue;
637 first_start_queue = service;
641 // Add a service to the stop queue
642 void addToStopQueue(ServiceRecord *service) noexcept
644 if (service->next_in_stop_queue == nullptr && first_stop_queue != service) {
645 service->next_in_stop_queue = first_stop_queue;
646 first_stop_queue = service;
650 void processQueues(bool do_start_first) noexcept
652 if (! do_start_first) {
653 while (first_stop_queue != nullptr) {
654 auto next = first_stop_queue;
655 first_stop_queue = next->next_in_stop_queue;
656 next->next_in_stop_queue = nullptr;
661 while (first_stop_queue != nullptr || first_start_queue != nullptr) {
662 while (first_start_queue != nullptr) {
663 auto next = first_start_queue;
664 first_start_queue = next->next_in_start_queue;
665 next->next_in_start_queue = nullptr;
668 while (first_stop_queue != nullptr) {
669 auto next = first_stop_queue;
670 first_stop_queue = next->next_in_stop_queue;
671 next->next_in_stop_queue = nullptr;
677 // Set the console queue tail (returns previous tail)
678 ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
680 auto prev_tail = console_queue_tail;
681 console_queue_tail = newTail;
683 console_queue_head = newTail;
684 enable_console_log(false);
687 prev_tail->next_for_console = newTail;
692 // Retrieve the current console queue head and remove it from the queue
693 ServiceRecord * pullConsoleQueue() noexcept
695 auto prev_head = console_queue_head;
697 prev_head->acquiredConsole();
698 console_queue_head = prev_head->next_for_console;
699 if (! console_queue_head) {
700 console_queue_tail = nullptr;
704 enable_console_log(true);
709 // Notification from service that it is active (state != STOPPED)
710 // Only to be called on the transition from inactive to active.
711 void service_active(ServiceRecord *) noexcept;
713 // Notification from service that it is inactive (STOPPED)
714 // Only to be called on the transition from active to inactive.
715 void service_inactive(ServiceRecord *) noexcept;
717 // Find out how many services are active (starting, running or stopping,
719 int count_active_services() noexcept
721 return active_services;
724 void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
726 restart_enabled = false;
727 shutdown_type = type;
728 for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
732 processQueues(false);
735 void set_auto_restart(bool restart) noexcept
737 restart_enabled = restart;
740 bool get_auto_restart() noexcept
742 return restart_enabled;
745 ShutdownType getShutdownType() noexcept
747 return shutdown_type;