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 <boost/format.hpp>
42 #include "../Exception.hh"
43 #include "../membind.hh"
45 //#include "Daemon.mpp"
47 ///////////////////////////////cc.p////////////////////////////////////////
49 #define LIBC_CALL(fn, args) if (fn args < 0) throw SystemException(#fn "()")
50 #define LIBC_CALL_RV(var, fn, args) int var (fn args); if (var < 0) throw SystemException(#fn "()")
52 ///////////////////////////////////////////////////////////////////////////
55 prefix_ senf::Daemon::~Daemon()
57 if (! pidfile_.empty()) {
59 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
60 } catch (SystemException e) {
61 e << "; could not unlink " << pidfile_.c_str();
67 prefix_ void senf::Daemon::daemonize(bool v)
72 prefix_ bool senf::Daemon::daemon()
77 prefix_ int senf::Daemon::argc() {
81 prefix_ char const ** senf::Daemon::argv() {
85 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
88 case StdOut : stdoutLog_ = path; break;
89 case StdErr : stderrLog_ = path; break;
90 case Both : stdoutLog_ = path; stderrLog_ = path; break;
95 prefix_ void senf::Daemon::openLog()
98 if (! stdoutLog_.empty()) {
99 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
101 throw SystemException("::open()");
104 if (stderrLog_ == stdoutLog_)
106 else if (! stderrLog_.empty()) {
107 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
109 throw SystemException("::open()");
114 prefix_ void senf::Daemon::pidFile(std::string const & f)
120 bool signaled (false);
126 prefix_ void senf::Daemon::detach()
128 if (daemonize_ && ! detached_) {
130 // To ensure all data is written to the console log file in the correct order, we suspend
131 // execution here until the parent process tells us to continue via SIGUSR1: We block
132 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
133 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
134 // SIGUSR1 and reinstall the old signal mask and action.
137 ::sigemptyset(&usrsig);
138 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
139 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
140 struct ::sigaction oldact;
141 struct ::sigaction usract;
142 ::memset(&usract, 0, sizeof(usract));
143 usract.sa_handler = &waitusr;
144 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
145 ::sigset_t waitsig (oldsig);
146 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
148 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
149 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
150 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
151 LIBC_CALL( ::close, (nul) );
155 ::sigsuspend(&waitsig);
157 throw SystemException("::sigsuspend()");
160 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
161 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
168 /* Purposely *not* derived from std::exception */
169 struct DaemonExitException {
170 DaemonExitException(unsigned c) : code(c) {}
175 prefix_ void senf::Daemon::exit(unsigned code)
177 throw DaemonExitException(code);
180 prefix_ int senf::Daemon::start(int argc, char const ** argv)
192 if (! pidfile_.empty() && ! pidfileCreate()) {
193 std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?"
200 catch (DaemonExitException & e) {
206 catch (std::exception & e) {
207 std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
211 std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
220 ////////////////////////////////////////
223 prefix_ senf::Daemon::Daemon()
224 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
228 ////////////////////////////////////////
231 prefix_ void senf::Daemon::configure()
233 for (int i (1); i<argc_; ++i) {
234 if (argv_[i] == std::string("--no-daemon"))
236 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
237 std::string arg (std::string(argv_[i]), 14u);
238 std::string::size_type komma (arg.find(','));
239 if (komma == std::string::npos) {
241 if (arg == std::string("none")) consoleLog("");
242 else if (!arg.empty()) consoleLog(arg);
244 std::string arg1 (arg,0,komma);
245 std::string arg2 (arg,komma+1);
248 if (arg1 == std::string("none")) consoleLog("",StdOut);
249 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
250 if (arg2 == std::string("none")) consoleLog("",StdErr);
251 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
254 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
255 pidFile(std::string(std::string(argv_[i]), 11u));
259 prefix_ void senf::Daemon::main()
266 prefix_ void senf::Daemon::init()
269 prefix_ void senf::Daemon::run()
272 prefix_ void senf::Daemon::fork()
277 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
278 LIBC_CALL( ::dup2, (nul, 0) );
279 LIBC_CALL( ::close, (nul) );
280 LIBC_CALL( ::pipe, (coutpipe) );
281 LIBC_CALL( ::pipe, (cerrpipe) );
283 // We need to block the SIGCHLD signal here so we don't miss it, if the child
287 ::sigemptyset(&cldsig);
288 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
289 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
291 LIBC_CALL_RV( pid, ::fork, () );
296 LIBC_CALL( ::dup2, (coutpipe[1],1) );
297 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
298 LIBC_CALL( ::close, (coutpipe[0]) );
299 LIBC_CALL( ::close, (coutpipe[1]) );
300 LIBC_CALL( ::close, (cerrpipe[0]) );
301 LIBC_CALL( ::close, (cerrpipe[1]) );
302 LIBC_CALL( ::setsid, () );
303 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
307 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
310 LIBC_CALL( ::close, (coutpipe[1]) );
311 LIBC_CALL( ::close, (cerrpipe[1]) );
313 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
319 prefix_ bool senf::Daemon::pidfileCreate()
321 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
322 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
323 // was some race condition, probably over NFS.
325 std::string tempname;
326 boost::format linkErrorFormat("; could not link \"%1%\" to \"%2%\"");
329 char hostname[HOST_NAME_MAX+1];
330 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
331 hostname[HOST_NAME_MAX] = 0;
332 std::stringstream tempname_s;
333 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
334 tempname = tempname_s.str();
339 std::ofstream pidf (tempname.c_str());
340 pidf << ::getpid() << std::endl;
343 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
345 throw SystemException("::link()")
346 << linkErrorFormat % pidfile_.c_str() % tempname.c_str();
350 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
351 LIBC_CALL( ::unlink, (tempname.c_str()) );
352 return s.st_nlink == 2;
355 // pidfile exists. Check, whether the pid in the pidfile still exists.
358 std::ifstream pidf (pidfile_.c_str());
359 if ( ! (pidf >> old_pid)
361 || ::kill(old_pid, 0) >= 0
366 // If we reach this point, the pid file exists but the process mentioned within the
367 // pid file does *not* exists. We assume, the pid file to be stale.
369 // I hope, the following procedure is without race condition: We remove our generated
370 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
371 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
372 // must have already created his hardlink. We then truncate the file and write our pid.
374 LIBC_CALL( ::unlink, (tempname.c_str() ));
375 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
377 throw SystemException("::link()")
378 << linkErrorFormat % tempname.c_str() % pidfile_.c_str();
379 // Hmm ... the pidfile mysteriously disappeared ... try again.
385 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
386 if (s.st_nlink != 2) {
387 LIBC_CALL( ::unlink, (tempname.c_str()) );
393 std::ofstream pidf (tempname.c_str());
394 pidf << ::getpid() << std::endl;
397 LIBC_CALL( ::unlink, (tempname.c_str()) );
403 ///////////////////////////////////////////////////////////////////////////
404 // senf::detail::DaemonWatcher
406 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
407 int stdout, int stderr)
408 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
409 stderr_(stderr), sigChld_(false),
410 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
411 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
413 coutForwarder_.addTarget(1);
415 coutForwarder_.addTarget(stdout_);
416 cerrForwarder_.addTarget(2);
418 cerrForwarder_.addTarget(stderr_);
421 prefix_ void senf::detail::DaemonWatcher::run()
423 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
424 Scheduler::instance().process();
427 ////////////////////////////////////////
430 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
433 case 1 : coutpipe_ = -1; break;
434 case 2 : cerrpipe_ = -1; break;
437 if (coutpipe_ == -1 && cerrpipe_ == -1) {
439 childDied(); // does not return
440 if (::kill(childPid_, SIGUSR1) < 0)
441 if (errno != ESRCH) throw SystemException("::kill()");
442 Scheduler::instance().timeout(
443 Scheduler::instance().eventTime() + ClockService::seconds(1),
444 senf::membind(&DaemonWatcher::childOk, this));
448 prefix_ void senf::detail::DaemonWatcher::sigChld()
451 if (coutpipe_ == -1 && cerrpipe_ == -1)
452 childDied(); // does not return
455 prefix_ void senf::detail::DaemonWatcher::childDied()
458 if (::waitpid(childPid_,&status,0) < 0) throw SystemException("::waitpid()");
459 if (WIFSIGNALED(status)) {
460 ::signal(WTERMSIG(status),SIG_DFL);
461 ::kill(::getpid(), WTERMSIG(status));
462 // should not be reached
465 if (WEXITSTATUS(status) == 0)
467 ::_exit(WEXITSTATUS(status));
470 prefix_ void senf::detail::DaemonWatcher::childOk()
472 Scheduler::instance().terminate();
475 ///////////////////////////////////////////////////////////////////////////
476 // senf::detail::DaemonWatcher::Forwarder
478 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
481 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
485 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
488 Scheduler::instance().remove(src_);
490 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
491 if (i->offset >= buffer_.size())
492 Scheduler::instance().remove(i->fd);
495 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
497 Target target = { fd, 0 };
498 targets_.push_back(target);
501 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
507 n = ::read(src_,buf,1024);
509 if (errno != EINTR) throw SystemException("::read()");
516 Scheduler::instance().remove(src_);
523 if (targets_.empty())
526 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
527 if (i->offset >= buffer_.size())
528 Scheduler::instance().add( i->fd,
529 boost::bind(&Forwarder::writeData, this, _1, i),
530 Scheduler::EV_WRITE );
532 buffer_.insert(buffer_.end(), buf, buf+n);
535 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
536 Targets::iterator target)
538 if (event != Scheduler::EV_WRITE) {
539 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
540 Scheduler::instance().remove(target->fd);
541 targets_.erase(target);
542 if (targets_.empty() && src_ == -1)
548 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
549 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
551 int w (::write(target->fd, buf, n));
553 if (errno != EINTR) throw SystemException("::write()");
558 n = std::min_element(
559 targets_.begin(), targets_.end(),
560 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
562 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
564 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
567 if (target->offset >= buffer_.size())
568 Scheduler::instance().remove(target->fd);
569 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
576 ///////////////////////////////cc.e////////////////////////////////////////
578 //#include "Daemon.mpp"
584 // comment-column: 40
585 // c-file-style: "senf"
586 // indent-tabs-mode: nil
587 // ispell-local-dictionary: "american"
588 // compile-command: "scons -u test"