11 // Tokenize a string, allow quoting
12 // TODO doesn't yet allow quoting...
13 static std::vector<std::string> tokenize(std::string arg)
15 // TODO rewrite to be more efficient.
17 istringstream iss(arg);
18 return vector<string>(istream_iterator<string>(iss), istream_iterator<string>());
21 // Find the requested service by name
22 static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
26 list<ServiceRecord *>::const_iterator i = records.begin();
27 for ( ; i != records.end(); i++ ) {
28 if (strcmp((*i)->getServiceName(), name) == 0) {
32 return (ServiceRecord *)0;
35 ServiceRecord * ServiceSet::findService(std::string name)
37 return ::findService(records, name.c_str());
40 void ServiceSet::startService(const char *name)
43 ServiceRecord *record = loadServiceRecord(name);
48 void ServiceSet::stopService(const std::string & name)
50 ServiceRecord *record = findService(name);
51 if (record != nullptr) {
56 // Called when a service has actually stopped.
57 void ServiceRecord::stopped()
59 service_state = SVC_STOPPED;
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();
67 service_set->service_inactive(this);
69 // TODO inform listeners.
70 if (desired_state == SVC_STARTED) {
71 // Desired state is "started".
76 void ServiceRecord::process_child_callback(struct ev_loop *loop, ev_child *w, int revents)
78 ServiceRecord *sr = (ServiceRecord *) w->data;
81 ev_child_stop(ev_default_loop(EVFLAG_AUTO), &sr->child_listener);
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.
88 if (sr->service_type == SVC_PROCESS) {
89 // TODO log non-zero rstatus?
90 if (sr->service_state == SVC_STOPPING) {
97 if (sr->auto_restart && sr->service_set->get_auto_restart()) {
101 else { // SVC_SCRIPTED
102 if (sr->service_state == SVC_STOPPING) {
103 if (w->rstatus == 0) {
108 // ??? failed to stop!
109 // For now just pretend we stopped, so that any dependencies
114 else { // SVC_STARTING
115 if (w->rstatus == 0) {
120 sr->failed_to_start();
126 void ServiceRecord::start()
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
136 desired_state = SVC_STARTED;
138 if (service_state != SVC_STOPPED) {
139 // Either we need do nothing (service is already started/starting)
140 // or the service is currently being stopped and we must wait for
145 // Service state is SVC_STOPPED. Start the service.
147 // First, start dependencies
148 bool all_deps_started = true;
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
152 if ((*i)->service_state != SVC_STARTED || (*i)->force_stop) {
153 all_deps_started = false;
158 if (! all_deps_started) {
159 // The dependencies will notify this service once they've started.
163 // Actually start this service.
164 service_state = SVC_STARTING;
165 service_set->service_active(this);
167 if (service_type == SVC_PROCESS) {
168 bool start_success = start_ps_process();
177 // Script-controlled service
178 bool start_success = start_ps_process(std::vector<std::string>(1, "start"));
179 if (! start_success) {
185 void ServiceRecord::started()
187 service_state = SVC_STARTED;
188 // TODO - inform listeners
190 if (desired_state == SVC_STARTED) {
191 // Start any dependents whose desired state is SVC_STARTED:
192 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
193 if ((*i)->desired_state == SVC_STARTED) {
203 void ServiceRecord::failed_to_start()
205 service_state = SVC_STOPPED;
206 desired_state = SVC_STOPPED;
207 service_set->service_inactive(this);
209 // TODO - inform listeners of failure
210 // Cancel start of dependents:
211 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
212 if ((*i)->desired_state == SVC_STARTED) {
213 (*i)->failed_dependency();
218 bool ServiceRecord::start_ps_process()
220 // BIG FAT NOTE: We rely on linux semantics of vfork() here.
222 // * Parent process execution is suspended until the forked child
223 // successfully exec's another program, or it exits
224 // * Memory is shared between the two processes until exec()
226 // Both of the above mean that we can determine in the parent process
227 // whether or not the exec succeeded. If vfork instead is implemented
228 // as an alias of fork, it will look like the exec always succeeded.
231 volatile int exec_status = 0;
232 pid_t forkpid = vfork();
235 // ev_default_destroy(); // won't need that on this side, free up fds.
236 // Hmm. causes segfault. Of course. Memory is shared due to vfork.
238 // Re-set stdin, stdout, stderr
239 close(0); close(1); close(2);
240 string logfile = this->logfile;
241 if (logfile.length() == 0) {
242 logfile = "/dev/null";
245 if (open("/dev/null", O_RDONLY) == 0) {
246 // stdin = 0. That's what we should have; proceed with opening
247 // stdout and stderr.
248 open(logfile.c_str(), O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
252 const char * pname = program_name.c_str();
253 char const * args[2] = { pname, 0 };
254 execvp(pname, (char ** const) args);
255 // If we got here, the exec failed
260 // Parent process - we only reach here once the exec() above
261 // has succeeded, or _exit() above was called (because vfork()
262 // suspends the parent until either of those occurs).
263 if (exec_status == 0) {
267 // Add a process listener so we can detect when the
269 ev_child_init(&child_listener, process_child_callback, pid, 0);
270 child_listener.data = this;
271 ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
273 service_state = SVC_STARTED;
282 return start_ps_process(std::vector<std::string>());
286 bool ServiceRecord::start_ps_process(const std::vector<std::string> &pargs)
288 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
289 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
290 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
291 // is written to the pipe, and the parent can read it.
297 if (pipe2(pipefd, O_CLOEXEC)) {
302 // TODO make sure pipefd's are not 0/1/2 (STDIN/OUT/ERR) - if they are, dup them
303 // until they are not.
305 pid_t forkpid = fork();
315 ev_default_destroy(); // won't need that on this side, free up fds.
317 // Re-set stdin, stdout, stderr
318 close(0); close(1); close(2);
319 string logfile = this->logfile;
320 if (logfile.length() == 0) {
321 logfile = "/dev/null";
324 // TODO rethink this logic. If we open it at not-0, shouldn't we just dup it to 0?:
325 if (open("/dev/null", O_RDONLY) == 0) {
326 // stdin = 0. That's what we should have; proceed with opening
327 // stdout and stderr.
328 open(logfile.c_str(), O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
332 // Tokenize the command, and add additional arguments from pargs:
333 vector<string> progAndArgs = tokenize(program_name);
334 progAndArgs.insert(progAndArgs.end(), pargs.begin(), pargs.end());
336 const char * pname = progAndArgs[0].c_str();
337 const char ** args = new const char *[progAndArgs.size() + 1];
339 for (std::vector<std::string>::size_type i = 0; i < progAndArgs.size(); i++) {
340 args[i] = progAndArgs[i].c_str();
342 args[progAndArgs.size()] = nullptr;
344 execvp(pname, (char ** const) args);
346 // If we got here, the exec failed:
347 int exec_status = errno;
348 write(pipefd[1], &exec_status, sizeof(int));
352 // Parent process - we only reach here once the exec() above
353 // has succeeded, or _exit() above was called (because vfork()
354 // suspends the parent until either of those occurs).
356 close(pipefd[1]); // close the 'other end' fd
359 if (read(pipefd[0], &exec_status, sizeof(int)) == 0) {
360 // pipe closed; success
363 // Add a process listener so we can detect when the
365 ev_child_init(&child_listener, process_child_callback, pid, 0);
366 child_listener.data = this;
367 ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
383 // Mark this and all dependent services as force-stopped.
384 void ServiceRecord::forceStop()
388 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
393 // A dependency of this service failed to start.
394 void ServiceRecord::failed_dependency()
396 // TODO notify listeners
397 desired_state = SVC_STOPPED;
399 // Presumably, we were starting. So now we're not.
400 service_state = SVC_STOPPED;
402 // Notify dependents of this service also
403 for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
404 if ((*i)->desired_state == SVC_STARTED) {
405 (*i)->failed_dependency();
410 void ServiceRecord::dependentStopped()
412 if (desired_state == SVC_STOPPED || force_stop) {
413 bool all_deps_stopped = true;
414 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
415 if ((*i)->service_state != SVC_STOPPED) {
416 all_deps_stopped = false;
421 if (all_deps_stopped) {
427 void ServiceRecord::stop()
429 if ((service_state == SVC_STOPPING || service_state == SVC_STOPPED)
430 && desired_state == SVC_STARTED) {
431 // The service *was* stopped/stopping, but it was going to restart.
432 // Now, we'll cancel the restart.
433 // TODO inform listeners waiting for start of cancellation
436 desired_state = SVC_STOPPED;
438 if (service_state != SVC_STARTED) {
439 // If we're starting we need to wait for that to complete.
440 // If we're already stopping/stopped there's nothing to do.
444 // Make sure all dependents have stopped.
446 bool all_deps_stopped = true;
447 for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
448 if ((*i)->service_state != SVC_STOPPED) {
449 all_deps_stopped = false;
454 if (! all_deps_stopped) {
455 // The dependents will notify this service once they've stopped.
459 // Ok, dependents have stopped. We can stop ourselves.
463 // Dependency stopped or is stopping; we must stop too.
464 void ServiceRecord::stopping()
466 service_state = SVC_STOPPING;
468 if (service_type == SVC_PROCESS) {
470 // The process is still kicking on - must actually kill it.
472 // Now we wait; the rest is done in process_child_callback
475 // The process is already dead.
481 start_ps_process(std::vector<string>(1, "stop"));
485 void ServiceSet::service_active(ServiceRecord *sr)
490 void ServiceSet::service_inactive(ServiceRecord *sr)