Finish soft dependency support.
[oweals/dinit.git] / service.cc
1 #include "service.h"
2 #include <cstring>
3 #include <cerrno>
4 #include <sstream>
5 #include <iterator>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10
11 // Tokenize a string, allow quoting
12 // TODO doesn't yet allow quoting...
13 static std::vector<std::string> tokenize(std::string arg)
14 {
15     // TODO rewrite to be more efficient.
16     using namespace std;
17     istringstream iss(arg);
18     return vector<string>(istream_iterator<string>(iss), istream_iterator<string>());
19 }
20
21 // Find the requested service by name
22 static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
23                                     const char *name)
24 {
25     using std::list;
26     list<ServiceRecord *>::const_iterator i = records.begin();
27     for ( ; i != records.end(); i++ ) {
28         if (strcmp((*i)->getServiceName(), name) == 0) {
29             return *i;
30         }
31     }
32     return (ServiceRecord *)0;
33 }
34
35 ServiceRecord * ServiceSet::findService(std::string name)
36 {
37     return ::findService(records, name.c_str());
38 }
39
40 void ServiceSet::startService(const char *name)
41 {
42     using namespace std;
43     ServiceRecord *record = loadServiceRecord(name);
44     
45     record->start();
46 }
47
48 void ServiceSet::stopService(const std::string & name)
49 {
50     ServiceRecord *record = findService(name);
51     if (record != nullptr) {
52         record->stop();
53     }
54 }
55
56 // Called when a service has actually stopped.
57 void ServiceRecord::stopped()
58 {
59     service_state = SVC_STOPPED;
60     force_stop = false;
61     
62     // Stop any dependencies whose desired state is SVC_STOPPED:
63     for (sr_iter i = depends_on.begin(); i != depends_on.end(); i++) {
64         (*i)->dependentStopped();
65     }
66
67     service_set->service_inactive(this);
68     
69     // TODO inform listeners.
70     if (desired_state == SVC_STARTED) {
71         // Desired state is "started".
72         start();
73     }
74 }
75
76 void ServiceRecord::process_child_callback(struct ev_loop *loop, ev_child *w, int revents)
77 {    
78     ServiceRecord *sr = (ServiceRecord *) w->data;
79
80     sr->pid = -1;
81     ev_child_stop(ev_default_loop(EVFLAG_AUTO), &sr->child_listener);
82     
83     // Ok, for a process service, any process death which we didn't rig
84     // ourselves is a bit... unexpected. Probably, the child died because
85     // we asked it to (sr->service_state == SVC_STOPPING). But even if
86     // we didn't, there's not much we can do.
87     
88     if (sr->service_type == SVC_PROCESS) {
89         // TODO log non-zero rstatus?
90         if (sr->service_state == SVC_STOPPING) {
91             sr->stopped();
92         }
93         else {
94             sr->forceStop();
95         }
96         
97         if (sr->auto_restart && sr->service_set->get_auto_restart()) {
98             sr->start();
99         }
100     }
101     else {  // SVC_SCRIPTED
102         if (sr->service_state == SVC_STOPPING) {
103             if (w->rstatus == 0) {
104                 sr->stopped();
105             }
106             else {
107                 // TODO
108                 // ??? failed to stop!
109                 // For now just pretend we stopped, so that any dependencies
110                 // can be stopped:
111                 sr->stopped();
112             }
113         }
114         else { // SVC_STARTING
115             if (w->rstatus == 0) {
116                 sr->started();
117             }
118             else {
119                 // failed to start
120                 sr->failed_to_start();
121             }
122         }
123     }
124 }
125
126 void ServiceRecord::start()
127 {
128     if ((service_state == SVC_STARTING || service_state == SVC_STARTED)
129             && desired_state == SVC_STOPPED) {
130         // This service was starting, or started, but was set to be stopped.
131         // Cancel the stop (and continue starting/running).
132         // TODO any listeners waiting for stop should be notified of
133         //      its cancellation
134     }
135
136     auto old_desired_state = desired_state;
137     desired_state = SVC_STARTED;
138     
139     if (service_state == SVC_STARTED || service_state == SVC_STARTING) {
140         // We couldn't be started or starting unless all dependencies have
141         // already started: so there's nothing left to do.
142         return;
143     }
144     
145     bool all_deps_started = true;
146
147     // Ask dependencies to start, mark them as being waited on.
148     
149     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
150         // Note, we cannot treat a dependency as started if its force_stop
151         // flag is set.
152         if ((*i)->service_state != SVC_STARTED || (*i)->force_stop) {
153             all_deps_started = false;
154             (*i)->start();
155         }
156     }
157     
158     if (old_desired_state != SVC_STARTED) {
159         // This is a fresh start, so we mark all soft dependencies as 'waiting on' and ask them
160         // to start:
161         for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
162             if (i->getTo()->service_state != SVC_STARTED) {
163                 all_deps_started = false;
164                 i->getTo()->start();
165                 i->waiting_on = true;
166             }
167         }
168     }
169     else {
170         // This is (or at least may be) a notification that a dependency is ready; let's
171         // just check them:
172         for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
173             ServiceRecord * to = i->getTo();
174             if (i->waiting_on) {
175                 if ((to->desired_state != SVC_STARTED && to->service_state != SVC_STARTING) || to->service_state == SVC_STARTED) {
176                     // Service has either started or is no longer starting
177                     i->waiting_on = false;
178                 }
179                 else {
180                     all_deps_started = false;
181                 }
182             }
183         }
184     }
185     
186
187     if (! all_deps_started) {
188         // The dependencies will notify this service once they've started.
189         return;
190     }
191     
192     // Actually start this service.
193     service_state = SVC_STARTING;
194     service_set->service_active(this);
195     
196     if (service_type == SVC_PROCESS) {
197         bool start_success = start_ps_process();
198         if (start_success) {
199             started();
200         }
201         else {
202             failed_to_start();
203         }
204     }
205     else {
206         // Script-controlled service
207         bool start_success = start_ps_process(std::vector<std::string>(1, "start"));
208         if (! start_success) {
209             failed_to_start();
210         }
211     }
212 }
213
214 void ServiceRecord::started()
215 {
216     service_state = SVC_STARTED;
217     // TODO - inform listeners
218
219     if (desired_state == SVC_STARTED) {
220         // Start any dependents whose desired state is SVC_STARTED:
221         for (auto i = dependents.begin(); i != dependents.end(); i++) {
222             if ((*i)->desired_state == SVC_STARTED) {
223                 (*i)->start();
224             }
225         }
226         for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
227             if ((*i)->getFrom()->desired_state == SVC_STARTED) {
228                 (*i)->getFrom()->start();
229             }
230         }
231     }
232     else {
233         stop();
234     }
235 }
236
237 void ServiceRecord::failed_to_start()
238 {
239     service_state = SVC_STOPPED;
240     desired_state = SVC_STOPPED;
241     service_set->service_inactive(this);
242     // failure to start
243     // Cancel start of dependents:
244     for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
245         if ((*i)->desired_state == SVC_STARTED) {
246             (*i)->failed_dependency();
247         }
248     }    
249     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
250         if ((*i)->getFrom()->desired_state == SVC_STARTED) {
251             // We can send 'start', because this is only a soft dependency.
252             // Our startup failure means that they don't have to wait for us.
253             (*i)->getFrom()->start();
254         }
255     }
256 }
257
258 bool ServiceRecord::start_ps_process()
259 {
260     return start_ps_process(std::vector<std::string>());
261 }
262
263
264 bool ServiceRecord::start_ps_process(const std::vector<std::string> &pargs)
265 {
266     // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
267     // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
268     // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
269     // is written to the pipe, and the parent can read it.
270     
271     using std::vector;
272     using std::string;
273     
274     int pipefd[2];
275     if (pipe2(pipefd, O_CLOEXEC)) {
276         // TODO log error
277         return false;
278     }
279     
280     // TODO make sure pipefd's are not 0/1/2 (STDIN/OUT/ERR) - if they are, dup them
281     // until they are not.
282     
283     pid_t forkpid = fork();
284     if (forkpid == -1) {
285         // TODO log error
286         close(pipefd[0]);
287         close(pipefd[1]);
288         return false;
289     }
290     
291     if (forkpid == 0) {
292         // Child process
293         ev_default_destroy(); // won't need that on this side, free up fds.
294         
295         // Re-set stdin, stdout, stderr
296         close(0); close(1); close(2);
297         string logfile = this->logfile;
298         if (logfile.length() == 0) {
299             logfile = "/dev/null";
300         }
301         
302         // TODO rethink this logic. If we open it at not-0, shouldn't we just dup it to 0?:
303         if (open("/dev/null", O_RDONLY) == 0) {
304           // stdin = 0. That's what we should have; proceed with opening
305           // stdout and stderr.
306           open(logfile.c_str(), O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
307           dup2(1, 2);
308         }
309         
310         // Tokenize the command, and add additional arguments from pargs:
311         vector<string> progAndArgs = tokenize(program_name);
312         progAndArgs.insert(progAndArgs.end(), pargs.begin(), pargs.end());
313        
314         const char * pname = progAndArgs[0].c_str();
315         const char ** args = new const char *[progAndArgs.size() + 1];
316         
317         for (std::vector<std::string>::size_type i = 0; i < progAndArgs.size(); i++) {
318             args[i] = progAndArgs[i].c_str();
319         }
320         args[progAndArgs.size()] = nullptr;
321         
322         execvp(pname, (char ** const) args);
323         
324         // If we got here, the exec failed:        
325         int exec_status = errno;
326         write(pipefd[1], &exec_status, sizeof(int));
327         exit(0);
328     }
329     else {
330         // Parent process - we only reach here once the exec() above
331         // has succeeded, or _exit() above was called (because vfork()
332         // suspends the parent until either of those occurs).
333         
334         close(pipefd[1]); // close the 'other end' fd
335
336         int exec_status;        
337         if (read(pipefd[0], &exec_status, sizeof(int)) == 0) {
338             // pipe closed; success
339             pid = forkpid;
340
341             // Add a process listener so we can detect when the
342             // service stops
343             ev_child_init(&child_listener, process_child_callback, pid, 0);
344             child_listener.data = this;
345             ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
346
347             close(pipefd[0]);
348             return true;
349         }
350         else {
351             // TODO log error
352             close(pipefd[0]);
353             return false;
354         }
355     }
356 }
357
358
359
360
361 // Mark this and all dependent services as force-stopped.
362 void ServiceRecord::forceStop()
363 {
364     force_stop = true;
365     stop();
366     for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
367         (*i)->forceStop();
368     }
369     // We don't want to force stop soft dependencies, however.
370 }
371
372 // A dependency of this service failed to start.
373 void ServiceRecord::failed_dependency()
374 {
375     desired_state = SVC_STOPPED;
376     
377     // Presumably, we were starting. So now we're not.
378     service_state = SVC_STOPPED;
379     
380     // Notify dependents of this service also
381     for (auto i = dependents.begin(); i != dependents.end(); i++) {
382         if ((*i)->desired_state == SVC_STARTED) {
383             (*i)->failed_dependency();
384         }
385     }
386     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
387         if ((*i)->getFrom()->desired_state == SVC_STARTED) {
388             // It's a soft dependency, so send them 'started' rather than
389             // 'failed dep'.
390             (*i)->getFrom()->started();
391         }
392     }    
393 }
394
395 void ServiceRecord::dependentStopped()
396 {
397     if (service_state != SVC_STOPPED && (desired_state == SVC_STOPPED || force_stop)) {
398         // Check the other dependents before we stop.
399         if (stopCheckDependents()) {
400             stopping();
401         }
402     }
403 }
404
405 void ServiceRecord::stop()
406 {
407     if ((service_state == SVC_STOPPING || service_state == SVC_STOPPED)
408             && desired_state == SVC_STARTED) {
409         // The service *was* stopped/stopping, but it was going to restart.
410         // Now, we'll cancel the restart.
411         // TODO inform listeners waiting for start of cancellation
412     }
413     
414     if (desired_state == SVC_STOPPED) return;
415     
416     desired_state = SVC_STOPPED;
417
418     if (service_state != SVC_STARTED) {
419         if (service_state == SVC_STARTING) {
420             // Well this is awkward: we're going to have to continue
421             // starting, but we don't want any dependents to think that
422             // they are still waiting to start.
423             // Make sure they remain stopped:
424             stopDependents();
425         }
426         
427         // If we're starting we need to wait for that to complete.
428         // If we're already stopping/stopped there's nothing to do.
429         return;
430     }
431     
432     // If we get here, we are in STARTED state; stop all dependents.
433     if (stopCheckDependents()) {
434         stopping();
435     }
436 }
437
438 bool ServiceRecord::stopCheckDependents()
439 {
440     bool all_deps_stopped = true;
441     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
442         if ((*i)->service_state != SVC_STOPPED) {
443             all_deps_stopped = false;
444             break;
445         }
446     }
447     
448     return all_deps_stopped;
449 }
450
451 bool ServiceRecord::stopDependents()
452 {
453     bool all_deps_stopped = true;
454     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
455         if ((*i)->service_state != SVC_STOPPED) {
456             all_deps_stopped = false;
457             (*i)->stop();
458         }
459     }
460     
461     return all_deps_stopped;
462 }
463
464
465
466 // Dependency stopped or is stopping; we must stop too.
467 void ServiceRecord::stopping()
468 {
469     service_state = SVC_STOPPING;
470
471     if (service_type == SVC_PROCESS) {
472         if (pid != -1) {
473           // The process is still kicking on - must actually kill it.
474           kill(pid, SIGTERM);
475           // Now we wait; the rest is done in process_child_callback
476         }
477         else {
478             // The process is already dead.
479             stopped();
480         }
481     }
482     else {
483         // Scripted service.
484         start_ps_process(std::vector<string>(1, "stop"));
485     }    
486 }
487
488 void ServiceSet::service_active(ServiceRecord *sr)
489 {
490     active_services++;
491 }
492
493 void ServiceSet::service_inactive(ServiceRecord *sr)
494 {
495     active_services--;
496 }