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.
77 // Not actually "onstart" commands:
78 bool no_sigterm : 1; // do not send SIGTERM
79 bool runs_on_console : 1; // run "in the foreground"
81 OnstartFlags() noexcept : rw_ready(false), log_ready(false),
82 no_sigterm(false), runs_on_console(false)
87 // Exception while loading a service
91 std::string serviceName;
92 const char *excDescription;
95 ServiceLoadExc(std::string serviceName) noexcept
96 : serviceName(serviceName)
101 class ServiceNotFound : public ServiceLoadExc
104 ServiceNotFound(std::string serviceName) noexcept
105 : ServiceLoadExc(serviceName)
107 excDescription = "Service description not found.";
111 class ServiceCyclicDependency : public ServiceLoadExc
114 ServiceCyclicDependency(std::string serviceName) noexcept
115 : ServiceLoadExc(serviceName)
117 excDescription = "Has cyclic dependency.";
121 class ServiceDescriptionExc : public ServiceLoadExc
124 std::string extraInfo;
126 ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
127 : ServiceLoadExc(serviceName), extraInfo(extraInfo)
129 excDescription = extraInfo.c_str();
133 class ServiceRecord; // forward declaration
134 class ServiceSet; // forward declaration
136 /* Service dependency record */
139 ServiceRecord * from;
143 /* Whether the 'from' service is waiting for the 'to' service to start */
146 ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false)
149 ServiceRecord * getFrom() noexcept
154 ServiceRecord * getTo() noexcept
160 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
161 // store a null terminator for the argument. Return a `char *` vector containing the beginning
162 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
163 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
165 std::vector<const char *> r;
166 r.reserve(arg_indices.size() + 1);
168 // First store nul terminator for each part:
169 for (auto index_pair : arg_indices) {
170 if (index_pair.second < s.length()) {
171 s[index_pair.second] = 0;
175 // Now we can get the C string (c_str) and store offsets into it:
176 const char * cstr = s.c_str();
177 for (auto index_pair : arg_indices) {
178 r.push_back(cstr + index_pair.first);
180 r.push_back(nullptr);
184 class ServiceChildWatcher : public EventLoop_t::ChildProcWatcher
187 // TODO resolve clunkiness of storing this field
188 ServiceRecord * service;
189 Rearm childStatus(EventLoop_t &eloop, pid_t child, int status) noexcept;
191 ServiceChildWatcher(ServiceRecord * sr) noexcept : service(sr) { }
194 class ServiceIoWatcher : public EventLoop_t::FdWatcher
197 // TODO resolve clunkiness of storing these fields
199 ServiceRecord * service;
200 Rearm fdEvent(EventLoop_t &eloop, int fd, int flags) noexcept;
202 ServiceIoWatcher(ServiceRecord * sr) noexcept : service(sr) { }
204 void addWatch(EventLoop_t &loop, int fd, int flags)
207 EventLoop_t::FdWatcher::addWatch(loop, fd, flags);
213 friend class ServiceChildWatcher;
214 friend class ServiceIoWatcher;
216 typedef std::string string;
219 ServiceType service_type; /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
220 ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
221 ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
223 string program_name; /* storage for program/script and arguments */
224 std::vector<const char *> exec_arg_parts; /* pointer to each argument/part of the program_name */
226 string stop_command; /* storage for stop program/script and arguments */
227 std::vector<const char *> stop_arg_parts; /* pointer to each argument/part of the stop_command */
231 OnstartFlags onstart_flags;
233 string logfile; // log file name, empty string specifies /dev/null
235 bool auto_restart : 1; // whether to restart this (process) if it dies unexpectedly
236 bool smooth_recovery : 1; // whether the service process can restart without bringing down service
238 bool pinned_stopped : 1;
239 bool pinned_started : 1;
240 bool waiting_for_deps : 1; // if STARTING, whether we are waiting for dependencies (inc console) to start
241 bool waiting_for_execstat : 1; // if we are waiting for exec status after fork()
242 bool doing_recovery : 1; // if we are currently recovering a BGPROCESS (restarting process, while
243 // holding STARTED service state)
244 bool start_explicit : 1; // whether we are are explictly required to be started
245 int required_by = 0; // number of dependents wanting this service to be started
247 typedef std::list<ServiceRecord *> sr_list;
248 typedef sr_list::iterator sr_iter;
250 // list of soft dependencies
251 typedef std::list<ServiceDep> softdep_list;
253 // list of soft dependents
254 typedef std::list<ServiceDep *> softdpt_list;
256 sr_list depends_on; // services this one depends on
257 sr_list dependents; // services depending on this one
258 softdep_list soft_deps; // services this one depends on via a soft dependency
259 softdpt_list soft_dpts; // services depending on this one via a soft dependency
261 // unsigned wait_count; /* if we are waiting for dependents/dependencies to
262 // start/stop, this is how many we're waiting for */
264 ServiceSet *service_set; // the set this service belongs to
266 std::unordered_set<ServiceListener *> listeners;
269 bool force_stop; // true if the service must actually stop. This is the
270 // case if for example the process dies; the service,
271 // and all its dependencies, MUST be stopped.
273 int term_signal = -1; // signal to use for process termination
275 string socket_path; // path to the socket for socket-activation service
276 int socket_perms; // socket permissions ("mode")
277 uid_t socket_uid = -1; // socket user id or -1
278 gid_t socket_gid = -1; // sockget group id or -1
280 // Implementation details
282 pid_t pid = -1; // PID of the process. If state is STARTING or STOPPING,
283 // this is PID of the service script; otherwise it is the
284 // PID of the process itself (process service).
285 int exit_status; // Exit status, if the process has exited (pid == -1).
286 int socket_fd = -1; // For socket-activation services, this is the file
287 // descriptor for the socket.
289 ServiceChildWatcher child_listener;
290 ServiceIoWatcher child_status_listener;
292 // Data for use by ServiceSet
295 // Next service (after this one) in the queue for the console. Intended to only be used by ServiceSet class.
296 ServiceRecord *next_for_console;
299 ServiceRecord *next_in_start_queue = nullptr;
300 ServiceRecord *next_in_stop_queue = nullptr;
305 // All dependents have stopped.
306 void allDepsStopped();
308 // Service has actually stopped (includes having all dependents
309 // reaching STOPPED state).
310 void stopped() noexcept;
312 // Service has successfully started
313 void started() noexcept;
315 // Service failed to start (only called when in STARTING state).
316 // dep_failed: whether failure is recorded due to a dependency failing
317 void failed_to_start(bool dep_failed = false) noexcept;
319 // For process services, start the process, return true on success
320 bool start_ps_process() noexcept;
321 bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
323 // Callback from libev when a child process dies
324 static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
325 int revents) noexcept;
327 static void process_child_status(EventLoop_t *loop, ServiceIoWatcher * stat_io,
328 int revents) noexcept;
330 void handle_exit_status() noexcept;
332 // A dependency has reached STARTED state
333 void dependencyStarted() noexcept;
335 void allDepsStarted(bool haveConsole = false) noexcept;
337 // Read the pid-file, return false on failure
338 bool read_pid_file() noexcept;
340 // Open the activation socket, return false on failure
341 bool open_socket() noexcept;
343 // Check whether dependencies have started, and optionally ask them to start
344 bool startCheckDependencies(bool do_start) noexcept;
346 // Whether a STARTING service can immediately transition to STOPPED (as opposed to
347 // having to wait for it reach STARTED and then go through STOPPING).
348 bool can_interrupt_start() noexcept
350 return waiting_for_deps;
353 // Whether a STOPPING service can immediately transition to STARTED.
354 bool can_interrupt_stop() noexcept
356 return waiting_for_deps && ! force_stop;
359 // Notify dependencies that we no longer need them,
360 // (if this is actually the case).
361 void notify_dependencies_stopped() noexcept;
363 // A dependent has reached STOPPED state
364 void dependentStopped() noexcept;
366 // check if all dependents have stopped
367 bool stopCheckDependents() noexcept;
369 // issue a stop to all dependents, return true if they are all already stopped
370 bool stopDependents() noexcept;
372 void require() noexcept;
373 void release() noexcept;
374 void release_dependencies() noexcept;
376 // Check if service is, fundamentally, stopped.
377 bool is_stopped() noexcept
379 return service_state == ServiceState::STOPPED
380 || (service_state == ServiceState::STARTING && waiting_for_deps);
383 void notifyListeners(ServiceEvent event) noexcept
385 for (auto l : listeners) {
386 l->serviceEvent(this, event);
390 // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
391 void queueForConsole() noexcept;
393 // Release console (console must be currently held by this service)
394 void releaseConsole() noexcept;
396 bool do_auto_restart() noexcept;
400 ServiceRecord(ServiceSet *set, string name)
401 : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
402 pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
403 waiting_for_execstat(false), doing_recovery(false),
404 start_explicit(false), force_stop(false), child_listener(this), child_status_listener(this)
408 service_type = ServiceType::DUMMY;
411 ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
412 sr_list * pdepends_on, sr_list * pdepends_soft)
413 : ServiceRecord(set, name)
417 this->service_type = service_type;
418 this->depends_on = std::move(*pdepends_on);
420 program_name = command;
421 exec_arg_parts = separate_args(program_name, command_offsets);
423 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
424 (*i)->dependents.push_back(this);
428 auto b_iter = soft_deps.end();
429 for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
430 b_iter = soft_deps.emplace(b_iter, this, *i);
431 (*i)->soft_dpts.push_back(&(*b_iter));
436 // TODO write a destructor
438 // Called on transition of desired state from stopped to started (or unpinned stop)
439 void do_start() noexcept;
441 // Called on transition of desired state from started to stopped (or unpinned start)
442 void do_stop() noexcept;
444 // Console is available.
445 void acquiredConsole() noexcept;
447 // Set the stop command and arguments (may throw std::bad_alloc)
448 void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
450 stop_command = command;
451 stop_arg_parts = separate_args(stop_command, stop_command_offsets);
454 // Get the current service state.
455 ServiceState getState() noexcept
457 return service_state;
460 // Get the target (aka desired) state.
461 ServiceState getTargetState() noexcept
463 return desired_state;
466 // Set logfile, should be done before service is started
467 void setLogfile(string logfile)
469 this->logfile = logfile;
472 // Set whether this service should automatically restart when it dies
473 void setAutoRestart(bool auto_restart) noexcept
475 this->auto_restart = auto_restart;
478 void setSmoothRecovery(bool smooth_recovery) noexcept
480 this->smooth_recovery = smooth_recovery;
483 // Set "on start" flags (commands)
484 void setOnstartFlags(OnstartFlags flags) noexcept
486 this->onstart_flags = flags;
489 // Set an additional signal (other than SIGTERM) to be used to terminate the process
490 void setExtraTerminationSignal(int signo) noexcept
492 this->term_signal = signo;
495 void set_pid_file(string &&pid_file) noexcept
497 this->pid_file = pid_file;
500 void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
502 this->socket_path = socket_path;
503 this->socket_perms = socket_perms;
504 this->socket_uid = socket_uid;
505 this->socket_gid = socket_gid;
508 const char *getServiceName() const noexcept { return service_name.c_str(); }
509 ServiceState getState() const noexcept { return service_state; }
511 void start(bool activate = true) noexcept; // start the service
512 void stop(bool bring_down = true) noexcept; // stop the service
514 void forceStop() noexcept; // force-stop this service and all dependents
516 // Pin the service in "started" state (when it reaches the state)
517 void pinStart() noexcept
519 pinned_started = true;
522 // Pin the service in "stopped" state (when it reaches the state)
523 void pinStop() noexcept
525 pinned_stopped = true;
528 // Remove both "started" and "stopped" pins. If the service is currently pinned
529 // in either state but would naturally be in the opposite state, it will immediately
530 // commence starting/stopping.
531 void unpin() noexcept;
533 bool isDummy() noexcept
535 return service_type == ServiceType::DUMMY;
538 // Add a listener. A listener must only be added once. May throw std::bad_alloc.
539 void addListener(ServiceListener * listener)
541 listeners.insert(listener);
544 // Remove a listener.
545 void removeListener(ServiceListener * listener) noexcept
547 listeners.erase(listener);
552 * A ServiceSet, as the name suggests, manages a set of services.
554 * Other than the ability to find services by name, the service set manages various queues.
555 * One is the queue for processes wishing to acquire the console. There is also a set of
556 * processes that want to start, and another set of those that want to stop. These latter
557 * two "queues" (not really queues since their order is not important) are used to prevent too
558 * much recursion and to prevent service states from "bouncing" too rapidly.
560 * A service that wishes to stop puts itself on the stop queue; a service that wishes to start
561 * puts itself on the start queue. Any operation that potentially manipulates the queues must
562 * be folloed by a "process queues" order (processQueues method, which can be instructed to
563 * process either the start queue or the stop queue first).
565 * Note that which queue it does process first, processQueues always repeatedly processes both
566 * queues until they are empty. The process is finite because starting a service can never
567 * cause services to be added to the stop queue, unless they fail to start, which should cause
568 * them to stop semi-permanently.
573 std::list<ServiceRecord *> records;
574 const char *service_dir; // directory containing service descriptions
575 bool restart_enabled; // whether automatic restart is enabled (allowed)
577 ShutdownType shutdown_type = ShutdownType::CONTINUE; // Shutdown type, if stopping
579 ServiceRecord * console_queue_head = nullptr; // first record in console queue
580 ServiceRecord * console_queue_tail = nullptr; // last record in console queue
582 // start/stop "queue" - list of services waiting to stop/start
583 ServiceRecord * first_start_queue = nullptr;
584 ServiceRecord * first_stop_queue = nullptr;
588 // Load a service description, and dependencies, if there is no existing
589 // record for the given name.
591 // ServiceLoadException (or subclass) on problem with service description
592 // std::bad_alloc on out-of-memory condition
593 ServiceRecord *loadServiceRecord(const char *name);
598 ServiceSet(const char *service_dir)
600 this->service_dir = service_dir;
602 restart_enabled = true;
605 // Start the service with the given name. The named service will begin
606 // transition to the 'started' state.
608 // Throws a ServiceLoadException (or subclass) if the service description
609 // cannot be loaded or is invalid;
610 // Throws std::bad_alloc if out of memory.
611 void startService(const char *name);
613 // Locate an existing service record.
614 ServiceRecord *findService(const std::string &name) noexcept;
616 // Find a loaded service record, or load it if it is not loaded.
618 // ServiceLoadException (or subclass) on problem with service description
619 // std::bad_alloc on out-of-memory condition
620 ServiceRecord *loadService(const std::string &name)
622 ServiceRecord *record = findService(name);
623 if (record == nullptr) {
624 record = loadServiceRecord(name.c_str());
629 // Stop the service with the given name. The named service will begin
630 // transition to the 'stopped' state.
631 void stopService(const std::string &name) noexcept;
633 // Add a service record to the start queue
634 void addToStartQueue(ServiceRecord *service) noexcept
636 if (service->next_in_start_queue == nullptr && first_start_queue != service) {
637 service->next_in_start_queue = first_start_queue;
638 first_start_queue = service;
642 // Add a service to the stop queue
643 void addToStopQueue(ServiceRecord *service) noexcept
645 if (service->next_in_stop_queue == nullptr && first_stop_queue != service) {
646 service->next_in_stop_queue = first_stop_queue;
647 first_stop_queue = service;
651 void processQueues(bool do_start_first) noexcept
653 if (! do_start_first) {
654 while (first_stop_queue != nullptr) {
655 auto next = first_stop_queue;
656 first_stop_queue = next->next_in_stop_queue;
657 next->next_in_stop_queue = nullptr;
662 while (first_stop_queue != nullptr || first_start_queue != nullptr) {
663 while (first_start_queue != nullptr) {
664 auto next = first_start_queue;
665 first_start_queue = next->next_in_start_queue;
666 next->next_in_start_queue = nullptr;
669 while (first_stop_queue != nullptr) {
670 auto next = first_stop_queue;
671 first_stop_queue = next->next_in_stop_queue;
672 next->next_in_stop_queue = nullptr;
678 // Set the console queue tail (returns previous tail)
679 ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
681 auto prev_tail = console_queue_tail;
682 console_queue_tail = newTail;
683 newTail->next_for_console = nullptr;
685 console_queue_head = newTail;
686 enable_console_log(false);
689 prev_tail->next_for_console = newTail;
694 // Retrieve the current console queue head and remove it from the queue
695 ServiceRecord * pullConsoleQueue() noexcept
697 auto prev_head = console_queue_head;
699 prev_head->acquiredConsole();
700 console_queue_head = prev_head->next_for_console;
701 if (! console_queue_head) {
702 console_queue_tail = nullptr;
706 enable_console_log(true);
711 // Notification from service that it is active (state != STOPPED)
712 // Only to be called on the transition from inactive to active.
713 void service_active(ServiceRecord *) noexcept;
715 // Notification from service that it is inactive (STOPPED)
716 // Only to be called on the transition from active to inactive.
717 void service_inactive(ServiceRecord *) noexcept;
719 // Find out how many services are active (starting, running or stopping,
721 int count_active_services() noexcept
723 return active_services;
726 void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
728 restart_enabled = false;
729 shutdown_type = type;
730 for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
734 processQueues(false);
737 void set_auto_restart(bool restart) noexcept
739 restart_enabled = restart;
742 bool get_auto_restart() noexcept
744 return restart_enabled;
747 ShutdownType getShutdownType() noexcept
749 return shutdown_type;