4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 \brief Daemon non-inline non-template implementation */
30 #include <sys/types.h>
39 #include <boost/algorithm/string/predicate.hpp>
40 #include <boost/algorithm/string/trim.hpp>
41 #include "../Exception.hh"
42 #include "../membind.hh"
44 //#include "Daemon.mpp"
46 ///////////////////////////////cc.p////////////////////////////////////////
48 #define LIBC_CALL(fn, args) if (fn args < 0) throw SystemException(#fn "()")
49 #define LIBC_CALL_RV(var, fn, args) int var (fn args); if (var < 0) throw SystemException(#fn "()")
51 ///////////////////////////////////////////////////////////////////////////
54 prefix_ senf::Daemon::~Daemon()
56 if (! pidfile_.empty())
57 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
60 prefix_ void senf::Daemon::daemonize(bool v)
65 prefix_ bool senf::Daemon::daemon()
70 prefix_ int senf::Daemon::argc() {
74 prefix_ char const ** senf::Daemon::argv() {
78 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
81 case StdOut : stdoutLog_ = path; break;
82 case StdErr : stderrLog_ = path; break;
83 case Both : stdoutLog_ = path; stderrLog_ = path; break;
88 prefix_ void senf::Daemon::openLog()
91 if (! stdoutLog_.empty()) {
92 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
94 throw SystemException("::open()");
97 if (stderrLog_ == stdoutLog_)
99 else if (! stderrLog_.empty()) {
100 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
102 throw SystemException("::open()");
107 prefix_ void senf::Daemon::pidFile(std::string const & f)
113 bool signaled (false);
119 prefix_ void senf::Daemon::detach()
121 if (daemonize_ && ! detached_) {
123 // To ensure all data is written to the console log file in the correct order, we suspend
124 // execution here until the parent process tells us to continue via SIGUSR1: We block
125 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
126 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
127 // SIGUSR1 and reinstall the old signal mask and action.
130 ::sigemptyset(&usrsig);
131 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
132 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
133 struct ::sigaction oldact;
134 struct ::sigaction usract;
135 ::memset(&usract, 0, sizeof(usract));
136 usract.sa_handler = &waitusr;
137 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
138 ::sigset_t waitsig (oldsig);
139 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
141 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
142 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
143 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
144 LIBC_CALL( ::close, (nul) );
148 ::sigsuspend(&waitsig);
150 throw SystemException("::sigsuspend()");
153 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
154 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
161 /* Purposely *not* derived from std::exception */
162 struct DaemonExitException {
163 DaemonExitException(unsigned c) : code(c) {}
168 prefix_ void senf::Daemon::exit(unsigned code)
170 throw DaemonExitException(code);
173 prefix_ int senf::Daemon::start(int argc, char const ** argv)
185 if (! pidfile_.empty() && ! pidfileCreate()) {
186 std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?"
193 catch (DaemonExitException & e) {
199 catch (std::exception & e) {
200 std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
204 std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
213 ////////////////////////////////////////
216 prefix_ senf::Daemon::Daemon()
217 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
221 ////////////////////////////////////////
224 prefix_ void senf::Daemon::configure()
226 for (int i (1); i<argc_; ++i) {
227 if (argv_[i] == std::string("--no-daemon"))
229 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
230 std::string arg (std::string(argv_[i]), 14u);
231 std::string::size_type komma (arg.find(','));
232 if (komma == std::string::npos) {
234 if (arg == std::string("none")) consoleLog("");
235 else if (!arg.empty()) consoleLog(arg);
237 std::string arg1 (arg,0,komma);
238 std::string arg2 (arg,komma+1);
241 if (arg1 == std::string("none")) consoleLog("",StdOut);
242 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
243 if (arg2 == std::string("none")) consoleLog("",StdErr);
244 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
247 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
248 pidFile(std::string(std::string(argv_[i]), 11u));
252 prefix_ void senf::Daemon::main()
259 prefix_ void senf::Daemon::init()
262 prefix_ void senf::Daemon::run()
265 prefix_ void senf::Daemon::fork()
270 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
271 LIBC_CALL( ::dup2, (nul, 0) );
272 LIBC_CALL( ::close, (nul) );
273 LIBC_CALL( ::pipe, (coutpipe) );
274 LIBC_CALL( ::pipe, (cerrpipe) );
276 // We need to block the SIGCHLD signal here so we don't miss it, if the child
280 ::sigemptyset(&cldsig);
281 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
282 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
284 LIBC_CALL_RV( pid, ::fork, () );
289 LIBC_CALL( ::dup2, (coutpipe[1],1) );
290 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
291 LIBC_CALL( ::close, (coutpipe[0]) );
292 LIBC_CALL( ::close, (coutpipe[1]) );
293 LIBC_CALL( ::close, (cerrpipe[0]) );
294 LIBC_CALL( ::close, (cerrpipe[1]) );
295 LIBC_CALL( ::setsid, () );
296 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
300 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
303 LIBC_CALL( ::close, (coutpipe[1]) );
304 LIBC_CALL( ::close, (cerrpipe[1]) );
306 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
312 prefix_ bool senf::Daemon::pidfileCreate()
314 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
315 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
316 // was some race condition, probably over NFS.
318 std::string tempname;
321 char hostname[HOST_NAME_MAX+1];
322 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
323 hostname[HOST_NAME_MAX] = 0;
324 std::stringstream tempname_s;
325 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
326 tempname = tempname_s.str();
331 std::ofstream pidf (tempname.c_str());
332 pidf << ::getpid() << std::endl;
335 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
337 throw SystemException("::link()");
341 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
342 LIBC_CALL( ::unlink, (tempname.c_str()) );
343 return s.st_nlink == 2;
346 // pidfile exists. Check, whether the pid in the pidfile still exists.
349 std::ifstream pidf (pidfile_.c_str());
350 if ( ! (pidf >> old_pid)
352 || ::kill(old_pid, 0) >= 0
357 // If we reach this point, the pid file exists but the process mentioned within the
358 // pid file does *not* exists. We assume, the pid file to be stale.
360 // I hope, the following procedure is without race condition: We remove our generated
361 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
362 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
363 // must have already created his hardlink. We then truncate the file and write our pid.
365 LIBC_CALL( ::unlink, (tempname.c_str() ));
366 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
367 if (errno != ENOENT) throw SystemException("::link()");
368 // Hmm ... the pidfile mysteriously disappeared ... try again.
374 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
375 if (s.st_nlink != 2) {
376 LIBC_CALL( ::unlink, (tempname.c_str()) );
382 std::ofstream pidf (tempname.c_str());
383 pidf << ::getpid() << std::endl;
386 LIBC_CALL( ::unlink, (tempname.c_str()) );
392 ///////////////////////////////////////////////////////////////////////////
393 // senf::detail::DaemonWatcher
395 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
396 int stdout, int stderr)
397 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
398 stderr_(stderr), sigChld_(false),
399 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
400 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
402 coutForwarder_.addTarget(1);
404 coutForwarder_.addTarget(stdout_);
405 cerrForwarder_.addTarget(2);
407 cerrForwarder_.addTarget(stderr_);
410 prefix_ void senf::detail::DaemonWatcher::run()
412 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
413 Scheduler::instance().process();
416 ////////////////////////////////////////
419 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
422 case 1 : coutpipe_ = -1; break;
423 case 2 : cerrpipe_ = -1; break;
426 if (coutpipe_ == -1 && cerrpipe_ == -1) {
428 childDied(); // does not return
429 if (::kill(childPid_, SIGUSR1) < 0)
430 if (errno != ESRCH) throw SystemException("::kill()");
431 Scheduler::instance().timeout(
432 Scheduler::instance().eventTime() + ClockService::seconds(1),
433 senf::membind(&DaemonWatcher::childOk, this));
437 prefix_ void senf::detail::DaemonWatcher::sigChld()
440 if (coutpipe_ == -1 && cerrpipe_ == -1)
441 childDied(); // does not return
444 prefix_ void senf::detail::DaemonWatcher::childDied()
447 if (::waitpid(childPid_,&status,0) < 0) throw SystemException("::waitpid()");
448 if (WIFSIGNALED(status)) {
449 ::signal(WTERMSIG(status),SIG_DFL);
450 ::kill(::getpid(), WTERMSIG(status));
451 // should not be reached
454 if (WEXITSTATUS(status) == 0)
456 ::_exit(WEXITSTATUS(status));
459 prefix_ void senf::detail::DaemonWatcher::childOk()
461 Scheduler::instance().terminate();
464 ///////////////////////////////////////////////////////////////////////////
465 // senf::detail::DaemonWatcher::Forwarder
467 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
470 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
474 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
477 Scheduler::instance().remove(src_);
479 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
480 if (i->offset >= buffer_.size())
481 Scheduler::instance().remove(i->fd);
484 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
486 Target target = { fd, 0 };
487 targets_.push_back(target);
490 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
496 n = ::read(src_,buf,1024);
498 if (errno != EINTR) throw SystemException("::read()");
505 Scheduler::instance().remove(src_);
512 if (targets_.empty())
515 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
516 if (i->offset >= buffer_.size())
517 Scheduler::instance().add( i->fd,
518 boost::bind(&Forwarder::writeData, this, _1, i),
519 Scheduler::EV_WRITE );
521 buffer_.insert(buffer_.end(), buf, buf+n);
524 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
525 Targets::iterator target)
527 if (event != Scheduler::EV_WRITE) {
528 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
529 Scheduler::instance().remove(target->fd);
530 targets_.erase(target);
531 if (targets_.empty() && src_ == -1)
537 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
538 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
540 int w (::write(target->fd, buf, n));
542 if (errno != EINTR) throw SystemException("::write()");
547 n = std::min_element(
548 targets_.begin(), targets_.end(),
549 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
551 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
553 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
556 if (target->offset >= buffer_.size())
557 Scheduler::instance().remove(target->fd);
558 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
565 ///////////////////////////////cc.e////////////////////////////////////////
567 //#include "Daemon.mpp"
573 // comment-column: 40
574 // c-file-style: "senf"
575 // indent-tabs-mode: nil
576 // ispell-local-dictionary: "american"
577 // compile-command: "scons -u test"