0140168a7e3da9e3c6395198f2f9e9707dcb976b
[oweals/dinit.git] / src / service.h
1 #ifndef SERVICE_H
2 #define SERVICE_H
3
4 #include <string>
5 #include <list>
6 #include <vector>
7 #include <csignal>
8 #include <unordered_set>
9 #include "ev.h"
10 #include "control.h"
11 #include "service-listener.h"
12 #include "service-constants.h"
13
14 /*
15  * Possible service states
16  *
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.
21  *
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
27  *                         completed startup.
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.
32  *
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 or for the exec() call in
36  * the forked child to complete and return a status.
37  */
38
39 struct OnstartFlags {
40     bool rw_ready : 1;
41     
42     // Not actually "onstart" commands:
43     bool no_sigterm : 1;  // do not send SIGTERM
44     bool runs_on_console : 1;  // run "in the foreground"
45     
46     OnstartFlags() noexcept : rw_ready(false),
47             no_sigterm(false), runs_on_console(false)
48     {
49     }
50 };
51
52 // Exception while loading a service
53 class ServiceLoadExc
54 {
55     public:
56     std::string serviceName;
57     const char *excDescription;
58     
59     protected:
60     ServiceLoadExc(std::string serviceName) noexcept
61         : serviceName(serviceName)
62     {
63     }
64 };
65
66 class ServiceNotFound : public ServiceLoadExc
67 {
68     public:
69     ServiceNotFound(std::string serviceName) noexcept
70         : ServiceLoadExc(serviceName)
71     {
72         excDescription = "Service description not found.";
73     }
74 };
75
76 class ServiceCyclicDependency : public ServiceLoadExc
77 {
78     public:
79     ServiceCyclicDependency(std::string serviceName) noexcept
80         : ServiceLoadExc(serviceName)
81     {
82         excDescription = "Has cyclic dependency.";
83     }
84 };
85
86 class ServiceDescriptionExc : public ServiceLoadExc
87 {
88     public:
89     std::string extraInfo;
90     
91     ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
92         : ServiceLoadExc(serviceName), extraInfo(extraInfo)
93     {
94         excDescription = extraInfo.c_str();
95     }    
96 };
97
98 class ServiceRecord; // forward declaration
99 class ServiceSet; // forward declaration
100
101 /* Service dependency record */
102 class ServiceDep
103 {
104     ServiceRecord * from;
105     ServiceRecord * to;
106
107     public:
108     /* Whether the 'from' service is waiting for the 'to' service to start */
109     bool waiting_on;
110
111     ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false)
112     {  }
113
114     ServiceRecord * getFrom() noexcept
115     {
116         return from;
117     }
118
119     ServiceRecord * getTo() noexcept
120     {
121         return to;
122     }
123 };
124
125 // Given a string and a list of pairs of (start,end) indices for each argument in that string,
126 // store a null terminator for the argument. Return a `char *` vector containing the beginning
127 // of each argument and a trailing nullptr. (The returned array is invalidated if the string is later modified).
128 static std::vector<const char *> separate_args(std::string &s, std::list<std::pair<unsigned,unsigned>> &arg_indices)
129 {
130     std::vector<const char *> r;
131     r.reserve(arg_indices.size() + 1);
132
133     // First store nul terminator for each part:
134     for (auto index_pair : arg_indices) {
135         if (index_pair.second < s.length()) {
136             s[index_pair.second] = 0;
137         }
138     }
139
140     // Now we can get the C string (c_str) and store offsets into it:
141     const char * cstr = s.c_str();
142     for (auto index_pair : arg_indices) {
143         r.push_back(cstr + index_pair.first);
144     }
145     r.push_back(nullptr);
146     return r;
147 }
148
149
150 class ServiceRecord
151 {
152     typedef std::string string;
153     
154     string service_name;
155     ServiceType service_type;  /* ServiceType::DUMMY, PROCESS, SCRIPTED, INTERNAL */
156     ServiceState service_state = ServiceState::STOPPED; /* ServiceState::STOPPED, STARTING, STARTED, STOPPING */
157     ServiceState desired_state = ServiceState::STOPPED; /* ServiceState::STOPPED / STARTED */
158
159     string program_name;          /* storage for program/script and arguments */
160     std::vector<const char *> exec_arg_parts; /* pointer to each argument/part of the program_name */
161     
162     string stop_command;          /* storage for stop program/script and arguments */
163     std::vector<const char *> stop_arg_parts; /* pointer to each argument/part of the stop_command */
164     
165     string pid_file;
166     
167     OnstartFlags onstart_flags;
168
169     string logfile;           // log file name, empty string specifies /dev/null
170     
171     bool auto_restart : 1;    // whether to restart this (process) if it dies unexpectedly
172     bool smooth_recovery : 1; // whether the service process can restart without bringing down service
173     
174     bool pinned_stopped : 1;
175     bool pinned_started : 1;
176     bool waiting_for_deps : 1;  // if STARTING, whether we are waiting for dependencies (inc console) to start
177     bool waiting_for_execstat : 1;  // if we are waiting for exec status after fork()
178     bool doing_recovery : 1;    // if we are currently recovering a BGPROCESS (restarting process, while
179                                 //   holding STARTED service state)
180     bool start_explicit : 1;    // whether we are are explictly required to be started
181     int required_by = 0;        // number of dependents wanting this service to be started
182
183     typedef std::list<ServiceRecord *> sr_list;
184     typedef sr_list::iterator sr_iter;
185     
186     // list of soft dependencies
187     typedef std::list<ServiceDep> softdep_list;
188     
189     // list of soft dependents
190     typedef std::list<ServiceDep *> softdpt_list;
191     
192     sr_list depends_on; // services this one depends on
193     sr_list dependents; // services depending on this one
194     softdep_list soft_deps;  // services this one depends on via a soft dependency
195     softdpt_list soft_dpts;  // services depending on this one via a soft dependency
196     
197     // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
198     //                         start/stop, this is how many we're waiting for */
199     
200     ServiceSet *service_set; // the set this service belongs to
201     
202     // Next service (after this one) in the queue for the console:
203     ServiceRecord *next_for_console;
204
205     std::unordered_set<ServiceListener *> listeners;
206     
207     // Process services:
208     bool force_stop; // true if the service must actually stop. This is the
209                      // case if for example the process dies; the service,
210                      // and all its dependencies, MUST be stopped.
211     
212     int term_signal = -1;  // signal to use for process termination
213     
214     string socket_path; // path to the socket for socket-activation service
215     int socket_perms;   // socket permissions ("mode")
216     uid_t socket_uid = -1;  // socket user id or -1
217     gid_t socket_gid = -1;  // sockget group id or -1
218
219     // Implementation details
220     
221     pid_t pid = -1;  // PID of the process. If state is STARTING or STOPPING,
222                      //   this is PID of the service script; otherwise it is the
223                      //   PID of the process itself (process service).
224     int exit_status; // Exit status, if the process has exited (pid == -1).
225     int socket_fd = -1;  // For socket-activation services, this is the file
226                          // descriptor for the socket.
227
228     ev_child child_listener;
229     ev_io child_status_listener;
230     
231     // All dependents have stopped.
232     void allDepsStopped();
233     
234     // Service has actually stopped (includes having all dependents
235     // reaching STOPPED state).
236     void stopped() noexcept;
237     
238     // Service has successfully started
239     void started() noexcept;
240     
241     // Service failed to start (only called when in STARTING state).
242     //   dep_failed: whether failure is recorded due to a dependency failing
243     void failed_to_start(bool dep_failed = false) noexcept;
244
245     // For process services, start the process, return true on success
246     bool start_ps_process() noexcept;
247     bool start_ps_process(const std::vector<const char *> &args, bool on_console) noexcept;
248     
249     // Callback from libev when a child process dies
250     static void process_child_callback(struct ev_loop *loop, struct ev_child *w,
251             int revents) noexcept;
252     
253     static void process_child_status(struct ev_loop *loop, ev_io * stat_io,
254             int revents) noexcept;
255     
256     void handle_exit_status() noexcept;
257     
258     void do_start() noexcept;
259     void do_stop() noexcept;
260     
261     // A dependency has reached STARTED state
262     void dependencyStarted() noexcept;
263     
264     void allDepsStarted(bool haveConsole = false) noexcept;
265     
266     // Read the pid-file, return false on failure
267     bool read_pid_file() noexcept;
268     
269     // Open the activation socket, return false on failure
270     bool open_socket() noexcept;
271     
272     // Check whether dependencies have started, and optionally ask them to start
273     bool startCheckDependencies(bool do_start) noexcept;
274     
275     // Whether a STARTING service can immediately transition to STOPPED (as opposed to
276     // having to wait for it reach STARTED and then go through STOPPING).
277     bool can_interrupt_start() noexcept
278     {
279         return waiting_for_deps;
280     }
281     
282     // Whether a STOPPING service can immediately transition to STARTED.
283     bool can_interrupt_stop() noexcept
284     {
285         return waiting_for_deps && ! force_stop;
286     }
287
288     // Notify dependencies that we no longer need them,
289     // (if this is actually the case).
290     void notify_dependencies_stopped() noexcept;
291
292     // A dependent has reached STOPPED state
293     void dependentStopped() noexcept;
294
295     // check if all dependents have stopped
296     bool stopCheckDependents() noexcept;
297     
298     // issue a stop to all dependents, return true if they are all already stopped
299     bool stopDependents() noexcept;
300     
301     void require() noexcept;
302     void release() noexcept;
303     void release_dependencies() noexcept;
304     
305     // Check if service is, fundamentally, stopped.
306     bool is_stopped() noexcept
307     {
308         return service_state == ServiceState::STOPPED
309             || (service_state == ServiceState::STARTING && waiting_for_deps);
310     }
311     
312     void notifyListeners(ServiceEvent event) noexcept
313     {
314         for (auto l : listeners) {
315             l->serviceEvent(this, event);
316         }
317     }
318     
319     // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
320     void queueForConsole() noexcept;
321     
322     // Console is available.
323     void acquiredConsole() noexcept;
324     
325     // Release console (console must be currently held by this service)
326     void releaseConsole() noexcept;
327     
328     bool do_auto_restart() noexcept;
329     
330     public:
331
332     ServiceRecord(ServiceSet *set, string name)
333         : service_state(ServiceState::STOPPED), desired_state(ServiceState::STOPPED), auto_restart(false),
334             pinned_stopped(false), pinned_started(false), waiting_for_deps(false),
335             waiting_for_execstat(false), doing_recovery(false),
336             start_explicit(false), force_stop(false)
337     {
338         service_set = set;
339         service_name = name;
340         service_type = ServiceType::DUMMY;
341     }
342     
343     ServiceRecord(ServiceSet *set, string name, ServiceType service_type, string &&command, std::list<std::pair<unsigned,unsigned>> &command_offsets,
344             sr_list * pdepends_on, sr_list * pdepends_soft)
345         : ServiceRecord(set, name)
346     {
347         service_set = set;
348         service_name = name;
349         this->service_type = service_type;
350         this->depends_on = std::move(*pdepends_on);
351
352         program_name = command;
353         exec_arg_parts = separate_args(program_name, command_offsets);
354
355         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
356             (*i)->dependents.push_back(this);
357         }
358
359         // Soft dependencies
360         auto b_iter = soft_deps.end();
361         for (sr_iter i = pdepends_soft->begin(); i != pdepends_soft->end(); ++i) {
362             b_iter = soft_deps.emplace(b_iter, this, *i);
363             (*i)->soft_dpts.push_back(&(*b_iter));
364             ++b_iter;
365         }
366     }
367     
368     // TODO write a destructor
369     
370     // Set the stop command and arguments (may throw std::bad_alloc)
371     void setStopCommand(std::string command, std::list<std::pair<unsigned,unsigned>> &stop_command_offsets)
372     {
373         stop_command = command;
374         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
375     }
376     
377     // Get the current service state.
378     ServiceState getState() noexcept
379     {
380         return service_state;
381     }
382     
383     // Get the target (aka desired) state.
384     ServiceState getTargetState() noexcept
385     {
386         return desired_state;
387     }
388
389     // Set logfile, should be done before service is started
390     void setLogfile(string logfile)
391     {
392         this->logfile = logfile;
393     }
394     
395     // Set whether this service should automatically restart when it dies
396     void setAutoRestart(bool auto_restart) noexcept
397     {
398         this->auto_restart = auto_restart;
399     }
400     
401     void setSmoothRecovery(bool smooth_recovery) noexcept
402     {
403         this->smooth_recovery = smooth_recovery;
404     }
405     
406     // Set "on start" flags (commands)
407     void setOnstartFlags(OnstartFlags flags) noexcept
408     {
409         this->onstart_flags = flags;
410     }
411     
412     // Set an additional signal (other than SIGTERM) to be used to terminate the process
413     void setExtraTerminationSignal(int signo) noexcept
414     {
415         this->term_signal = signo;
416     }
417     
418     void set_pid_file(string &&pid_file) noexcept
419     {
420         this->pid_file = pid_file;
421     }
422     
423     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
424     {
425         this->socket_path = socket_path;
426         this->socket_perms = socket_perms;
427         this->socket_uid = socket_uid;
428         this->socket_gid = socket_gid;
429     }
430
431     const char *getServiceName() const noexcept { return service_name.c_str(); }
432     ServiceState getState() const noexcept { return service_state; }
433     
434     void start(bool activate = true) noexcept;  // start the service
435     void stop(bool bring_down = true) noexcept;   // stop the service
436     
437     void forceStop() noexcept; // force-stop this service and all dependents
438     
439     // Pin the service in "started" state (when it reaches the state)
440     void pinStart() noexcept
441     {
442         pinned_started = true;
443     }
444     
445     // Pin the service in "stopped" state (when it reaches the state)
446     void pinStop() noexcept
447     {
448         pinned_stopped = true;
449     }
450     
451     // Remove both "started" and "stopped" pins. If the service is currently pinned
452     // in either state but would naturally be in the opposite state, it will immediately
453     // commence starting/stopping.
454     void unpin() noexcept;
455     
456     bool isDummy() noexcept
457     {
458         return service_type == ServiceType::DUMMY;
459     }
460     
461     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
462     void addListener(ServiceListener * listener)
463     {
464         listeners.insert(listener);
465     }
466     
467     // Remove a listener.    
468     void removeListener(ServiceListener * listener) noexcept
469     {
470         listeners.erase(listener);
471     }
472 };
473
474
475 class ServiceSet
476 {
477     int active_services;
478     std::list<ServiceRecord *> records;
479     const char *service_dir;  // directory containing service descriptions
480     bool restart_enabled; // whether automatic restart is enabled (allowed)
481     
482     ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
483     
484     ServiceRecord * console_queue_tail = nullptr; // last record in console queue
485     
486     // Private methods
487         
488     // Load a service description, and dependencies, if there is no existing
489     // record for the given name.
490     // Throws:
491     //   ServiceLoadException (or subclass) on problem with service description
492     //   std::bad_alloc on out-of-memory condition
493     ServiceRecord *loadServiceRecord(const char *name);
494
495     // Public
496     
497     public:
498     ServiceSet(const char *service_dir)
499     {
500         this->service_dir = service_dir;
501         active_services = 0;
502         restart_enabled = true;
503     }
504     
505     // Start the service with the given name. The named service will begin
506     // transition to the 'started' state.
507     //
508     // Throws a ServiceLoadException (or subclass) if the service description
509     // cannot be loaded or is invalid;
510     // Throws std::bad_alloc if out of memory.
511     void startService(const char *name);
512     
513     // Locate an existing service record.
514     ServiceRecord *findService(const std::string &name) noexcept;
515     
516     // Find a loaded service record, or load it if it is not loaded.
517     // Throws:
518     //   ServiceLoadException (or subclass) on problem with service description
519     //   std::bad_alloc on out-of-memory condition 
520     ServiceRecord *loadService(const std::string &name)
521     {
522         ServiceRecord *record = findService(name);
523         if (record == nullptr) {
524             record = loadServiceRecord(name.c_str());
525         }
526         return record;
527     }
528     
529     // Stop the service with the given name. The named service will begin
530     // transition to the 'stopped' state.
531     void stopService(const std::string &name) noexcept;
532     
533     // Set the console queue tail (returns previous tail)
534     ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
535     {
536         auto prev_tail = console_queue_tail;
537         console_queue_tail = newTail;
538         return prev_tail;
539     }
540     
541     // Notification from service that it is active (state != STOPPED)
542     // Only to be called on the transition from inactive to active.
543     void service_active(ServiceRecord *) noexcept;
544     
545     // Notification from service that it is inactive (STOPPED)
546     // Only to be called on the transition from active to inactive.
547     void service_inactive(ServiceRecord *) noexcept;
548     
549     // Find out how many services are active (starting, running or stopping,
550     // but not stopped).
551     int count_active_services() noexcept
552     {
553         return active_services;
554     }
555     
556     void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
557     {
558         restart_enabled = false;
559         shutdown_type = type;
560         for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
561             (*i)->stop(false);
562             (*i)->unpin();
563         }
564     }
565     
566     void set_auto_restart(bool restart) noexcept
567     {
568         restart_enabled = restart;
569     }
570     
571     bool get_auto_restart() noexcept
572     {
573         return restart_enabled;
574     }
575     
576     ShutdownType getShutdownType() noexcept
577     {
578         return shutdown_type;
579     }
580 };
581
582 #endif