When performing shutdown, un-pin services after issuing stop.
[oweals/dinit.git] / 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.
36  */
37
38 struct OnstartFlags {
39     bool rw_ready : 1;
40     
41     // Not actually "onstart" commands:
42     bool no_sigterm : 1;  // do not send SIGTERM
43     bool runs_on_console : 1;  // run "in the foreground"
44     
45     OnstartFlags() noexcept : rw_ready(false),
46             no_sigterm(false), runs_on_console(false)
47     {
48     }
49 };
50
51 // Exception while loading a service
52 class ServiceLoadExc
53 {
54     public:
55     std::string serviceName;
56     const char *excDescription;
57     
58     protected:
59     ServiceLoadExc(std::string serviceName) noexcept
60         : serviceName(serviceName)
61     {
62     }
63 };
64
65 class ServiceNotFound : public ServiceLoadExc
66 {
67     public:
68     ServiceNotFound(std::string serviceName) noexcept
69         : ServiceLoadExc(serviceName)
70     {
71         excDescription = "Service description not found.";
72     }
73 };
74
75 class ServiceCyclicDependency : public ServiceLoadExc
76 {
77     public:
78     ServiceCyclicDependency(std::string serviceName) noexcept
79         : ServiceLoadExc(serviceName)
80     {
81         excDescription = "Has cyclic dependency.";
82     }
83 };
84
85 class ServiceDescriptionExc : public ServiceLoadExc
86 {
87     public:
88     std::string extraInfo;
89     
90     ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
91         : ServiceLoadExc(serviceName), extraInfo(extraInfo)
92     {
93         excDescription = extraInfo.c_str();
94     }    
95 };
96
97 class ServiceRecord; // forward declaration
98 class ServiceSet; // forward declaration
99
100 /* Service dependency record */
101 class ServiceDep
102 {
103     ServiceRecord * from;
104     ServiceRecord * to;
105
106     public:
107     /* Whether the 'from' service is waiting for the 'to' service to start */
108     bool waiting_on;
109
110     ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false)
111     {  }
112
113     ServiceRecord * getFrom() noexcept
114     {
115         return from;
116     }
117
118     ServiceRecord * getTo() noexcept
119     {
120         return to;
121     }
122 };
123
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)
128 {
129     std::vector<const char *> r;
130     r.reserve(arg_indices.size() + 1);
131
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;
136         }
137     }
138
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);
143     }
144     r.push_back(nullptr);
145     return r;
146 }
147
148
149 class ServiceRecord
150 {
151     typedef std::string string;
152     
153     string service_name;
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 */
157
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 */
160     
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 */
163     
164     OnstartFlags onstart_flags;
165
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;
171     
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() */
174
175     typedef std::list<ServiceRecord *> sr_list;
176     typedef sr_list::iterator sr_iter;
177     
178     // list of soft dependencies
179     typedef std::list<ServiceDep> softdep_list;
180     
181     // list of soft dependents
182     typedef std::list<ServiceDep *> softdpt_list;
183     
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
188     
189     // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
190     //                         start/stop, this is how many we're waiting for */
191     
192     ServiceSet *service_set; // the set this service belongs to
193     
194     // Next service (after this one) in the queue for the console:
195     ServiceRecord *next_for_console;
196     
197     // Process services:
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.
201     
202     std::unordered_set<ServiceListener *> listeners;
203
204     int term_signal = -1;  // signal to use for process termination
205
206     // Implementation details
207     
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).
212
213     ev_child child_listener;
214     ev_io child_status_listener;
215     
216     // All dependents have stopped.
217     void allDepsStopped();
218     
219     // Service has actually stopped (includes having all dependents
220     // reaching STOPPED state).
221     void stopped() noexcept;
222     
223     // Service has successfully started
224     void started();
225     
226     // Service failed to start
227     void failed_to_start();
228     
229     // A dependency of this service failed to start.
230     void failed_dependency();
231     
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;
235     
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;
239     
240     static void process_child_status(struct ev_loop *loop, ev_io * stat_io,
241             int revents) noexcept;
242     
243     void handle_exit_status() noexcept;
244     
245     // A dependency has reached STARTED state
246     void dependencyStarted() noexcept;
247     
248     void allDepsStarted(bool haveConsole = false) noexcept;
249     
250     // Check whether dependencies have started, and optionally ask them to start
251     bool startCheckDependencies(bool do_start) noexcept;
252     
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
256     {
257         return waiting_for_deps;
258     }
259     
260     // Whether a STOPPING service can immediately transition to STARTED.
261     bool can_interrupt_stop() noexcept
262     {
263         return waiting_for_deps && ! force_stop;
264     }
265
266     // A dependent has reached STOPPED state
267     void dependentStopped() noexcept;
268
269     // check if all dependents have stopped
270     bool stopCheckDependents() noexcept;
271     
272     // issue a stop to all dependents, return true if they are all already stopped
273     bool stopDependents() noexcept;
274     
275     void forceStop() noexcept; // force-stop this service and all dependents
276     
277     void notifyListeners(ServiceEvent event) noexcept
278     {
279         for (auto l : listeners) {
280             l->serviceEvent(this, event);
281         }
282     }
283     
284     // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
285     void queueForConsole() noexcept;
286     
287     // Console is available.
288     void acquiredConsole() noexcept;
289     
290     // Release console (console must be currently held by this service)
291     void releaseConsole() noexcept;
292     
293     public:
294
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)
298     {
299         service_set = set;
300         service_name = name;
301         service_type = ServiceType::DUMMY;
302     }
303     
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)
307     {
308         service_set = set;
309         service_name = name;
310         this->service_type = service_type;
311         this->depends_on = std::move(*pdepends_on);
312
313         program_name = command;
314         exec_arg_parts = separate_args(program_name, command_offsets);
315
316         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
317             (*i)->dependents.push_back(this);
318         }
319
320         // Soft dependencies
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));
325             ++b_iter;
326         }
327     }
328     
329     // TODO write a destructor
330     
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)
333     {
334         stop_command = command;
335         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
336     }
337     
338     // Get the current service state.
339     ServiceState getState() noexcept
340     {
341         return service_state;
342     }
343     
344     // Get the target (aka desired) state.
345     ServiceState getTargetState() noexcept
346     {
347         return desired_state;
348     }
349
350     // Set logfile, should be done before service is started
351     void setLogfile(string logfile)
352     {
353         this->logfile = logfile;
354     }
355     
356     // Set whether this service should automatically restart when it dies
357     void setAutoRestart(bool auto_restart) noexcept
358     {
359         this->auto_restart = auto_restart;
360     }
361     
362     void setSmoothRecovery(bool smooth_recovery) noexcept
363     {
364         this->smooth_recovery = smooth_recovery;
365     }
366     
367     // Set "on start" flags (commands)
368     void setOnstartFlags(OnstartFlags flags) noexcept
369     {
370         this->onstart_flags = flags;
371     }
372     
373     // Set an additional signal (other than SIGTERM) to be used to terminate the process
374     void setExtraTerminationSignal(int signo) noexcept
375     {
376         this->term_signal = signo;
377     }
378
379     const char *getServiceName() const noexcept { return service_name.c_str(); }
380     ServiceState getState() const noexcept { return service_state; }
381     
382     void start() noexcept;  // start the service
383     void stop() noexcept;   // stop the service
384     
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
388     
389     bool isDummy() noexcept
390     {
391         return service_type == ServiceType::DUMMY;
392     }
393     
394     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
395     void addListener(ServiceListener * listener)
396     {
397         listeners.insert(listener);
398     }
399     
400     // Remove a listener.    
401     void removeListener(ServiceListener * listener) noexcept
402     {
403         listeners.erase(listener);
404     }
405 };
406
407
408 class ServiceSet
409 {
410     int active_services;
411     std::list<ServiceRecord *> records;
412     const char *service_dir;  // directory containing service descriptions
413     bool restart_enabled; // whether automatic restart is enabled (allowed)
414     
415     ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
416     
417     ServiceRecord * console_queue_tail = nullptr; // last record in console queue
418     
419     // Private methods
420         
421     // Load a service description, and dependencies, if there is no existing
422     // record for the given name.
423     // Throws:
424     //   ServiceLoadException (or subclass) on problem with service description
425     //   std::bad_alloc on out-of-memory condition
426     ServiceRecord *loadServiceRecord(const char *name);
427
428     // Public
429     
430     public:
431     ServiceSet(const char *service_dir)
432     {
433         this->service_dir = service_dir;
434         active_services = 0;
435         restart_enabled = true;
436     }
437     
438     // Start the service with the given name. The named service will begin
439     // transition to the 'started' state.
440     //
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);
445     
446     // Locate an existing service record.
447     ServiceRecord *findService(const std::string &name) noexcept;
448     
449     // Find a loaded service record, or load it if it is not loaded.
450     // Throws:
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)
454     {
455         ServiceRecord *record = findService(name);
456         if (record == nullptr) {
457             record = loadServiceRecord(name.c_str());
458         }
459         return record;
460     }
461     
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;
465     
466     // Set the console queue tail (returns previous tail)
467     ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
468     {
469         auto prev_tail = console_queue_tail;
470         console_queue_tail = newTail;
471         return prev_tail;
472     }
473     
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;
477     
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;
481     
482     // Find out how many services are active (starting, running or stopping,
483     // but not stopped).
484     int count_active_services() noexcept
485     {
486         return active_services;
487     }
488     
489     void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
490     {
491         restart_enabled = false;
492         shutdown_type = type;
493         for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
494             (*i)->stop();
495             (*i)->unpin();
496         }
497     }
498     
499     void set_auto_restart(bool restart) noexcept
500     {
501         restart_enabled = restart;
502     }
503     
504     bool get_auto_restart() noexcept
505     {
506         return restart_enabled;
507     }
508     
509     ShutdownType getShutdownType() noexcept
510     {
511         return shutdown_type;
512     }
513 };
514
515 #endif