8 #include <unordered_set>
11 #include "service-listener.h"
12 #include "service-constants.h"
15 * Possible service states
17 * Services have both a current state and a desired state. The desired state can be
18 * either STARTED or STOPPED. The current state can also be STARTING or STOPPING.
19 * A service can be "pinned" in either the STARTED or STOPPED states to prevent it
20 * from leaving that state until it is unpinned.
22 * The total state is a combination of the two, current and desired:
23 * STOPPED/STOPPED : stopped and will remain stopped
24 * STOPPED/STARTED : stopped (pinned), must be unpinned to start
25 * STARTING/STARTED : starting, but not yet started. Dependencies may also be starting.
26 * STARTING/STOPPED : as above, but the service will be stopped again as soon as it has
28 * STARTED/STARTED : running and will continue running.
29 * STARTED/STOPPED : started (pinned), must be unpinned to stop
30 * STOPPING/STOPPED : stopping and will stop. Dependents may be stopping.
31 * STOPPING/STARTED : as above, but the service will be re-started again once it stops.
33 * A scripted service is in the STARTING/STOPPING states during the script execution.
34 * A process service is in the STOPPING state when it has been signalled to stop, and is
35 * in the STARTING state when waiting for dependencies to start.
41 // Not actually "onstart" commands:
42 bool no_sigterm : 1; // do not send SIGTERM
43 bool runs_on_console : 1; // run "in the foreground"
45 OnstartFlags() noexcept : rw_ready(false),
46 no_sigterm(false), runs_on_console(false)
51 // Exception while loading a service
55 std::string serviceName;
56 const char *excDescription;
59 ServiceLoadExc(std::string serviceName) noexcept
60 : serviceName(serviceName)
65 class ServiceNotFound : public ServiceLoadExc
68 ServiceNotFound(std::string serviceName) noexcept
69 : ServiceLoadExc(serviceName)
71 excDescription = "Service description not found.";
75 class ServiceCyclicDependency : public ServiceLoadExc
78 ServiceCyclicDependency(std::string serviceName) noexcept
79 : ServiceLoadExc(serviceName)
81 excDescription = "Has cyclic dependency.";
85 class ServiceDescriptionExc : public ServiceLoadExc
88 std::string extraInfo;
90 ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
91 : ServiceLoadExc(serviceName), extraInfo(extraInfo)
93 excDescription = extraInfo.c_str();
97 class ServiceRecord; // forward declaration
98 class ServiceSet; // forward declaration
100 /* Service dependency record */
103 ServiceRecord * from;
107 /* Whether the 'from' service is waiting for the 'to' service to start */
110 ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false)
113 ServiceRecord * getFrom() noexcept
118 ServiceRecord * getTo() noexcept
124 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
125 // store a null terminator for the argument. Return a `char *` vector containing the beginning
126 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
127 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
129 std::vector<const char *> r;
130 r.reserve(arg_indices.size() + 1);
132 // First store nul terminator for each part:
133 for (auto index_pair : arg_indices) {
134 if (index_pair.second < s.length()) {
135 s[index_pair.second] = 0;
139 // Now we can get the C string (c_str) and store offsets into it:
140 const char * cstr = s.c_str();
141 for (auto index_pair : arg_indices) {
142 r.push_back(cstr + index_pair.first);
144 r.push_back(nullptr);
151 typedef std::string string;
154 ServiceType service_type; /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
155 ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
156 ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
158 string program_name; /* storage for program/script and arguments */
159 std::vector<const char *> exec_arg_parts; /* pointer to each argument/part of the program_name */
161 string stop_command; /* storage for stop program/script and arguments */
162 std::vector<const char *> stop_arg_parts; /* pointer to each argument/part of the stop_command */
164 OnstartFlags onstart_flags;
166 string logfile; // log file name, empty string specifies /dev/null
167 bool auto_restart : 1; // whether to restart this (process) if it dies unexpectedly
168 bool smooth_recovery : 1; // whether the service process can restart without bringing down service
169 bool pinned_stopped : 1;
170 bool pinned_started : 1;
172 bool waiting_for_deps : 1; /* if STARTING, whether we are waiting for dependencies (inc console) to start */
173 bool waiting_for_execstat : 1; /* if we are waiting for exec status after fork() */
175 typedef std::list<ServiceRecord *> sr_list;
176 typedef sr_list::iterator sr_iter;
178 // list of soft dependencies
179 typedef std::list<ServiceDep> softdep_list;
181 // list of soft dependents
182 typedef std::list<ServiceDep *> softdpt_list;
184 sr_list depends_on; // services this one depends on
185 sr_list dependents; // services depending on this one
186 softdep_list soft_deps; // services this one depends on via a soft dependency
187 softdpt_list soft_dpts; // services depending on this one via a soft dependency
189 // unsigned wait_count; /* if we are waiting for dependents/dependencies to
190 // start/stop, this is how many we're waiting for */
192 ServiceSet *service_set; // the set this service belongs to
194 // Next service (after this one) in the queue for the console:
195 ServiceRecord *next_for_console;
198 bool force_stop; // true if the service must actually stop. This is the
199 // case if for example the process dies; the service,
200 // and all its dependencies, MUST be stopped.
202 std::unordered_set<ServiceListener *> listeners;
204 int term_signal = -1; // signal to use for process termination
206 // Implementation details
208 pid_t pid; // PID of the process. If state is STARTING or STOPPING,
209 // this is PID of the service script; otherwise it is the
210 // PID of the process itself (process service).
211 int exit_status; // Exit status, if the process has exited (pid == -1).
213 ev_child child_listener;
214 ev_io child_status_listener;
216 // All dependents have stopped.
217 void allDepsStopped();
219 // Service has actually stopped (includes having all dependents
220 // reaching STOPPED state).
221 void stopped() noexcept;
223 // Service has successfully started
226 // Service failed to start
227 void failed_to_start();
229 // A dependency of this service failed to start.
230 void failed_dependency();
232 // For process services, start the process, return true on success
233 bool start_ps_process() noexcept;
234 bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
236 // Callback from libev when a child process dies
237 static void process_child_callback(struct ev_loop *loop, struct ev_child *w,
238 int revents) noexcept;
240 static void process_child_status(struct ev_loop *loop, ev_io * stat_io,
241 int revents) noexcept;
243 void handle_exit_status() noexcept;
245 // A dependency has reached STARTED state
246 void dependencyStarted() noexcept;
248 void allDepsStarted(bool haveConsole = false) noexcept;
250 // Check whether dependencies have started, and optionally ask them to start
251 bool startCheckDependencies(bool do_start) noexcept;
253 // Whether a STARTING service can immediately transition to STOPPED (as opposed to
254 // having to wait for it reach STARTED and then go through STOPPING).
255 bool can_interrupt_start() noexcept
257 return waiting_for_deps;
260 // Whether a STOPPING service can immediately transition to STARTED.
261 bool can_interrupt_stop() noexcept
263 return waiting_for_deps && ! force_stop;
266 // A dependent has reached STOPPED state
267 void dependentStopped() noexcept;
269 // check if all dependents have stopped
270 bool stopCheckDependents() noexcept;
272 // issue a stop to all dependents, return true if they are all already stopped
273 bool stopDependents() noexcept;
275 void forceStop() noexcept; // force-stop this service and all dependents
277 void notifyListeners(ServiceEvent event) noexcept
279 for (auto l : listeners) {
280 l->serviceEvent(this, event);
284 // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
285 void queueForConsole() noexcept;
287 // Console is available.
288 void acquiredConsole() noexcept;
290 // Release console (console must be currently held by this service)
291 void releaseConsole() noexcept;
295 ServiceRecord(ServiceSet *set, string name)
296 : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
297 pinned_stopped(false), pinned_started(false), force_stop(false)
301 service_type = ServiceType::DUMMY;
304 ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
305 sr_list * pdepends_on, sr_list * pdepends_soft)
306 : ServiceRecord(set, name)
310 this->service_type = service_type;
311 this->depends_on = std::move(*pdepends_on);
313 program_name = command;
314 exec_arg_parts = separate_args(program_name, command_offsets);
316 for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
317 (*i)->dependents.push_back(this);
321 auto b_iter = soft_deps.end();
322 for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
323 b_iter = soft_deps.emplace(b_iter, this, *i);
324 (*i)->soft_dpts.push_back(&(*b_iter));
329 // TODO write a destructor
331 // Set the stop command and arguments (may throw std::bad_alloc)
332 void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
334 stop_command = command;
335 stop_arg_parts = separate_args(stop_command, stop_command_offsets);
338 // Get the current service state.
339 ServiceState getState() noexcept
341 return service_state;
344 // Get the target (aka desired) state.
345 ServiceState getTargetState() noexcept
347 return desired_state;
350 // Set logfile, should be done before service is started
351 void setLogfile(string logfile)
353 this->logfile = logfile;
356 // Set whether this service should automatically restart when it dies
357 void setAutoRestart(bool auto_restart) noexcept
359 this->auto_restart = auto_restart;
362 void setSmoothRecovery(bool smooth_recovery) noexcept
364 this->smooth_recovery = smooth_recovery;
367 // Set "on start" flags (commands)
368 void setOnstartFlags(OnstartFlags flags) noexcept
370 this->onstart_flags = flags;
373 // Set an additional signal (other than SIGTERM) to be used to terminate the process
374 void setExtraTerminationSignal(int signo) noexcept
376 this->term_signal = signo;
379 const char *getServiceName() const noexcept { return service_name.c_str(); }
380 ServiceState getState() const noexcept { return service_state; }
382 void start() noexcept; // start the service
383 void stop() noexcept; // stop the service
385 void pinStart() noexcept; // start the service and pin it
386 void pinStop() noexcept; // stop the service and pin it
387 void unpin() noexcept; // unpin the service
389 bool isDummy() noexcept
391 return service_type == ServiceType::DUMMY;
394 // Add a listener. A listener must only be added once. May throw std::bad_alloc.
395 void addListener(ServiceListener * listener)
397 listeners.insert(listener);
400 // Remove a listener.
401 void removeListener(ServiceListener * listener) noexcept
403 listeners.erase(listener);
411 std::list<ServiceRecord *> records;
412 const char *service_dir; // directory containing service descriptions
413 bool restart_enabled; // whether automatic restart is enabled (allowed)
415 ShutdownType shutdown_type = ShutdownType::CONTINUE; // Shutdown type, if stopping
417 ServiceRecord * console_queue_tail = nullptr; // last record in console queue
421 // Load a service description, and dependencies, if there is no existing
422 // record for the given name.
424 // ServiceLoadException (or subclass) on problem with service description
425 // std::bad_alloc on out-of-memory condition
426 ServiceRecord *loadServiceRecord(const char *name);
431 ServiceSet(const char *service_dir)
433 this->service_dir = service_dir;
435 restart_enabled = true;
438 // Start the service with the given name. The named service will begin
439 // transition to the 'started' state.
441 // Throws a ServiceLoadException (or subclass) if the service description
442 // cannot be loaded or is invalid;
443 // Throws std::bad_alloc if out of memory.
444 void startService(const char *name);
446 // Locate an existing service record.
447 ServiceRecord *findService(const std::string &name) noexcept;
449 // Find a loaded service record, or load it if it is not loaded.
451 // ServiceLoadException (or subclass) on problem with service description
452 // std::bad_alloc on out-of-memory condition
453 ServiceRecord *loadService(const std::string &name)
455 ServiceRecord *record = findService(name);
456 if (record == nullptr) {
457 record = loadServiceRecord(name.c_str());
462 // Stop the service with the given name. The named service will begin
463 // transition to the 'stopped' state.
464 void stopService(const std::string &name) noexcept;
466 // Set the console queue tail (returns previous tail)
467 ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
469 auto prev_tail = console_queue_tail;
470 console_queue_tail = newTail;
474 // Notification from service that it is active (state != STOPPED)
475 // Only to be called on the transition from inactive to active.
476 void service_active(ServiceRecord *) noexcept;
478 // Notification from service that it is inactive (STOPPED)
479 // Only to be called on the transition from active to inactive.
480 void service_inactive(ServiceRecord *) noexcept;
482 // Find out how many services are active (starting, running or stopping,
484 int count_active_services() noexcept
486 return active_services;
489 void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
491 restart_enabled = false;
492 shutdown_type = type;
493 for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
499 void set_auto_restart(bool restart) noexcept
501 restart_enabled = restart;
504 bool get_auto_restart() noexcept
506 return restart_enabled;
509 ShutdownType getShutdownType() noexcept
511 return shutdown_type;