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 PosixChildWatcher<NullMutex>
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 PosixFdWatcher<NullMutex>
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 PosixFdWatcher<NullMutex>::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 // All dependents have stopped.
292 void allDepsStopped();
294 // Service has actually stopped (includes having all dependents
295 // reaching STOPPED state).
296 void stopped() noexcept;
298 // Service has successfully started
299 void started() noexcept;
301 // Service failed to start (only called when in STARTING state).
302 // dep_failed: whether failure is recorded due to a dependency failing
303 void failed_to_start(bool dep_failed = false) noexcept;
305 // For process services, start the process, return true on success
306 bool start_ps_process() noexcept;
307 bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
309 // Callback from libev when a child process dies
310 static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
311 int revents) noexcept;
313 static void process_child_status(EventLoop_t *loop, ServiceIoWatcher * stat_io,
314 int revents) noexcept;
316 void handle_exit_status() noexcept;
318 // Called on transition of desired state from stopped to started (or unpinned stop)
319 void do_start() noexcept;
321 // Called on transition of desired state from started to stopped (or unpinned start)
322 void do_stop() noexcept;
324 // A dependency has reached STARTED state
325 void dependencyStarted() noexcept;
327 void allDepsStarted(bool haveConsole = false) noexcept;
329 // Read the pid-file, return false on failure
330 bool read_pid_file() noexcept;
332 // Open the activation socket, return false on failure
333 bool open_socket() noexcept;
335 // Check whether dependencies have started, and optionally ask them to start
336 bool startCheckDependencies(bool do_start) noexcept;
338 // Whether a STARTING service can immediately transition to STOPPED (as opposed to
339 // having to wait for it reach STARTED and then go through STOPPING).
340 bool can_interrupt_start() noexcept
342 return waiting_for_deps;
345 // Whether a STOPPING service can immediately transition to STARTED.
346 bool can_interrupt_stop() noexcept
348 return waiting_for_deps && ! force_stop;
351 // Notify dependencies that we no longer need them,
352 // (if this is actually the case).
353 void notify_dependencies_stopped() noexcept;
355 // A dependent has reached STOPPED state
356 void dependentStopped() noexcept;
358 // check if all dependents have stopped
359 bool stopCheckDependents() noexcept;
361 // issue a stop to all dependents, return true if they are all already stopped
362 bool stopDependents() noexcept;
364 void require() noexcept;
365 void release() noexcept;
366 void release_dependencies() noexcept;
368 // Check if service is, fundamentally, stopped.
369 bool is_stopped() noexcept
371 return service_state == ServiceState::STOPPED
372 || (service_state == ServiceState::STARTING && waiting_for_deps);
375 void notifyListeners(ServiceEvent event) noexcept
377 for (auto l : listeners) {
378 l->serviceEvent(this, event);
382 // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
383 void queueForConsole() noexcept;
385 // Release console (console must be currently held by this service)
386 void releaseConsole() noexcept;
388 bool do_auto_restart() noexcept;
392 ServiceRecord(ServiceSet *set, string name)
393 : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
394 pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
395 waiting_for_execstat(false), doing_recovery(false),
396 start_explicit(false), force_stop(false), child_listener(this), child_status_listener(this)
400 service_type = ServiceType::DUMMY;
403 ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
404 sr_list * pdepends_on, sr_list * pdepends_soft)
405 : ServiceRecord(set, name)
409 this->service_type = service_type;
410 this->depends_on = std::move(*pdepends_on);
412 program_name = command;
413 exec_arg_parts = separate_args(program_name, command_offsets);
415 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
416 (*i)->dependents.push_back(this);
420 auto b_iter = soft_deps.end();
421 for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
422 b_iter = soft_deps.emplace(b_iter, this, *i);
423 (*i)->soft_dpts.push_back(&(*b_iter));
428 // TODO write a destructor
430 // Next service (after this one) in the queue for the console. Intended to only be used by ServiceSet class.
431 ServiceRecord *next_for_console;
433 // Console is available.
434 void acquiredConsole() noexcept;
436 // Set the stop command and arguments (may throw std::bad_alloc)
437 void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
439 stop_command = command;
440 stop_arg_parts = separate_args(stop_command, stop_command_offsets);
443 // Get the current service state.
444 ServiceState getState() noexcept
446 return service_state;
449 // Get the target (aka desired) state.
450 ServiceState getTargetState() noexcept
452 return desired_state;
455 // Set logfile, should be done before service is started
456 void setLogfile(string logfile)
458 this->logfile = logfile;
461 // Set whether this service should automatically restart when it dies
462 void setAutoRestart(bool auto_restart) noexcept
464 this->auto_restart = auto_restart;
467 void setSmoothRecovery(bool smooth_recovery) noexcept
469 this->smooth_recovery = smooth_recovery;
472 // Set "on start" flags (commands)
473 void setOnstartFlags(OnstartFlags flags) noexcept
475 this->onstart_flags = flags;
478 // Set an additional signal (other than SIGTERM) to be used to terminate the process
479 void setExtraTerminationSignal(int signo) noexcept
481 this->term_signal = signo;
484 void set_pid_file(string &&pid_file) noexcept
486 this->pid_file = pid_file;
489 void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
491 this->socket_path = socket_path;
492 this->socket_perms = socket_perms;
493 this->socket_uid = socket_uid;
494 this->socket_gid = socket_gid;
497 const char *getServiceName() const noexcept { return service_name.c_str(); }
498 ServiceState getState() const noexcept { return service_state; }
500 void start(bool activate = true) noexcept; // start the service
501 void stop(bool bring_down = true) noexcept; // stop the service
503 void forceStop() noexcept; // force-stop this service and all dependents
505 // Pin the service in "started" state (when it reaches the state)
506 void pinStart() noexcept
508 pinned_started = true;
511 // Pin the service in "stopped" state (when it reaches the state)
512 void pinStop() noexcept
514 pinned_stopped = true;
517 // Remove both "started" and "stopped" pins. If the service is currently pinned
518 // in either state but would naturally be in the opposite state, it will immediately
519 // commence starting/stopping.
520 void unpin() noexcept;
522 bool isDummy() noexcept
524 return service_type == ServiceType::DUMMY;
527 // Add a listener. A listener must only be added once. May throw std::bad_alloc.
528 void addListener(ServiceListener * listener)
530 listeners.insert(listener);
533 // Remove a listener.
534 void removeListener(ServiceListener * listener) noexcept
536 listeners.erase(listener);
544 std::list<ServiceRecord *> records;
545 const char *service_dir; // directory containing service descriptions
546 bool restart_enabled; // whether automatic restart is enabled (allowed)
548 ShutdownType shutdown_type = ShutdownType::CONTINUE; // Shutdown type, if stopping
550 ServiceRecord * console_queue_head = nullptr; // first record in console queue
551 ServiceRecord * console_queue_tail = nullptr; // last record in console queue
555 // Load a service description, and dependencies, if there is no existing
556 // record for the given name.
558 // ServiceLoadException (or subclass) on problem with service description
559 // std::bad_alloc on out-of-memory condition
560 ServiceRecord *loadServiceRecord(const char *name);
565 ServiceSet(const char *service_dir)
567 this->service_dir = service_dir;
569 restart_enabled = true;
572 // Start the service with the given name. The named service will begin
573 // transition to the 'started' state.
575 // Throws a ServiceLoadException (or subclass) if the service description
576 // cannot be loaded or is invalid;
577 // Throws std::bad_alloc if out of memory.
578 void startService(const char *name);
580 // Locate an existing service record.
581 ServiceRecord *findService(const std::string &name) noexcept;
583 // Find a loaded service record, or load it if it is not loaded.
585 // ServiceLoadException (or subclass) on problem with service description
586 // std::bad_alloc on out-of-memory condition
587 ServiceRecord *loadService(const std::string &name)
589 ServiceRecord *record = findService(name);
590 if (record == nullptr) {
591 record = loadServiceRecord(name.c_str());
596 // Stop the service with the given name. The named service will begin
597 // transition to the 'stopped' state.
598 void stopService(const std::string &name) noexcept;
600 // Set the console queue tail (returns previous tail)
601 ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
603 auto prev_tail = console_queue_tail;
604 console_queue_tail = newTail;
606 console_queue_head = newTail;
607 enable_console_log(false);
610 prev_tail->next_for_console = newTail;
615 // Retrieve the current console queue head and remove it from the queue
616 ServiceRecord * pullConsoleQueue() noexcept
618 auto prev_head = console_queue_head;
620 prev_head->acquiredConsole();
621 console_queue_head = prev_head->next_for_console;
622 if (! console_queue_head) {
623 console_queue_tail = nullptr;
627 enable_console_log(true);
632 // Notification from service that it is active (state != STOPPED)
633 // Only to be called on the transition from inactive to active.
634 void service_active(ServiceRecord *) noexcept;
636 // Notification from service that it is inactive (STOPPED)
637 // Only to be called on the transition from active to inactive.
638 void service_inactive(ServiceRecord *) noexcept;
640 // Find out how many services are active (starting, running or stopping,
642 int count_active_services() noexcept
644 return active_services;
647 void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
649 restart_enabled = false;
650 shutdown_type = type;
651 for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
657 void set_auto_restart(bool restart) noexcept
659 restart_enabled = restart;
662 bool get_auto_restart() noexcept
664 return restart_enabled;
667 ShutdownType getShutdownType() noexcept
669 return shutdown_type;