4775fcf5b24a494d79f63ee4b931531941671cd5
[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
10 #include "dasync.h"
11
12 #include "control.h"
13 #include "service-listener.h"
14 #include "service-constants.h"
15
16 /*
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.
20  *
21  * Service states
22  * --------------
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.
27  *
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
33  *                         completed startup.
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.
38  *
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.
43  *
44  * Aquisition/release:
45  * ------------------
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).
51  *
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).
58  *
59  * Pinning
60  * -------
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).
64  *
65  * The priority of the different state deciders is:
66  *  - pins
67  *  - force stop flag
68  *  - desired state (which is manipulated by require/release operations)
69  *
70  * So a forced stop cannot occur until the service is not pinned started, for instance.
71  */
72
73 struct OnstartFlags {
74     bool rw_ready : 1;
75     
76     // Not actually "onstart" commands:
77     bool no_sigterm : 1;  // do not send SIGTERM
78     bool runs_on_console : 1;  // run "in the foreground"
79     
80     OnstartFlags() noexcept : rw_ready(false),
81             no_sigterm(false), runs_on_console(false)
82     {
83     }
84 };
85
86 // Exception while loading a service
87 class ServiceLoadExc
88 {
89     public:
90     std::string serviceName;
91     const char *excDescription;
92     
93     protected:
94     ServiceLoadExc(std::string serviceName) noexcept
95         : serviceName(serviceName)
96     {
97     }
98 };
99
100 class ServiceNotFound : public ServiceLoadExc
101 {
102     public:
103     ServiceNotFound(std::string serviceName) noexcept
104         : ServiceLoadExc(serviceName)
105     {
106         excDescription = "Service description not found.";
107     }
108 };
109
110 class ServiceCyclicDependency : public ServiceLoadExc
111 {
112     public:
113     ServiceCyclicDependency(std::string serviceName) noexcept
114         : ServiceLoadExc(serviceName)
115     {
116         excDescription = "Has cyclic dependency.";
117     }
118 };
119
120 class ServiceDescriptionExc : public ServiceLoadExc
121 {
122     public:
123     std::string extraInfo;
124     
125     ServiceDescriptionExc(std::string serviceName, std::string extraInfo) noexcept
126         : ServiceLoadExc(serviceName), extraInfo(extraInfo)
127     {
128         excDescription = extraInfo.c_str();
129     }    
130 };
131
132 class ServiceRecord; // forward declaration
133 class ServiceSet; // forward declaration
134
135 /* Service dependency record */
136 class ServiceDep
137 {
138     ServiceRecord * from;
139     ServiceRecord * to;
140
141     public:
142     /* Whether the 'from' service is waiting for the 'to' service to start */
143     bool waiting_on;
144
145     ServiceDep(ServiceRecord * from, ServiceRecord * to) noexcept : from(from), to(to), waiting_on(false)
146     {  }
147
148     ServiceRecord * getFrom() noexcept
149     {
150         return from;
151     }
152
153     ServiceRecord * getTo() noexcept
154     {
155         return to;
156     }
157 };
158
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)
163 {
164     std::vector<const char *> r;
165     r.reserve(arg_indices.size() + 1);
166
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;
171         }
172     }
173
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);
178     }
179     r.push_back(nullptr);
180     return r;
181 }
182
183 class ServiceChildWatcher : public PosixChildWatcher<NullMutex>
184 {
185     public:
186     // TODO resolve clunkiness of storing this field
187     ServiceRecord * service;
188     void gotTermStat(EventLoop_t * eloop, pid_t child, int status) noexcept;
189     
190     ServiceChildWatcher(ServiceRecord * sr) noexcept : service(sr) { }
191 };
192
193 class ServiceIoWatcher : public PosixFdWatcher<NullMutex>
194 {
195     public:
196     // TODO resolve clunkiness of storing these fields
197     int fd;
198     ServiceRecord * service;
199     Rearm gotEvent(EventLoop_t * eloop, int fd, int flags) noexcept;
200     
201     ServiceIoWatcher(ServiceRecord * sr) noexcept : service(sr) { }
202     
203     void registerWith(EventLoop_t *loop, int fd, int flags)
204     {
205         this->fd = fd;
206         PosixFdWatcher<NullMutex>::registerWith(loop, fd, flags);
207     }
208 };
209
210 class ServiceRecord
211 {
212     friend class ServiceChildWatcher;
213     friend class ServiceIoWatcher;
214     
215     typedef std::string string;
216     
217     string service_name;
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 */
221
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 */
224     
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 */
227     
228     string pid_file;
229     
230     OnstartFlags onstart_flags;
231
232     string logfile;           // log file name, empty string specifies /dev/null
233     
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
236     
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
245
246     typedef std::list<ServiceRecord *> sr_list;
247     typedef sr_list::iterator sr_iter;
248     
249     // list of soft dependencies
250     typedef std::list<ServiceDep> softdep_list;
251     
252     // list of soft dependents
253     typedef std::list<ServiceDep *> softdpt_list;
254     
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
259     
260     // unsigned wait_count;  /* if we are waiting for dependents/dependencies to
261     //                         start/stop, this is how many we're waiting for */
262     
263     ServiceSet *service_set; // the set this service belongs to
264     
265     std::unordered_set<ServiceListener *> listeners;
266     
267     // Process services:
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.
271     
272     int term_signal = -1;  // signal to use for process termination
273     
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
278
279     // Implementation details
280     
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.
287
288     ServiceChildWatcher child_listener;
289     ServiceIoWatcher child_status_listener;
290     
291     // All dependents have stopped.
292     void allDepsStopped();
293     
294     // Service has actually stopped (includes having all dependents
295     // reaching STOPPED state).
296     void stopped() noexcept;
297     
298     // Service has successfully started
299     void started() noexcept;
300     
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;
304
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;
308     
309     // Callback from libev when a child process dies
310     static void process_child_callback(EventLoop_t *loop, ServiceChildWatcher *w,
311             int revents) noexcept;
312     
313     static void process_child_status(EventLoop_t *loop, ServiceIoWatcher * stat_io,
314             int revents) noexcept;
315     
316     void handle_exit_status() noexcept;
317
318     // Called on transition of desired state from stopped to started (or unpinned stop)
319     void do_start() noexcept;
320
321     // Called on transition of desired state from started to stopped (or unpinned start)
322     void do_stop() noexcept;
323     
324     // A dependency has reached STARTED state
325     void dependencyStarted() noexcept;
326     
327     void allDepsStarted(bool haveConsole = false) noexcept;
328     
329     // Read the pid-file, return false on failure
330     bool read_pid_file() noexcept;
331     
332     // Open the activation socket, return false on failure
333     bool open_socket() noexcept;
334     
335     // Check whether dependencies have started, and optionally ask them to start
336     bool startCheckDependencies(bool do_start) noexcept;
337     
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
341     {
342         return waiting_for_deps;
343     }
344     
345     // Whether a STOPPING service can immediately transition to STARTED.
346     bool can_interrupt_stop() noexcept
347     {
348         return waiting_for_deps && ! force_stop;
349     }
350
351     // Notify dependencies that we no longer need them,
352     // (if this is actually the case).
353     void notify_dependencies_stopped() noexcept;
354
355     // A dependent has reached STOPPED state
356     void dependentStopped() noexcept;
357
358     // check if all dependents have stopped
359     bool stopCheckDependents() noexcept;
360     
361     // issue a stop to all dependents, return true if they are all already stopped
362     bool stopDependents() noexcept;
363     
364     void require() noexcept;
365     void release() noexcept;
366     void release_dependencies() noexcept;
367     
368     // Check if service is, fundamentally, stopped.
369     bool is_stopped() noexcept
370     {
371         return service_state == ServiceState::STOPPED
372             || (service_state == ServiceState::STARTING && waiting_for_deps);
373     }
374     
375     void notifyListeners(ServiceEvent event) noexcept
376     {
377         for (auto l : listeners) {
378             l->serviceEvent(this, event);
379         }
380     }
381     
382     // Queue to run on the console. 'acquiredConsole()' will be called when the console is available.
383     void queueForConsole() noexcept;
384     
385     // Release console (console must be currently held by this service)
386     void releaseConsole() noexcept;
387     
388     bool do_auto_restart() noexcept;
389     
390     public:
391
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)
397     {
398         service_set = set;
399         service_name = name;
400         service_type = ServiceType::DUMMY;
401     }
402     
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)
406     {
407         service_set = set;
408         service_name = name;
409         this->service_type = service_type;
410         this->depends_on = std::move(*pdepends_on);
411
412         program_name = command;
413         exec_arg_parts = separate_args(program_name, command_offsets);
414
415         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
416             (*i)->dependents.push_back(this);
417         }
418
419         // Soft dependencies
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));
424             ++b_iter;
425         }
426     }
427     
428     // TODO write a destructor
429
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;
432     
433     // Console is available.
434     void acquiredConsole() noexcept;
435     
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)
438     {
439         stop_command = command;
440         stop_arg_parts = separate_args(stop_command, stop_command_offsets);
441     }
442     
443     // Get the current service state.
444     ServiceState getState() noexcept
445     {
446         return service_state;
447     }
448     
449     // Get the target (aka desired) state.
450     ServiceState getTargetState() noexcept
451     {
452         return desired_state;
453     }
454
455     // Set logfile, should be done before service is started
456     void setLogfile(string logfile)
457     {
458         this->logfile = logfile;
459     }
460     
461     // Set whether this service should automatically restart when it dies
462     void setAutoRestart(bool auto_restart) noexcept
463     {
464         this->auto_restart = auto_restart;
465     }
466     
467     void setSmoothRecovery(bool smooth_recovery) noexcept
468     {
469         this->smooth_recovery = smooth_recovery;
470     }
471     
472     // Set "on start" flags (commands)
473     void setOnstartFlags(OnstartFlags flags) noexcept
474     {
475         this->onstart_flags = flags;
476     }
477     
478     // Set an additional signal (other than SIGTERM) to be used to terminate the process
479     void setExtraTerminationSignal(int signo) noexcept
480     {
481         this->term_signal = signo;
482     }
483     
484     void set_pid_file(string &&pid_file) noexcept
485     {
486         this->pid_file = pid_file;
487     }
488     
489     void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid) noexcept
490     {
491         this->socket_path = socket_path;
492         this->socket_perms = socket_perms;
493         this->socket_uid = socket_uid;
494         this->socket_gid = socket_gid;
495     }
496
497     const char *getServiceName() const noexcept { return service_name.c_str(); }
498     ServiceState getState() const noexcept { return service_state; }
499     
500     void start(bool activate = true) noexcept;  // start the service
501     void stop(bool bring_down = true) noexcept;   // stop the service
502     
503     void forceStop() noexcept; // force-stop this service and all dependents
504     
505     // Pin the service in "started" state (when it reaches the state)
506     void pinStart() noexcept
507     {
508         pinned_started = true;
509     }
510     
511     // Pin the service in "stopped" state (when it reaches the state)
512     void pinStop() noexcept
513     {
514         pinned_stopped = true;
515     }
516     
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;
521     
522     bool isDummy() noexcept
523     {
524         return service_type == ServiceType::DUMMY;
525     }
526     
527     // Add a listener. A listener must only be added once. May throw std::bad_alloc.
528     void addListener(ServiceListener * listener)
529     {
530         listeners.insert(listener);
531     }
532     
533     // Remove a listener.    
534     void removeListener(ServiceListener * listener) noexcept
535     {
536         listeners.erase(listener);
537     }
538 };
539
540
541 class ServiceSet
542 {
543     int active_services;
544     std::list<ServiceRecord *> records;
545     const char *service_dir;  // directory containing service descriptions
546     bool restart_enabled; // whether automatic restart is enabled (allowed)
547     
548     ShutdownType shutdown_type = ShutdownType::CONTINUE;  // Shutdown type, if stopping
549     
550     ServiceRecord * console_queue_head = nullptr; // first record in console queue
551     ServiceRecord * console_queue_tail = nullptr; // last record in console queue
552     
553     // Private methods
554         
555     // Load a service description, and dependencies, if there is no existing
556     // record for the given name.
557     // Throws:
558     //   ServiceLoadException (or subclass) on problem with service description
559     //   std::bad_alloc on out-of-memory condition
560     ServiceRecord *loadServiceRecord(const char *name);
561
562     // Public
563     
564     public:
565     ServiceSet(const char *service_dir)
566     {
567         this->service_dir = service_dir;
568         active_services = 0;
569         restart_enabled = true;
570     }
571     
572     // Start the service with the given name. The named service will begin
573     // transition to the 'started' state.
574     //
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);
579     
580     // Locate an existing service record.
581     ServiceRecord *findService(const std::string &name) noexcept;
582     
583     // Find a loaded service record, or load it if it is not loaded.
584     // Throws:
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)
588     {
589         ServiceRecord *record = findService(name);
590         if (record == nullptr) {
591             record = loadServiceRecord(name.c_str());
592         }
593         return record;
594     }
595     
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;
599     
600     // Set the console queue tail (returns previous tail)
601     ServiceRecord * consoleQueueTail(ServiceRecord * newTail) noexcept
602     {
603         auto prev_tail = console_queue_tail;
604         console_queue_tail = newTail;
605         if (! prev_tail) {
606             console_queue_head = newTail;
607             enable_console_log(false);
608         }
609         else {
610             prev_tail->next_for_console = newTail;
611         }
612         return prev_tail;
613     }
614     
615     // Retrieve the current console queue head and remove it from the queue
616     ServiceRecord * pullConsoleQueue() noexcept
617     {
618         auto prev_head = console_queue_head;
619         if (prev_head) {
620             prev_head->acquiredConsole();
621             console_queue_head = prev_head->next_for_console;
622             if (! console_queue_head) {
623                 console_queue_tail = nullptr;
624             }
625         }
626         else {
627             enable_console_log(true);
628         }
629         return prev_head;
630     }
631     
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;
635     
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;
639     
640     // Find out how many services are active (starting, running or stopping,
641     // but not stopped).
642     int count_active_services() noexcept
643     {
644         return active_services;
645     }
646     
647     void stop_all_services(ShutdownType type = ShutdownType::HALT) noexcept
648     {
649         restart_enabled = false;
650         shutdown_type = type;
651         for (std::list<ServiceRecord *>::iterator i = records.begin(); i != records.end(); ++i) {
652             (*i)->stop(false);
653             (*i)->unpin();
654         }
655     }
656     
657     void set_auto_restart(bool restart) noexcept
658     {
659         restart_enabled = restart;
660     }
661     
662     bool get_auto_restart() noexcept
663     {
664         return restart_enabled;
665     }
666     
667     ShutdownType getShutdownType() noexcept
668     {
669         return shutdown_type;
670     }
671 };
672
673 #endif